code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/** * @license AngularJS v1.0.0 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc overview * @name ngSanitize * @description */ /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ /** * @ngdoc service * @name ngSanitize.$sanitize * @function * * @description * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * * @param {string} html Html input. * @returns {string} Sanitized html. * * @example <doc:example module="ngSanitize"> <doc:source> <script> function Ctrl($scope) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; } </script> <div ng-controller="Ctrl"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="html-filter"> <td>html filter</td> <td> <pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> <tr id="html-unsafe-filter"> <td>unsafe html filter</td> <td><pre>&lt;div ng-bind-html-unsafe="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html-unsafe="snippet"></div></td> </tr> </table> </div> </doc:source> <doc:scenario> it('should sanitize the html snippet ', function() { expect(using('#html-filter').element('div').html()). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should escape snippet without any filter', function() { expect(using('#escaped-html').element('div').html()). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should inline raw snippet if filtered as unsafe', function() { expect(using('#html-unsafe-filter').element("div").html()). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should update', function() { input('snippet').enter('new <b>text</b>'); expect(using('#html-filter').binding('snippet')).toBe('new <b>text</b>'); expect(using('#escaped-html').element('div').html()).toBe("new &lt;b&gt;text&lt;/b&gt;"); expect(using('#html-unsafe-filter').binding("snippet")).toBe('new <b>text</b>'); }); </doc:scenario> </doc:example> */ var $sanitize = function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf)); return buf.join(''); }; // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/, NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = makeMap("area,br,col,hr,img,wbr"); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), optionalEndTagInlineElements = makeMap("rp,rt"), optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article,aside," + "blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6," + "header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b,bdi,bdo," + "big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small," + "span,strike,strong,sub,sup,time,tt,u,var")); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); var validAttrs = angular.extend({}, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); function makeMap(str) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) obj[items[i]] = true; return obj; } /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function() { return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { index = html.indexOf("-->"); if ( index >= 0 ) { if (handler.comment) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if (handler.chars) handler.chars( decodeEntities(text) ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text. replace(COMMENT_REGEXP, "$1"). replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars( decodeEntities(text) ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw "Parse Error: " + html; } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = angular.lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = voidElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) { var value = doubleQuotedValue || singleQoutedValue || unqoutedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start( tagName, attrs, unary ); } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = angular.lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) if (handler.end) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } } /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ var hiddenPre=document.createElement("pre"); function decodeEntities(value) { hiddenPre.innerHTML=value.replace(/</g,"&lt;"); return hiddenPre.innerText || hiddenPre.textContent || ''; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf){ var ignore = false; var out = angular.bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = angular.lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] == true) { out('<'); out(tag); angular.forEach(attrs, function(value, key){ var lkey=angular.lowercase(key); if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = angular.lowercase(tag); if (!ignore && validElements[tag] == true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(encodeEntities(chars)); } } }; } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).value('$sanitize', $sanitize); /** * @ngdoc directive * @name ngSanitize.directive:ngBindHtml * * @description * Creates a binding that will sanitize the result of evaluating the `expression` with the * {@link ngSanitize.$sanitize $sanitize} service and innerHTML the result into the current element. * * See {@link ngSanitize.$sanitize $sanitize} docs for examples. * * @element ANY * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. */ angular.module('ngSanitize').directive('ngBindHtml', ['$sanitize', function($sanitize) { return function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBindHtml); scope.$watch(attr.ngBindHtml, function(value) { value = $sanitize(value); element.html(value || ''); }); }; }]); /** * @ngdoc filter * @name ngSanitize.filter:linky * @function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plain email address links. * * @param {string} text Input text. * @returns {string} Html-linkified text. * * @example <doc:example module="ngSanitize"> <doc:source> <script> function Ctrl($scope) { $scope.snippet = 'Pretty text with some links:\n'+ 'http://angularjs.org/,\n'+ 'mailto:us@somewhere.org,\n'+ 'another@somewhere.org,\n'+ 'and one more: ftp://127.0.0.1/.'; } </script> <div ng-controller="Ctrl"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet | linky"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </doc:source> <doc:scenario> it('should linkify the snippet with urls', function() { expect(using('#linky-filter').binding('snippet | linky')). toBe('Pretty text with some links:&#10;' + '<a href="http://angularjs.org/">http://angularjs.org/</a>,&#10;' + '<a href="mailto:us@somewhere.org">us@somewhere.org</a>,&#10;' + '<a href="mailto:another@somewhere.org">another@somewhere.org</a>,&#10;' + 'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.'); }); it ('should not linkify snippet without the linky filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("Pretty text with some links:\n" + "http://angularjs.org/,\n" + "mailto:us@somewhere.org,\n" + "another@somewhere.org,\n" + "and one more: ftp://127.0.0.1/."); }); it('should update', function() { input('snippet').enter('new http://link.'); expect(using('#linky-filter').binding('snippet | linky')). toBe('new <a href="http://link">http://link</a>.'); expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); }); </doc:scenario> </doc:example> */ angular.module('ngSanitize').filter('linky', function() { var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/, MAILTO_REGEXP = /^mailto:/; return function(text) { if (!text) return text; var match; var raw = text; var html = []; // TODO(vojta): use $sanitize instead var writer = htmlSanitizeWriter(html); var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/mailto then assume mailto if (match[2] == match[3]) url = 'mailto:' + url; i = match.index; writer.chars(raw.substr(0, i)); writer.start('a', {href:url}); writer.chars(match[0].replace(MAILTO_REGEXP, '')); writer.end('a'); raw = raw.substring(i + match[0].length); } writer.chars(raw); return html.join(''); }; }); })(window, window.angular);
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/angular-1.0.0/angular-sanitize-1.0.0.js
JavaScript
asf20
17,350
/** * @license AngularJS v1.0.0 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ ( /** * @ngdoc interface * @name angular.Module * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } return ensure(ensure(window, 'angular', Object), 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @description * * The `angular.module` is a global place for creating and registering Angular modules. All * modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * * # Module * * A module is a collocation of services, directives, filters, and configure information. Module * is used to configure the {@link AUTO.$injector $injector}. * * <pre> * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { 'use strict'; * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * </pre> * * Then you can create an injector and load your modules like this: * * <pre> * var injector = angular.injector(['ng', 'MyModule']) * </pre> * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the * the module is being retrieved for further configuration. * @param {Function} configFn Option configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw Error('No module: ' + name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @propertyOf angular.Module * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @propertyOf angular.Module * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @methodOf angular.Module * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the service. * @description * See {@link AUTO.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @methodOf angular.Module * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link AUTO.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @methodOf angular.Module * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link AUTO.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @methodOf angular.Module * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link AUTO.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @methodOf angular.Module * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link AUTO.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#filter * @methodOf angular.Module * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @methodOf angular.Module * @param {string} name Controller name. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @methodOf angular.Module * @param {string} name directive name * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider.directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @methodOf angular.Module * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @methodOf angular.Module * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which needs to be performed when the injector with * with the current module is finished loading. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; } } }); }; }); } )(window); /** * Closure compiler type information * * @typedef { { * requires: !Array.<string>, * invokeQueue: !Array.<Array.<*>>, * * service: function(string, Function):angular.Module, * factory: function(string, Function):angular.Module, * value: function(string, *):angular.Module, * * filter: function(string, Function):angular.Module, * * init: function(Function):angular.Module * } } */ angular.Module;
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/angular-1.0.0/angular-loader-1.0.0.js
JavaScript
asf20
9,113
/** * @license AngularJS v1.0.0 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window) { 'use strict'; /** * JSTestDriver adapter for angular scenario tests * * Example of jsTestDriver.conf for running scenario tests with JSTD: <pre> server: http://localhost:9877 load: - lib/angular-scenario.js - lib/jstd-scenario-adapter-config.js - lib/jstd-scenario-adapter.js # your test files go here # proxy: - {matcher: "/your-prefix/*", server: "http://localhost:8000/"} </pre> * * For more information on how to configure jstd proxy, see {@link http://code.google.com/p/js-test-driver/wiki/Proxy} * Note the order of files - it's important ! * * Example of jstd-scenario-adapter-config.js <pre> var jstdScenarioAdapter = { relativeUrlPrefix: '/your-prefix/' }; </pre> * * Whenever you use <code>browser().navigateTo('relativeUrl')</code> in your scenario test, the relativeUrlPrefix will be prepended. * You have to configure this to work together with JSTD proxy. * * Let's assume you are using the above configuration (jsTestDriver.conf and jstd-scenario-adapter-config.js): * Now, when you call <code>browser().navigateTo('index.html')</code> in your scenario test, the browser will open /your-prefix/index.html. * That matches the proxy, so JSTD will proxy this request to http://localhost:8000/index.html. */ /** * Custom type of test case * * @const * @see jstestdriver.TestCaseInfo */ var SCENARIO_TYPE = 'scenario'; /** * Plugin for JSTestDriver * Connection point between scenario's jstd output and jstestdriver. * * @see jstestdriver.PluginRegistrar */ function JstdPlugin() { var nop = function() {}; this.reportResult = nop; this.reportEnd = nop; this.runScenario = nop; this.name = 'Angular Scenario Adapter'; /** * Called for each JSTD TestCase * * Handles only SCENARIO_TYPE test cases. There should be only one fake TestCase. * Runs all scenario tests (under one fake TestCase) and report all results to JSTD. * * @param {jstestdriver.TestRunConfiguration} configuration * @param {Function} onTestDone * @param {Function} onAllTestsComplete * @returns {boolean} True if this type of test is handled by this plugin, false otherwise */ this.runTestConfiguration = function(configuration, onTestDone, onAllTestsComplete) { if (configuration.getTestCaseInfo().getType() != SCENARIO_TYPE) return false; this.reportResult = onTestDone; this.reportEnd = onAllTestsComplete; this.runScenario(); return true; }; this.getTestRunsConfigurationFor = function(testCaseInfos, expressions, testRunsConfiguration) { testRunsConfiguration.push( new jstestdriver.TestRunConfiguration( new jstestdriver.TestCaseInfo( 'Angular Scenario Tests', function() {}, SCENARIO_TYPE), [])); return true; }; } /** * Singleton instance of the plugin * Accessed using closure by: * - jstd output (reports to this plugin) * - initScenarioAdapter (register the plugin to jstd) */ var plugin = new JstdPlugin(); /** * Initialise scenario jstd-adapter * (only if jstestdriver is defined) * * @param {Object} jstestdriver Undefined when run from browser (without jstd) * @param {Function} initScenarioAndRun Function that inits scenario and runs all the tests * @param {Object=} config Configuration object, supported properties: * - relativeUrlPrefix: prefix for all relative links when navigateTo() */ function initScenarioAdapter(jstestdriver, initScenarioAndRun, config) { if (jstestdriver) { // create and register ScenarioPlugin jstestdriver.pluginRegistrar.register(plugin); plugin.runScenario = initScenarioAndRun; /** * HACK (angular.scenario.Application.navigateTo) * * We need to navigate to relative urls when running from browser (without JSTD), * because we want to allow running scenario tests without creating its own virtual host. * For example: http://angular.local/build/docs/docs-scenario.html * * On the other hand, when running with JSTD, we need to navigate to absolute urls, * because of JSTD proxy. (proxy, because of same domain policy) * * So this hack is applied only if running with JSTD and change all relative urls to absolute. */ var appProto = angular.scenario.Application.prototype, navigateTo = appProto.navigateTo, relativeUrlPrefix = config && config.relativeUrlPrefix || '/'; appProto.navigateTo = function(url, loadFn, errorFn) { if (url.charAt(0) != '/' && url.charAt(0) != '#' && url != 'about:blank' && !url.match(/^https?/)) { url = relativeUrlPrefix + url; } return navigateTo.call(this, url, loadFn, errorFn); }; } } /** * Builds proper TestResult object from given model spec * * TODO(vojta) report error details * * @param {angular.scenario.ObjectModel.Spec} spec * @returns {jstestdriver.TestResult} */ function createTestResultFromSpec(spec) { var map = { success: 'PASSED', error: 'ERROR', failure: 'FAILED' }; return new jstestdriver.TestResult( spec.fullDefinitionName, spec.name, jstestdriver.TestResult.RESULT[map[spec.status]], spec.error || '', spec.line || '', spec.duration); } /** * Generates JSTD output (jstestdriver.TestResult) */ angular.scenario.output('jstd', function(context, runner, model) { model.on('SpecEnd', function(spec) { plugin.reportResult(createTestResultFromSpec(spec)); }); model.on('RunnerEnd', function() { plugin.reportEnd(); }); }); initScenarioAdapter(window.jstestdriver, angular.scenario.setUpAndRun, window.jstdScenarioAdapter); })(window);
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/angular-1.0.0/jstd-scenario-adapter-1.0.0.js
JavaScript
asf20
5,784
/** * @license AngularJS v1.0.0 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc overview * @name ngCookies */ angular.module('ngCookies', ['ng']). /** * @ngdoc object * @name ngCookies.$cookies * @requires $browser * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from * this object, new cookies are created/deleted at the end of current $eval. * * @example */ factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { var cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false, copy = angular.copy, isUndefined = angular.isUndefined; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) $rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. $rootScope.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { if (angular.isDefined(lastCookies[name])) { cookies[name] = lastCookies[name]; } else { delete cookies[name]; } } else if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }]). /** * @ngdoc object * @name ngCookies.$cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * @example */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name ngCookies.$cookieStore#get * @methodOf ngCookies.$cookieStore * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { return angular.fromJson($cookies[key]); }, /** * @ngdoc method * @name ngCookies.$cookieStore#put * @methodOf ngCookies.$cookieStore * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies[key] = angular.toJson(value); }, /** * @ngdoc method * @name ngCookies.$cookieStore#remove * @methodOf ngCookies.$cookieStore * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $cookies[key]; } }; }]); })(window, window.angular);
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/angular-1.0.0/angular-cookies-1.0.0.js
JavaScript
asf20
4,842
'use strict'; function UserCtrl($scope, backend) { $scope.user = null; $scope.login = function () { backend.user().then(function (response) { $scope.user = response.data; }); } $scope.login(); } function EditorCtrl($scope, $location, $routeParams, $timeout, editor, doc, autosaver) { console.log($routeParams); $scope.editor = editor; $scope.doc = doc; $scope.$on('saved', function (event) { $location.path('/edit/' + doc.resource_id); }); if ($routeParams.id) { editor.load($routeParams.id); } else { // New doc, but defer to next event cycle to ensure init $timeout(function () { editor.create(); }, 1); } } function ShareCtrl($scope, appId, doc) { /* var client = gapi.drive.share.ShareClient(appId); $scope.enabled = function() { return doc.resource_id != null; }; $scope.share = function() { client.setItemIds([doc.resource_id]); client.showSharingSettings(); } */ } function MenuCtrl($scope, $location, appId) { var onFilePicked = function (data) { $scope.$apply(function () { if (data.action == 'picked') { var id = data.docs[0].id; $location.path('/edit/' + id); } }); }; $scope.open = function () { var view = new google.picker.View(google.picker.ViewId.DOCS); view.setMimeTypes('text/plain'); var picker = new google.picker.PickerBuilder() .setAppId(appId) .addView(view) .setCallback(angular.bind(this, onFilePicked)) .build(); picker.setVisible(true); }; $scope.create = function () { this.editor.create(); }; $scope.save = function () { this.editor.save(true); } } function RenameCtrl($scope, doc) { $('#rename-dialog').on('show', function () { $scope.$apply(function () { $scope.newFileName = doc.info.title; }); }); $scope.save = function () { doc.info.title = $scope.newFileName; $('#rename-dialog').modal('hide'); }; } function AboutCtrl($scope, backend) { $('#about-dialog').on('show', function () { backend.about().then(function (result) { $scope.info = result.data; }); }); }
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/controllers.js
JavaScript
asf20
2,458
'use strict'; /* Filters */ angular.module('app.filters', []) .filter('saveStateFormatter', function () { return function (state) { if (state == EditorState.DIRTY) { return 'You have unsaved changes'; } else if (state == EditorState.SAVE) { return 'Saving...'; } else if (state == EditorState.LOAD) { return 'Loading...'; } else if (state == EditorState.READONLY) { return "Read only" } else { return 'All changes saved'; } }; }) .filter('bytes', function () { return function (bytes) { bytes = parseInt(bytes); if (isNaN(bytes)) { return "..."; } var units = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB']; var p = bytes > 0 ? Math.floor(Math.log(bytes) / Math.LN2 / 10) : 0; var u = Math.round(bytes / Math.pow(2, 10 * p)); return u + units[p]; } });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/filters.js
JavaScript
asf20
1,084
'use strict'; var module = angular.module('app.services', []); var ONE_HOUR_IN_MS = 1000 * 60 * 60; // Shared model for current document module.factory('doc', function ($rootScope) { var service = $rootScope.$new(true); service.dirty = false; service.lastSave = 0; service.timeSinceLastSave = function () { return new Date().getTime() - this.lastSave; }; service.$watch('info', function (newValue, oldValue) { service.dirty = true; }, true); service.$watch('info', function() { service.dirty = false; }); return service; }); module.factory('editor', function (doc, backend, $q, $rootScope, $log) { var editor = null; var EditSession = require("ace/edit_session").EditSession; var service = { loading:false, saving:false, rebind:function (element) { editor = ace.edit(element); }, snapshot:function () { doc.dirty = false; var data = angular.extend({}, doc.info); data.resource_id = doc.resource_id; if (doc.info.editable) { data.content = editor.getSession().getValue(); } return data; }, create:function () { $log.info("Creating new doc"); this.updateEditor({ content:'', labels:{ starred:false }, editable:true, title:'Untitled document', description:'', mimeType:'text/plain', resource_id:null }); }, load:function (id, reload) { $log.info("Loading resource", id, doc.resource_id); if (!reload && doc.info && id == doc.resource_id) { return $q.when(doc.info); } this.loading = true; return backend.load(id).then(angular.bind(this, function (result) { this.loading = false; this.updateEditor(result.data); $rootScope.$broadcast('loaded', doc.info); return result; }), angular.bind(this, function (result) { $log.warn("Error loading", result); this.loading = false; $rootScope.$broadcast('error', { action:'load', message:"An error occured while loading the file" }); return result; })); }, save:function (newRevision) { $log.info("Saving file", newRevision); if (this.saving || this.loading) { throw 'Save called from incorrect state'; } this.saving = true; var file = this.snapshot(); // Force revision if first save of the session newRevision = newRevision || doc.timeSinceLastSave() > ONE_HOUR_IN_MS; var promise = backend.save(file, newRevision); promise.then(angular.bind(this, function (result) { $log.info("Saved file", result); this.saving = false; doc.resource_id = result.data; doc.lastSave = new Date().getTime(); $rootScope.$broadcast('saved', doc.info); return doc.info; }), angular.bind(this, function (result) { this.saving = false; doc.dirty = true; $rootScope.$broadcast('error', { action:'save', message:"An error occured while saving the file" }); return result; })); return promise; }, updateEditor:function (fileInfo) { $log.info("Updating editor", fileInfo); var session = new EditSession(fileInfo.content); session.on('change', function () { doc.dirty = true; $rootScope.$apply(); }); fileInfo.content = null; doc.lastSave = 0; doc.info = fileInfo; doc.resource_id = fileInfo.id; editor.setSession(session); editor.setReadOnly(!doc.info.editable); editor.focus(); }, state:function () { if (this.loading) { return EditorState.LOAD; } else if (this.saving) { return EditorState.SAVE; } else if (doc.dirty) { return EditorState.DIRTY; } else if (!doc.info.editable) { return EditorState.READONLY; } return EditorState.CLEAN; } }; return service; }); module.factory('backend', function ($http, $log) { var jsonTransform = function (data, headers) { return angular.fromJson(data); }; var service = { user:function () { return $http.get('/user', {transformResponse:jsonTransform}); }, about:function () { return $http.get('/about', {transformResponse:jsonTransform}); }, load:function (id) { return $http.get('/svc', { transformResponse:jsonTransform, params:{ 'file_id':id } }); }, save:function (fileInfo, newRevision) { $log.info('Saving', fileInfo); return $http({ url:'/svc', method:fileInfo.resource_id ? 'PUT' : 'POST', headers:{ 'Content-Type':'application/json' }, params:{ 'newRevision':newRevision }, transformResponse:jsonTransform, data:JSON.stringify(fileInfo) }); } }; return service; }); module.factory('autosaver', function (editor, saveInterval, $timeout) { var saveFn = function () { if (editor.state() == EditorState.DIRTY) { editor.save(false); } }; var createTimeout = function () { return $timeout(saveFn, saveInterval).then(createTimeout); } return createTimeout(); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/services.js
JavaScript
asf20
7,185
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/tomorrow_night_blue', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-tomorrow-night-blue"; exports.cssText = "\ .ace-tomorrow-night-blue .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tomorrow-night-blue .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tomorrow-night-blue .ace_gutter {\ background: #022346;\ color: #7388b5;\ }\ \ .ace-tomorrow-night-blue .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tomorrow-night-blue .ace_scroller {\ background-color: #002451;\ }\ \ .ace-tomorrow-night-blue .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-tomorrow-night-blue .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-tomorrow-night-blue .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-tomorrow-night-blue .ace_marker-layer .ace_selection {\ background: #003F8E;\ }\ \ .ace-tomorrow-night-blue.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #002451;\ border-radius: 2px;\ }\ \ .ace-tomorrow-night-blue .ace_marker-layer .ace_step {\ background: rgb(127, 111, 19);\ }\ \ .ace-tomorrow-night-blue .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #404F7D;\ }\ \ .ace-tomorrow-night-blue .ace_marker-layer .ace_active_line {\ background: #00346E;\ }\ \ .ace-tomorrow-night-blue .ace_gutter_active_line {\ background-color: #022040;\ }\ \ .ace-tomorrow-night-blue .ace_marker-layer .ace_selected_word {\ border: 1px solid #003F8E;\ }\ \ .ace-tomorrow-night-blue .ace_invisible {\ color: #404F7D;\ }\ \ .ace-tomorrow-night-blue .ace_keyword, .ace-tomorrow-night-blue .ace_meta {\ color:#EBBBFF;\ }\ \ .ace-tomorrow-night-blue .ace_keyword.ace_operator {\ color:#99FFFF;\ }\ \ .ace-tomorrow-night-blue .ace_constant.ace_language {\ color:#FFC58F;\ }\ \ .ace-tomorrow-night-blue .ace_constant.ace_numeric {\ color:#FFC58F;\ }\ \ .ace-tomorrow-night-blue .ace_constant.ace_other {\ color:#FFFFFF;\ }\ \ .ace-tomorrow-night-blue .ace_invalid {\ color:#FFFFFF;\ background-color:#F99DA5;\ }\ \ .ace-tomorrow-night-blue .ace_invalid.ace_deprecated {\ color:#FFFFFF;\ background-color:#EBBBFF;\ }\ \ .ace-tomorrow-night-blue .ace_support.ace_constant {\ color:#FFC58F;\ }\ \ .ace-tomorrow-night-blue .ace_fold {\ background-color: #BBDAFF;\ border-color: #FFFFFF;\ }\ \ .ace-tomorrow-night-blue .ace_support.ace_function {\ color:#BBDAFF;\ }\ \ .ace-tomorrow-night-blue .ace_storage {\ color:#EBBBFF;\ }\ \ .ace-tomorrow-night-blue .ace_storage.ace_type, .ace-tomorrow-night-blue .ace_support.ace_type{\ color:#EBBBFF;\ }\ \ .ace-tomorrow-night-blue .ace_variable {\ color:#BBDAFF;\ }\ \ .ace-tomorrow-night-blue .ace_variable.ace_parameter {\ color:#FFC58F;\ }\ \ .ace-tomorrow-night-blue .ace_string {\ color:#D1F1A9;\ }\ \ .ace-tomorrow-night-blue .ace_string.ace_regexp {\ color:#FF9DA4;\ }\ \ .ace-tomorrow-night-blue .ace_comment {\ color:#7285B7;\ }\ \ .ace-tomorrow-night-blue .ace_variable {\ color:#FF9DA4;\ }\ \ .ace-tomorrow-night-blue .ace_meta.ace_tag {\ color:#FF9DA4;\ }\ \ .ace-tomorrow-night-blue .ace_entity.ace_other.ace_attribute-name {\ color:#FF9DA4;\ }\ \ .ace-tomorrow-night-blue .ace_entity.ace_name.ace_function {\ color:#BBDAFF;\ }\ \ .ace-tomorrow-night-blue .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-tomorrow-night-blue .ace_markup.ace_heading {\ color:#D1F1A9;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-tomorrow_night_blue.js
JavaScript
asf20
5,404
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/cobalt', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-cobalt"; exports.cssText = "\ .ace-cobalt .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-cobalt .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-cobalt .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-cobalt .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-cobalt .ace_scroller {\ background-color: #002240;\ }\ \ .ace-cobalt .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-cobalt .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-cobalt .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-cobalt .ace_marker-layer .ace_selection {\ background: rgba(179, 101, 57, 0.75);\ }\ \ .ace-cobalt.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #002240;\ border-radius: 2px;\ }\ \ .ace-cobalt .ace_marker-layer .ace_step {\ background: rgb(127, 111, 19);\ }\ \ .ace-cobalt .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(255, 255, 255, 0.15);\ }\ \ .ace-cobalt .ace_marker-layer .ace_active_line {\ background: rgba(0, 0, 0, 0.35);\ }\ \ .ace-cobalt .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-cobalt .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(179, 101, 57, 0.75);\ }\ \ .ace-cobalt .ace_invisible {\ color: rgba(255, 255, 255, 0.15);\ }\ \ .ace-cobalt .ace_keyword, .ace-cobalt .ace_meta {\ color:#FF9D00;\ }\ \ .ace-cobalt .ace_constant, .ace-cobalt .ace_constant.ace_other {\ color:#FF628C;\ }\ \ .ace-cobalt .ace_constant.ace_character, {\ color:#FF628C;\ }\ \ .ace-cobalt .ace_constant.ace_character.ace_escape, {\ color:#FF628C;\ }\ \ .ace-cobalt .ace_invalid {\ color:#F8F8F8;\ background-color:#800F00;\ }\ \ .ace-cobalt .ace_support {\ color:#80FFBB;\ }\ \ .ace-cobalt .ace_support.ace_constant {\ color:#EB939A;\ }\ \ .ace-cobalt .ace_fold {\ background-color: #FF9D00;\ border-color: #FFFFFF;\ }\ \ .ace-cobalt .ace_support.ace_function {\ color:#FFB054;\ }\ \ .ace-cobalt .ace_storage {\ color:#FFEE80;\ }\ \ .ace-cobalt .ace_string.ace_regexp {\ color:#80FFC2;\ }\ \ .ace-cobalt .ace_comment {\ font-style:italic;\ color:#0088FF;\ }\ \ .ace-cobalt .ace_variable {\ color:#CCCCCC;\ }\ \ .ace-cobalt .ace_variable.ace_language {\ color:#FF80E1;\ }\ \ .ace-cobalt .ace_meta.ace_tag {\ color:#9EFFFF;\ }\ \ .ace-cobalt .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-cobalt .ace_markup.ace_heading {\ color:#C8E4FD;\ background-color:#001221;\ }\ \ .ace-cobalt .ace_markup.ace_list {\ background-color:#130D26;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-cobalt.js
JavaScript
asf20
4,632
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/clouds', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-clouds"; exports.cssText = "\ .ace-clouds .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-clouds .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-clouds .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-clouds .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-clouds .ace_scroller {\ background-color: #FFFFFF;\ }\ \ .ace-clouds .ace_text-layer {\ cursor: text;\ color: #000000;\ }\ \ .ace-clouds .ace_cursor {\ border-left: 2px solid #000000;\ }\ \ .ace-clouds .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #000000;\ }\ \ .ace-clouds .ace_marker-layer .ace_selection {\ background: #BDD5FC;\ }\ \ .ace-clouds.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #FFFFFF;\ border-radius: 2px;\ }\ \ .ace-clouds .ace_marker-layer .ace_step {\ background: rgb(255, 255, 0);\ }\ \ .ace-clouds .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #BFBFBF;\ }\ \ .ace-clouds .ace_marker-layer .ace_active_line {\ background: #FFFBD1;\ }\ \ .ace-clouds .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-clouds .ace_marker-layer .ace_selected_word {\ border: 1px solid #BDD5FC;\ }\ \ .ace-clouds .ace_invisible {\ color: #BFBFBF;\ }\ \ .ace-clouds .ace_keyword, .ace-clouds .ace_meta {\ color:#AF956F;\ }\ \ .ace-clouds .ace_keyword.ace_operator {\ color:#484848;\ }\ \ .ace-clouds .ace_constant.ace_language {\ color:#39946A;\ }\ \ .ace-clouds .ace_constant.ace_numeric {\ color:#46A609;\ }\ \ .ace-clouds .ace_invalid {\ background-color:#FF002A;\ }\ \ .ace-clouds .ace_fold {\ background-color: #AF956F;\ border-color: #000000;\ }\ \ .ace-clouds .ace_support.ace_function {\ color:#C52727;\ }\ \ .ace-clouds .ace_storage {\ color:#C52727;\ }\ \ .ace-clouds .ace_string {\ color:#5D90CD;\ }\ \ .ace-clouds .ace_comment {\ color:#BCC8BA;\ }\ \ .ace-clouds .ace_entity.ace_other.ace_attribute-name {\ color:#606060;\ }\ \ .ace-clouds .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-clouds.js
JavaScript
asf20
4,092
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/solarized_light', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-solarized-light"; exports.cssText = "\ .ace-solarized-light .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-solarized-light .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-solarized-light .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-solarized-light .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-solarized-light .ace_scroller {\ background-color: #FDF6E3;\ }\ \ .ace-solarized-light .ace_text-layer {\ cursor: text;\ color: #586E75;\ }\ \ .ace-solarized-light .ace_cursor {\ border-left: 2px solid #000000;\ }\ \ .ace-solarized-light .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #000000;\ }\ \ .ace-solarized-light .ace_marker-layer .ace_selection {\ background: #073642;\ }\ \ .ace-solarized-light.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #FDF6E3;\ border-radius: 2px;\ }\ \ .ace-solarized-light .ace_marker-layer .ace_step {\ background: rgb(255, 255, 0);\ }\ \ .ace-solarized-light .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(147, 161, 161, 0.50);\ }\ \ .ace-solarized-light .ace_marker-layer .ace_active_line {\ background: #EEE8D5;\ }\ \ .ace-solarized-light .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-solarized-light .ace_marker-layer .ace_selected_word {\ border: 1px solid #073642;\ }\ \ .ace-solarized-light .ace_invisible {\ color: rgba(147, 161, 161, 0.50);\ }\ \ .ace-solarized-light .ace_keyword, .ace-solarized-light .ace_meta {\ color:#859900;\ }\ \ .ace-solarized-light .ace_constant.ace_language {\ color:#B58900;\ }\ \ .ace-solarized-light .ace_constant.ace_numeric {\ color:#D33682;\ }\ \ .ace-solarized-light .ace_constant.ace_other {\ color:#CB4B16;\ }\ \ .ace-solarized-light .ace_fold {\ background-color: #268BD2;\ border-color: #586E75;\ }\ \ .ace-solarized-light .ace_support.ace_function {\ color:#268BD2;\ }\ \ .ace-solarized-light .ace_storage {\ color:#073642;\ }\ \ .ace-solarized-light .ace_variable {\ color:#268BD2;\ }\ \ .ace-solarized-light .ace_string {\ color:#2AA198;\ }\ \ .ace-solarized-light .ace_string.ace_regexp {\ color:#D30102;\ }\ \ .ace-solarized-light .ace_comment {\ color:#93A1A1;\ }\ \ .ace-solarized-light .ace_variable.ace_language {\ color:#268BD2;\ }\ \ .ace-solarized-light .ace_entity.ace_other.ace_attribute-name {\ color:#93A1A1;\ }\ \ .ace-solarized-light .ace_entity.ace_name.ace_function {\ color:#268BD2;\ }\ \ .ace-solarized-light .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-solarized_light.js
JavaScript
asf20
4,620
define('ace/mode/latex', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/latex_highlight_rules', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var LatexHighlightRules = require("./latex_highlight_rules").LatexHighlightRules; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new LatexHighlightRules().getRules()); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { // This code is adapted from ruby.js var outdent = true; // LaTeX comments begin with % and go to the end of the line var commentRegEx = /^(\s*)\%/; for (var i = startRow; i <= endRow; i++) { if (!commentRegEx.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i = startRow; i <= endRow; i++) { var line = doc.getLine(i); var m = line.match(commentRegEx); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "%"); } }; // There is no universally accepted way of indenting a tex document // so just maintain the indentation of the previous line this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/latex_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LatexHighlightRules = function() { this.$rules = { "start" : [{ // A tex command e.g. \foo token : "keyword", regex : "\\\\(?:[^a-zA-Z]|[a-zA-Z]+)", }, { // Curly and square braces token : "lparen", regex : "[[({]" }, { // Curly and square braces token : "rparen", regex : "[\\])}]" }, { // Inline math between two $ symbols token : "string", regex : "\\$(?:(?:\\\\.)|(?:[^\\$\\\\]))*?\\$" }, { // A comment. Tex comments start with % and go to // the end of the line token : "comment", regex : "%.*$" }] }; }; oop.inherits(LatexHighlightRules, TextHighlightRules); exports.LatexHighlightRules = LatexHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-latex.js
JavaScript
asf20
3,006
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/svg', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml', 'ace/mode/javascript', 'ace/tokenizer', 'ace/mode/svg_highlight_rules', 'ace/mode/folding/mixed', 'ace/mode/folding/xml', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var XmlMode = require("./xml").Mode; var JavaScriptMode = require("./javascript").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var SvgHighlightRules = require("./svg_highlight_rules").SvgHighlightRules; var MixedFoldMode = require("./folding/mixed").FoldMode; var XmlFoldMode = require("./folding/xml").FoldMode; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { XmlMode.call(this); this.highlighter = new SvgHighlightRules(); this.$tokenizer = new Tokenizer(this.highlighter.getRules()); this.$embeds = this.highlighter.getEmbeds(); this.createModeDelegates({ "js-": JavaScriptMode }); this.foldingRules = new MixedFoldMode(new XmlFoldMode({}), { "js-": new CStyleFoldMode() }); }; oop.inherits(Mode, XmlMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules()); this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" }], cdata : [{ token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "(?:[^\\]]|\\](?!\\]>))+" }], comment : [{ token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); }; oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/svg_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/javascript_highlight_rules', 'ace/mode/xml_highlight_rules', 'ace/mode/xml_util'], function(require, exports, module) { var oop = require("../lib/oop"); var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var xmlUtil = require("./xml_util"); var SvgHighlightRules = function() { XmlHighlightRules.call(this); this.$rules.start.splice(3, 0, { token : "meta.tag", regex : "<(?=\s*script)", next : "script" }); xmlUtil.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); }; oop.inherits(SvgHighlightRules, XmlHighlightRules); exports.SvgHighlightRules = SvgHighlightRules; }); define('ace/mode/folding/mixed', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-svg.js
JavaScript
asf20
58,305
"no use strict"; var console = { log: function(msg) { postMessage({type: "log", data: msg}); } }; var window = { console: console }; 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("/"); var moduleName = base + "/" + moduleName; while(moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; var moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; var require = function(parentId, id) { var id = normalizeModule(parentId, id); var module = require.modules[id]; if (module) { if (!module.initialized) { module.exports = module.factory().exports; module.initialized = true; } return module.exports; } var chunks = id.split("/"); chunks[0] = require.tlns[chunks[0]] || chunks[0]; var path = chunks.join("/") + ".js"; require.id = id; importScripts(path); return require(parentId, id); }; require.modules = {}; require.tlns = {}; var define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; } else if (arguments.length == 1) { factory = id; id = require.id; } if (id.indexOf("text!") === 0) return; var req = function(deps, factory) { return require(id, deps, factory); }; require.modules[id] = { factory: function() { var module = { exports: {} }; var returnExports = factory(req, module.exports, module); if (returnExports) module.exports = returnExports; return module; } }; }; function initBaseUrls(topLevelNamespaces) { require.tlns = topLevelNamespaces; } function initSender() { var EventEmitter = require(null, "ace/lib/event_emitter").EventEmitter; var oop = require(null, "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; var sender; onmessage = function(e) { var msg = e.data; if (msg.command) { main[msg.command].apply(main, msg.args); } else if (msg.init) { initBaseUrls(msg.tlns); require(null, "ace/lib/fixoldbrowsers"); sender = initSender(); var clazz = require(null, msg.module)[msg.classname]; main = new clazz(sender); } else if (msg.event && sender) { sender._emit(msg.event, msg.data); } }; // vim:set ts=4 sts=4 sw=4 st: // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Irakli Gozalishvili Copyright (C) 2010 MIT License /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) { require("./regexp"); require("./es5-shim"); }); define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) { //--------------------------------- // Private variables //--------------------------------- 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; //--------------------------------- // Overriden native methods //--------------------------------- // Adds named capture support (with backreferences returned as `result.name`), and fixes two // cross-browser issues per ES3: // - Captured values for nonparticipating capturing groups should be returned as `undefined`, // rather than the empty string. // - `lastIndex` should not be incremented after zero-length matches. RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed // matching due to characters outside the match 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; } }); } // Attach named capture properties 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]; } } // Fix browsers that increment `lastIndex` after zero-length matches if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; } return match; }; // Don't override `test` if it won't change anything if (!compliantLastIndexIncrement) { // Fix browser bug in native method RegExp.prototype.test = function (str) { // Use the native `exec` to skip some processing overhead, even though the overriden // `exec` would take care of the `lastIndex` fix var match = real.exec.call(this, str); // Fix browsers that increment `lastIndex` after zero-length matches if (match && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; return !!match; }; } //--------------------------------- // Private helper functions //--------------------------------- 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; }; }); // vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License // -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License // -- kossnocorp Sasha Koss XXX TODO License or CLA // -- bryanforbes Bryan Forbes XXX TODO License or CLA // -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence // -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License // -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License // -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain) // -- iwyg XXX TODO License or CLA // -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License // -- xavierm02 Montillet Xavier XXX TODO License or CLA // -- Raynos Raynos XXX TODO License or CLA // -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License // -- rwldrn Rick Waldron Copyright (C) 2011 MIT License // -- lexer Alexey Zakharov XXX TODO License or CLA /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) { /* * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * * @module */ /*whatsupdoc*/ // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (typeof target != "function") throw new TypeError(); // TODO message // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){}; F.prototype = target.prototype; var self = new F; var result = target.apply( self, args.concat(slice.call(arguments)) ); if (result !== null && Object(result) === result) return result; return self; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(slice.call(arguments)) ); } }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. 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); // If JS engine supports accessors creating shortcuts. 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__); } // // Array // ===== // // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function isArray(obj) { return toString(obj) == "[object Array]"; }; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var self = toObject(this), thisp = arguments[1], i = 0, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object context fun.call(thisp, self[i], i, self); } i++; } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var self = toObject(this), length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, self); } return result; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, result = [], thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) result.push(self[i]); } return result; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, self)) return false; } return true; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) return true; } return false; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value and an empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) throw new TypeError(); // TODO message } while (true); } for (; i < length; i++) { if (i in self) result = fun.call(void 0, result, self[i], i, self); } return result; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value, empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) throw new TypeError(); // TODO message } while (true); } do { if (i in this) result = fun.call(void 0, result, self[i], i, self); } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = toObject(this), length = self.length >>> 0; if (!length) return -1; var i = 0; if (arguments.length > 1) i = toInteger(arguments[1]); // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = 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])); // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) return i; } return -1; }; } // // Object // ====== // // ES5 15.2.3.2 // http://es5.github.com/#x15.2.3.2 if (!Object.getPrototypeOf) { // https://github.com/kriskowal/es5-shim/issues#issue/2 // http://ejohn.org/blog/objectgetprototypeof/ // recommended by fschaefer on github Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } // ES5 15.2.3.3 // http://es5.github.com/#x15.2.3.3 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 object does not owns property return undefined immediately. if (!owns(object, property)) return; var descriptor, getter, setter; // If object has a property then it's for sure both `enumerable` and // `configurable`. descriptor = { enumerable: true, configurable: true }; // If JS engine supports accessor properties then property may be a // getter or setter. if (supportsAccessors) { // Unfortunately `__lookupGetter__` will return a getter even // if object has own non getter property along with a same named // inherited getter. To avoid misbehavior we temporary remove // `__proto__` so that `__lookupGetter__` will return getter only // if it's owned by an object. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); // Once we have getter and setter we can put values back. object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; // If it was accessor property we're done and return here // in order to avoid adding `value` to the descriptor. return descriptor; } } // If we got this far we know that object has an own property that is // not an accessor so we set it as a value and return descriptor. descriptor.value = object[property]; return descriptor; }; } // ES5 15.2.3.4 // http://es5.github.com/#x15.2.3.4 if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!Object.create) { Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = { "__proto__": null }; } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); // IE has no built-in implementation of `Object.getPrototypeOf` // neither `__proto__`, but this manually setting `__proto__` will // guarantee that `Object.getPrototypeOf` will work as expected with // objects created using `Object.create` object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } // ES5 15.2.3.6 // http://es5.github.com/#x15.2.3.6 // Patch for WebKit and IE8 standard mode // Designed by hax <hax.github.com> // related issue: https://github.com/kriskowal/es5-shim/issues#issue/5 // IE8 Reference: // http://msdn.microsoft.com/en-us/library/dd282900.aspx // http://msdn.microsoft.com/en-us/library/dd229916.aspx // WebKit Bugs: // https://bugs.webkit.org/show_bug.cgi?id=36423 function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { // returns falsy } } // check whether defineProperty works if it's given. Otherwise, // shim partially. 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); // make a valiant attempt to use the real defineProperty // for I8's DOM elements. if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { // try the shim if the real one doesn't work } } // If it's a data property. if (owns(descriptor, "value")) { // fail silently if "writable", "enumerable", or "configurable" // are requested but not supported /* // alternate approach: if ( // can't implement these features; allow false but not true !(owns(descriptor, "writable") ? descriptor.writable : true) || !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) || !(owns(descriptor, "configurable") ? descriptor.configurable : true) ) throw new RangeError( "This implementation of Object.defineProperty does not " + "support configurable, enumerable, or writable." ); */ if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { // As accessors are supported only on engines implementing // `__proto__` we can safely override `__proto__` while defining // a property to make sure that we don't hit an inherited // accessor. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; // Deleting a property anyway since getter / setter may be // defined on object itself. delete object[property]; object[property] = descriptor.value; // Setting original `__proto__` back now. object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); // If we got that far then getters and setters can be defined !! if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 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; }; } // ES5 15.2.3.8 // http://es5.github.com/#x15.2.3.8 if (!Object.seal) { Object.seal = function seal(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.9 // http://es5.github.com/#x15.2.3.9 if (!Object.freeze) { Object.freeze = function freeze(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // detect a Rhino bug and patch it 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); } // ES5 15.2.3.10 // http://es5.github.com/#x15.2.3.10 if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.11 // http://es5.github.com/#x15.2.3.11 if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } // ES5 15.2.3.12 // http://es5.github.com/#x15.2.3.12 if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } // ES5 15.2.3.13 // http://es5.github.com/#x15.2.3.13 if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { // 1. If Type(O) is not Object throw a TypeError exception. if (Object(object) === object) { throw new TypeError(); // TODO message } // 2. Return the Boolean value of the [[Extensible]] internal property of O. var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation 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; }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) { Date.prototype.toISOString = function toISOString() { var result, length, value, year; if (!isFinite(this)) throw new RangeError; // the date time string format is specified in 15.9.1.15. result = [this.getUTCMonth() + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = this.getUTCFullYear(); year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two digits. if (value < 10) result[length] = "0" + value; } // pad milliseconds to have three digits. return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z"; } } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). if (!Date.prototype.toJSON) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be ToPrimitive(O, hint Number). // 3. If tv is a Number and is not finite, return null. // XXX // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof this.toISOString != "function") throw new TypeError(); // TODO message // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return this.toISOString(); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function(NativeDate) { // Date.length === 7 var Date = function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length == 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); }; // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:\\.(\\d{3}))?" + // milliseconds capture ")?" + "(?:" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) Date[key] = NativeDate[key]; // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { match.shift(); // kill match[0], the full match // parse months, days, hours, minutes, seconds, and milliseconds for (var i = 1; i < 7; i++) { // provide default values if necessary match[i] = +(match[i] || (i < 3 ? 1 : 0)); // match[1] is the month. Months are 0-11 in JavaScript // `Date` objects, but 1-12 in ISO notation, so we // decrement. if (i == 1) match[i]--; } // parse the UTC offset component var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop(); // compute the explicit time zone offset if specified var offset = 0; if (sign) { // detect invalid offsets and return early if (hourOffset > 23 || minuteOffset > 59) return NaN; // express the provided time zone offset in minutes. The offset is // negative for time zones west of UTC; positive otherwise. offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1); } // Date.UTC for years between 0 and 99 converts year to 1900 + year // The Gregorian calendar has a 400-year cycle, so // to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...), // where 12622780800000 - number of milliseconds in Gregorian calendar 400 years var year = +match[0]; if (0 <= year && year <= 99) { match[0] = year + 400; return NativeDate.UTC.apply(this, match) + offset - 12622780800000; } // compute a new UTC date value, accounting for the optional offset return NativeDate.UTC.apply(this, match) + offset; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // // String // ====== // // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 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()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ 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, ""); }; } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer var toInteger = function (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; }; var prepareString = "a"[0] != "a", // ES5 9.9 // http://es5.github.com/#x9.9 toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError(); // TODO message } // If the implementation doesn't support by-index access of // string characters (ex. IE < 7), split the string if (prepareString && typeof o == "string" && o) { return o.split(""); } return Object(o); }; }); define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) { var EventEmitter = {}; 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; e = e || {}; e.type = eventName; if (!e.stopPropagation) { e.stopPropagation = function() { this.propagationStopped = true; }; } if (!e.preventDefault) { e.preventDefault = function() { this.defaultPrevented = true; }; } for (var i=0; i<listeners.length; i++) { listeners[i](e); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e); }; EventEmitter.setDefaultHandler = function(eventName, callback) { this._defaultHandlers = this._defaultHandlers || {}; if (this._defaultHandlers[eventName]) throw new Error("The default handler for '" + eventName + "' is already set"); this._defaultHandlers[eventName] = callback; }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) var listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners.push(callback); }; EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) { exports.inherits = (function() { var tempCtor = function() {}; return function(ctor, superCtor) { tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor.prototype; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }; }()); exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); define('ace/mode/css_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/mode/css/csslint'], function(require, exports, module) { var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var CSSLint = require("./css/csslint").CSSLint; var Worker = exports.Worker = function(sender) { Mirror.call(this, sender); this.setTimeout(200); }; oop.inherits(Worker, Mirror); (function() { this.onUpdate = function() { var value = this.doc.getValue(); var result = CSSLint.verify(value); this.sender.emit("csslint", result.messages.map(function(msg) { delete msg.rule; return msg; })); }; }).call(Worker.prototype); }); define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) { 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.deferredCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { doc.applyDeltas([e.data]); deferredUpdate.schedule(_self.$timeout); }); }; (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() { // abstract method }; }).call(Mirror.prototype); }); define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; /** * new Document([text]) * - text (String | Array): The starting text * * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * **/ var Document = function(text) { this.$lines = []; // There has to be one line at least in the document. If you pass an empty // string to the insert function, nothing will happen. Workaround. if (text.length == 0) { this.$lines = [""]; } else if (Array.isArray(text)) { this.insertLines(0, text); } else { this.insert({row: 0, column:0}, text); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength(); this.remove(new Range(0, 0, len, this.getLine(len-1).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); }; // check for IE split bug 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); if (match) { this.$autoNewLine = match[1]; } else { this.$autoNewLine = "\n"; } }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; case "auto": return this.$autoNewLine; } }; this.$autoNewLine = "\n"; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; }; 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) { if (range.start.row == range.end.row) { return this.$lines[range.start.row].substring(range.start.column, range.end.column); } else { var lines = this.getLines(range.start.row+1, range.end.row-1); lines.unshift((this.$lines[range.start.row] || "").substring(range.start.column)); lines.push((this.$lines[range.end.row] || "").substring(0, range.end.column)); return lines.join(this.getNewLineCharacter()); } }; 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; } return position; }; this.insert = function(position, text) { if (!text || text.length === 0) return position; position = this.$clipPosition(position); // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); var lines = this.$split(text); var firstLine = lines.splice(0, 1)[0]; var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0]; position = this.insertInLine(position, firstLine); if (lastLine !== null) { position = this.insertNewLine(position); // terminate first line position = this.insertLines(position.row, lines); position = this.insertInLine(position, lastLine || ""); } return position; }; this.insertLines = function(row, lines) { if (lines.length == 0) return {row: row, column: 0}; // apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF) // to circumvent that we have to break huge inserts into smaller chunks here if (lines.length > 0xFFFF) { var end = this.insertLines(row, lines.slice(0xFFFF)); lines = lines.slice(0, 0xFFFF); } var args = [row, 0]; args.push.apply(args, lines); this.$lines.splice.apply(this.$lines, args); var range = new Range(row, 0, row + lines.length, 0); var delta = { action: "insertLines", range: range, lines: lines }; this._emit("change", { data: delta }); return end || range.end; }; this.insertNewLine = function(position) { position = this.$clipPosition(position); var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column); this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length)); var end = { row : position.row + 1, column : 0 }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); return end; }; this.insertInLine = function(position, text) { if (text.length == 0) return position; var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column) + text + line.substring(position.column); var end = { row : position.row, column : position.column + text.length }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: text }; this._emit("change", { data: delta }); return end; }; this.remove = function(range) { // clip to document range.start = this.$clipPosition(range.start); range.end = this.$clipPosition(range.end); if (range.isEmpty()) return range.start; var firstRow = range.start.row; var lastRow = range.end.row; if (range.isMultiLine()) { var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1; var lastFullRow = lastRow - 1; if (range.end.column > 0) this.removeInLine(lastRow, 0, range.end.column); if (lastFullRow >= firstFullRow) this.removeLines(firstFullRow, lastFullRow); if (firstFullRow != firstRow) { this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length); this.removeNewLine(range.start.row); } } else { this.removeInLine(firstRow, range.start.column, range.end.column); } return range.start; }; this.removeInLine = function(row, startColumn, endColumn) { if (startColumn == endColumn) return; var range = new Range(row, startColumn, row, endColumn); var line = this.getLine(row); var removed = line.substring(startColumn, endColumn); var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length); this.$lines.splice(row, 1, newLine); var delta = { action: "removeText", range: range, text: removed }; this._emit("change", { data: delta }); return range.start; }; this.removeLines = function(firstRow, lastRow) { var range = new Range(firstRow, 0, lastRow + 1, 0); var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1); var delta = { action: "removeLines", range: range, nl: this.getNewLineCharacter(), lines: removed }; this._emit("change", { data: delta }); return removed; }; this.removeNewLine = function(row) { var firstLine = this.getLine(row); var secondLine = this.getLine(row+1); var range = new Range(row, firstLine.length, row+1, 0); var line = firstLine + secondLine; this.$lines.splice(row, 2, line); var delta = { action: "removeText", range: range, text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); }; this.replace = function(range, text) { if (text.length == 0 && range.isEmpty()) return range.start; // Shortcut: If the text we want to insert is the same as it is already // in the document, we don't have to replace anything. if (text == this.getTextRange(range)) return range.end; this.remove(range); if (text) { var end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "insertText") this.insert(range.start, delta.text); else if (delta.action == "removeLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "removeText") this.remove(range); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "insertText") this.remove(range); else if (delta.action == "removeLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "removeText") this.insert(range.start, delta.text); } }; }).call(Document.prototype); exports.Document = Document; }); define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class Range * * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. * **/ /** * new Range(startRow, startColumn, endRow, endColumn) * - startRow (Number): The starting row * - startColumn (Number): The starting column * - endRow (Number): The ending row * - endColumn (Number): The ending column * * Creates a new `Range` object with the given starting and ending row and column points. * **/ var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { /** * Range.isEqual(range) -> Boolean * - range (Range): A range to check against * * Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`. * **/ 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; } } } /** related to: Range.compare * Range.comparePoint(p) -> Number * - p (Range): A point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1<br/> * * Checks the row and column points of `p` with the row and column points of the calling range. * * * **/ this.comparePoint = function(p) { return this.compare(p.row, p.column); } /** related to: Range.comparePoint * Range.containsRange(range) -> Boolean * - range (Range): A range to compare with * * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. * **/ this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } /** * Range.intersects(range) -> Boolean * - range (Range): A range to compare with * * Returns `true` if passed in `range` intersects with the one calling this method. * **/ this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); } /** * Range.isEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. * **/ this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } /** * Range.isStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. * **/ this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; } /** * Range.setStart(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** * Range.setEnd(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** related to: Range.compare * Range.inside(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range. * **/ 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; } /** related to: Range.compare * Range.insideStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's starting points. * **/ this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; } /** related to: Range.compare * Range.insideEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's ending points. * **/ this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; } /** * Range.compare(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal <br/> * * `-1` if `p.row` is less then the calling range <br/> * * `1` if `p.row` is greater than the calling range <br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> * <br/> * If the ending row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0` <br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ 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); } } /** * Range.compareEnd(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } } /** * Range.compareInside(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`<br/> * * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`<br/> * <br/> * Otherwise, it returns the value after calling [[Range.compare `compare()`]]. * * Checks the row and column points with the row and column points of the calling range. * * * **/ 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); } } /** * Range.clipRows(firstRow, lastRow) -> Range * - firstRow (Number): The starting row * - lastRow (Number): The ending row * * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. * **/ this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) { var end = { row: lastRow+1, column: 0 }; } if (this.start.row > lastRow) { var start = { row: lastRow+1, column: 0 }; } if (this.start.row < firstRow) { var start = { row: firstRow, column: 0 }; } if (this.end.row < firstRow) { var end = { 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 ); }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; exports.Range = Range; }); define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; /** * new Anchor(doc, row, column) * - doc (Document): The document to associate with the anchor * - row (Number): The starting row position * - column (Number): The starting column position * * Creates a new `Anchor` and associates it with a document. * **/ var Anchor = exports.Anchor = function(doc, row, column) { this.document = doc; if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); this.$onChange = this.onChange.bind(this); doc.on("change", this.$onChange); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.onChange = function(e) { var delta = e.data; var range = delta.range; if (range.start.row == range.end.row && range.start.row != this.row) return; if (range.start.row > this.row) return; if (range.start.row == this.row && range.start.column > this.column) return; var row = this.row; var column = this.column; if (delta.action === "insertText") { if (range.start.row === row && range.start.column <= column) { if (range.start.row === range.end.row) { column += range.end.column - range.start.column; } else { column -= range.start.column; row += range.end.row - range.start.row; } } else if (range.start.row !== range.end.row && range.start.row < row) { row += range.end.row - range.start.row; } } else if (delta.action === "insertLines") { if (range.start.row <= row) { row += range.end.row - range.start.row; } } else if (delta.action == "removeText") { if (range.start.row == row && range.start.column < column) { if (range.end.column >= column) column = range.start.column; else column = Math.max(0, column - (range.end.column - range.start.column)); } else if (range.start.row !== range.end.row && range.start.row < row) { if (range.end.row == row) { column = Math.max(0, column - range.end.column) + range.start.column; } row -= (range.end.row - range.start.row); } else if (range.end.row == row) { row -= range.end.row - range.start.row; column = Math.max(0, column - range.end.column) + range.start.column; } } else if (delta.action == "removeLines") { if (range.start.row <= row) { if (range.end.row <= row) row -= range.end.row - range.start.row; else { row = range.start.row; column = 0; } } } this.setPosition(row, column, true); }; 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._emit("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("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); }); define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) { exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { return new Array(count + 1).join(string); }; 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<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function (obj) { if (typeof obj != "object") { return obj; } var copy = obj.constructor(); for (var key in obj) { if (typeof obj[key] == "object") { copy[key] = this.deepCopy(obj[key]); } else { copy[key] = obj[key]; } } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; return deferred; }; }); define('ace/mode/css/csslint', ['require', 'exports', 'module' ], function(require, exports, module) { /*! CSSLint Copyright (c) 2011 Nicole Sullivan and Nicholas C. Zakas. All rights reserved. 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. */ /* Build time: 2-March-2012 02:47:11 */ /*! Parser-Lib Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved. 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. */ /* Version v0.1.6, Build time: 2-March-2012 02:44:32 */ var parserlib = {}; (function(){ /** * A generic base to inherit from for any object * that needs event handling. * @class EventTarget * @constructor */ function EventTarget(){ /** * The array of listeners for various events. * @type Object * @property _listeners * @private */ this._listeners = {}; } EventTarget.prototype = { //restore constructor constructor: EventTarget, /** * Adds a listener for a given event type. * @param {String} type The type of event to add a listener for. * @param {Function} listener The function to call when the event occurs. * @return {void} * @method addListener */ addListener: function(type, listener){ if (!this._listeners[type]){ this._listeners[type] = []; } this._listeners[type].push(listener); }, /** * Fires an event based on the passed-in object. * @param {Object|String} event An object with at least a 'type' attribute * or a string indicating the event name. * @return {void} * @method fire */ 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]){ //create a copy of the array and use that so listeners can't chane var listeners = this._listeners[event.type].concat(); for (var i=0, len=listeners.length; i < len; i++){ listeners[i].call(this, event); } } }, /** * Removes a listener for a given event type. * @param {String} type The type of event to remove a listener from. * @param {Function} listener The function to remove from the event. * @return {void} * @method removeListener */ 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){ /** * The input text with line endings normalized. * @property _input * @type String * @private */ this._input = text.replace(/\n\r?/g, "\n"); this._line = 1; this._col = 1; this._cursor = 0; } StringReader.prototype = { //restore constructor constructor: StringReader, //------------------------------------------------------------------------- // Position info //------------------------------------------------------------------------- /** * Returns the column of the character to be read next. * @return {int} The column of the character to be read next. * @method getCol */ getCol: function(){ return this._col; }, /** * Returns the row of the character to be read next. * @return {int} The row of the character to be read next. * @method getLine */ getLine: function(){ return this._line ; }, /** * Determines if you're at the end of the input. * @return {Boolean} True if there's no more input, false otherwise. * @method eof */ eof: function(){ return (this._cursor == this._input.length); }, //------------------------------------------------------------------------- // Basic reading //------------------------------------------------------------------------- /** * Reads the next character without advancing the cursor. * @param {int} count How many characters to look ahead (default is 1). * @return {String} The next character or null if there is no next character. * @method peek */ peek: function(count){ var c = null; count = (typeof count == "undefined" ? 1 : count); //if we're not at the end of the input... if (this._cursor < this._input.length){ //get character and increment cursor and column c = this._input.charAt(this._cursor + count - 1); } return c; }, /** * Reads the next character from the input and adjusts the row and column * accordingly. * @return {String} The next character or null if there is no next character. * @method read */ read: function(){ var c = null; //if we're not at the end of the input... if (this._cursor < this._input.length){ //if the last character was a newline, increment row count //and reset column count if (this._input.charAt(this._cursor) == "\n"){ this._line++; this._col=1; } else { this._col++; } //get character and increment cursor and column c = this._input.charAt(this._cursor++); } return c; }, //------------------------------------------------------------------------- // Misc //------------------------------------------------------------------------- /** * Saves the current location so it can be returned to later. * @method mark * @return {void} */ 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; } }, //------------------------------------------------------------------------- // Advanced reading //------------------------------------------------------------------------- /** * Reads up to and including the given string. Throws an error if that * string is not found. * @param {String} pattern The string to read. * @return {String} The string when it is found. * @throws Error when the string pattern is not found. * @method readTo */ 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; }, /** * Reads characters while each character causes the given * filter function to return true. The function is passed * in each character and either returns true to continue * reading or false to stop. * @param {Function} filter The function to read on each character. * @return {String} The string made up of all characters that passed the * filter check. * @method readWhile */ readWhile: function(filter){ var buffer = "", c = this.read(); while(c !== null && filter(c)){ buffer += c; c = this.read(); } return buffer; }, /** * Reads characters that match either text or a regular expression and * returns those characters. If a match is found, the row and column * are adjusted; if no match is found, the reader's state is unchanged. * reading or false to stop. * @param {String|RegExp} matchter If a string, then the literal string * value is searched for. If a regular expression, then any string * matching the pattern is search for. * @return {String} The string made up of all characters that matched or * null if there was no match. * @method readMatch */ readMatch: function(matcher){ var source = this._input.substring(this._cursor), value = null; //if it's a string, just do a straight match 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; }, /** * Reads a given number of characters. If the end of the input is reached, * it reads only the remaining characters and does not throw an error. * @param {int} count The number of characters to read. * @return {String} The string made up the read characters. * @method readCount */ readCount: function(count){ var buffer = ""; while(count--){ buffer += this.read(); } return buffer; } }; function SyntaxError(message, line, col){ /** * The column at which the error occurred. * @type int * @property col */ this.col = col; this.line = line; this.message = message; } //inherit from Error SyntaxError.prototype = new Error(); function SyntaxUnit(text, line, col, type){ /** * The column of text on which the unit resides. * @type int * @property col */ this.col = col; this.line = line; this.text = text; this.type = type; } /** * Create a new syntax unit based solely on the given token. * Convenience method for creating a new syntax unit when * it represents a single token instead of multiple. * @param {Object} token The token object to represent. * @return {parserlib.util.SyntaxUnit} The object representing the token. * @static * @method fromToken */ SyntaxUnit.fromToken = function(token){ return new SyntaxUnit(token.value, token.startLine, token.startCol); }; SyntaxUnit.prototype = { //restore constructor constructor: SyntaxUnit, /** * Returns the text representation of the unit. * @return {String} The text representation of the unit. * @method valueOf */ valueOf: function(){ return this.toString(); }, /** * Returns the text representation of the unit. * @return {String} The text representation of the unit. * @method toString */ toString: function(){ return this.text; } }; /** * Generic TokenStream providing base functionality. * @class TokenStreamBase * @namespace parserlib.util * @constructor * @param {String|StringReader} input The text to tokenize or a reader from * which to read the input. */ function TokenStreamBase(input, tokenData){ /** * The string reader for easy access to the text. * @type StringReader * @property _reader * @private */ this._reader = input ? new StringReader(input.toString()) : null; this._token = null; this._tokenData = tokenData; this._lt = []; this._ltIndex = 0; this._ltIndexCache = []; } /** * Accepts an array of token information and outputs * an array of token data containing key-value mappings * and matching functions that the TokenStream needs. * @param {Array} tokens An array of token descriptors. * @return {Array} An array of processed token data. * @method createTokenData * @static */ 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 = { //restore constructor constructor: TokenStreamBase, //------------------------------------------------------------------------- // Matching methods //------------------------------------------------------------------------- /** * Determines if the next token matches the given token type. * If so, that token is consumed; if not, the token is placed * back onto the token stream. You can pass in any number of * token types and this will return true if any of the token * types is found. * @param {int|int[]} tokenTypes Either a single token type or an array of * token types that the next token might be. If an array is passed, * it's assumed that the token can be any of these. * @param {variant} channel (Optional) The channel to read from. If not * provided, reads from the default (unnamed) channel. * @return {Boolean} True if the token type matches, false if not. * @method match */ match: function(tokenTypes, channel){ //always convert to an array, makes things easier 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; } } //no match found, put the token back this.unget(); return false; }, /** * Determines if the next token matches the given token type. * If so, that token is consumed; if not, an error is thrown. * @param {int|int[]} tokenTypes Either a single token type or an array of * token types that the next token should be. If an array is passed, * it's assumed that the token must be one of these. * @param {variant} channel (Optional) The channel to read from. If not * provided, reads from the default (unnamed) channel. * @return {void} * @method mustMatch */ mustMatch: function(tokenTypes, channel){ var token; //always convert to an array, makes things easier 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); } }, //------------------------------------------------------------------------- // Consuming methods //------------------------------------------------------------------------- /** * Keeps reading from the token stream until either one of the specified * token types is found or until the end of the input is reached. * @param {int|int[]} tokenTypes Either a single token type or an array of * token types that the next token should be. If an array is passed, * it's assumed that the token must be one of these. * @param {variant} channel (Optional) The channel to read from. If not * provided, reads from the default (unnamed) channel. * @return {void} * @method advance */ advance: function(tokenTypes, channel){ while(this.LA(0) !== 0 && !this.match(tokenTypes, channel)){ this.get(); } return this.LA(0); }, /** * Consumes the next token from the token stream. * @return {int} The token type of the token that was just consumed. * @method get */ get: function(channel){ var tokenInfo = this._tokenData, reader = this._reader, value, i =0, len = tokenInfo.length, found = false, token, info; //check the lookahead buffer first if (this._lt.length && this._ltIndex >= 0 && this._ltIndex < this._lt.length){ i++; this._token = this._lt[this._ltIndex++]; info = tokenInfo[this._token.type]; //obey channels logic while((info.channel !== undefined && channel !== info.channel) && this._ltIndex < this._lt.length){ this._token = this._lt[this._ltIndex++]; info = tokenInfo[this._token.type]; i++; } //here be dragons if ((info.channel === undefined || channel === info.channel) && this._ltIndex <= this._lt.length){ this._ltIndexCache.push(i); return this._token.type; } } //call token retriever method token = this._getToken(); //if it should be hidden, don't save a token if (token.type > -1 && !tokenInfo[token.type].hide){ //apply token channel token.channel = tokenInfo[token.type].channel; //save for later this._token = token; this._lt.push(token); //save space that will be moved (must be done before array is truncated) this._ltIndexCache.push(this._lt.length - this._ltIndex + i); //keep the buffer under 5 items if (this._lt.length > 5){ this._lt.shift(); } //also keep the shift buffer under 5 items if (this._ltIndexCache.length > 5){ this._ltIndexCache.shift(); } //update lookahead index this._ltIndex = this._lt.length; } /* * Skip to the next token if: * 1. The token type is marked as hidden. * 2. The token type has a channel specified and it isn't the current channel. */ info = tokenInfo[token.type]; if (info && (info.hide || (info.channel !== undefined && channel !== info.channel))){ return this.get(channel); } else { //return just the type return token.type; } }, /** * Looks ahead a certain number of tokens and returns the token type at * that position. This will throw an error if you lookahead past the * end of input, past the size of the lookahead buffer, or back past * the first token in the lookahead buffer. * @param {int} The index of the token type to retrieve. 0 for the * current token, 1 for the next, -1 for the previous, etc. * @return {int} The token type of the token in the given position. * @method LA */ LA: function(index){ var total = index, tt; if (index > 0){ //TODO: Store 5 somewhere if (index > 5){ throw new Error("Too much lookahead."); } //get all those tokens while(total){ tt = this.get(); total--; } //unget all those tokens 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; }, /** * Looks ahead a certain number of tokens and returns the token at * that position. This will throw an error if you lookahead past the * end of input, past the size of the lookahead buffer, or back past * the first token in the lookahead buffer. * @param {int} The index of the token type to retrieve. 0 for the * current token, 1 for the next, -1 for the previous, etc. * @return {Object} The token of the token in the given position. * @method LA */ LT: function(index){ //lookahead first to prime the token buffer this.LA(index); //now find the token, subtract one because _ltIndex is already at the next index return this._lt[this._ltIndex+index-1]; }, /** * Returns the token type for the next token in the stream without * consuming it. * @return {int} The token type of the next token in the stream. * @method peek */ peek: function(){ return this.LA(1); }, /** * Returns the actual token object for the last consumed token. * @return {Token} The token object for the last consumed token. * @method token */ token: function(){ return this._token; }, /** * Returns the name of the token for the given token type. * @param {int} tokenType The type of token to get the name of. * @return {String} The name of the token or "UNKNOWN_TOKEN" for any * invalid token type. * @method tokenName */ tokenName: function(tokenType){ if (tokenType < 0 || tokenType > this._tokenData.length){ return "UNKNOWN_TOKEN"; } else { return this._tokenData[tokenType].name; } }, /** * Returns the token type value for the given token name. * @param {String} tokenName The name of the token whose value should be returned. * @return {int} The token type value for the given token name or -1 * for an unknown token. * @method tokenName */ tokenType: function(tokenName){ return this._tokenData[tokenName] || -1; }, /** * Returns the last consumed token to the token stream. * @method unget */ unget: function(){ //if (this._ltIndex > -1){ 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 }; })(); /* Version v0.1.6, Build time: 2-March-2012 02:44:32 */ (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", darkgreen :"#006400", darkkhaki :"#bdb76b", darkmagenta :"#8b008b", darkolivegreen :"#556b2f", darkorange :"#ff8c00", darkorchid :"#9932cc", darkred :"#8b0000", darksalmon :"#e9967a", darkseagreen :"#8fbc8f", darkslateblue :"#483d8b", darkslategray :"#2f4f4f", darkturquoise :"#00ced1", darkviolet :"#9400d3", deeppink :"#ff1493", deepskyblue :"#00bfff", dimgray :"#696969", dodgerblue :"#1e90ff", firebrick :"#b22222", floralwhite :"#fffaf0", forestgreen :"#228b22", fuchsia :"#ff00ff", gainsboro :"#dcdcdc", ghostwhite :"#f8f8ff", gold :"#ffd700", goldenrod :"#daa520", gray :"#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", lightgreen :"#90ee90", lightpink :"#ffb6c1", lightsalmon :"#ffa07a", lightseagreen :"#20b2aa", lightskyblue :"#87cefa", lightslategray :"#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", 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" }; /** * Represents a selector combinator (whitespace, +, >). * @namespace parserlib.css * @class Combinator * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} text The text representation of the unit. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function Combinator(text, line, col){ SyntaxUnit.call(this, text, line, col, Parser.COMBINATOR_TYPE); this.type = "unknown"; //pretty simple 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; /** * Represents a media feature, such as max-width:500. * @namespace parserlib.css * @class MediaFeature * @extends parserlib.util.SyntaxUnit * @constructor * @param {SyntaxUnit} name The name of the feature. * @param {SyntaxUnit} value The value of the feature or null if none. */ 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; /** * Represents an individual media query. * @namespace parserlib.css * @class MediaQuery * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} modifier The modifier "not" or "only" (or null). * @param {String} mediaType The type of media (i.e., "print"). * @param {Array} parts Array of selectors parts making up this selector. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function MediaQuery(modifier, mediaType, features, line, col){ SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType + " " : "") + 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; /** * A CSS3 parser. * @namespace parserlib.css * @class Parser * @constructor * @param {Object} options (Optional) Various options for the parser: * starHack (true|false) to allow IE6 star hack as valid, * underscoreHack (true|false) to interpret leading underscores * as IE6-7 targeting for known properties, ieFilters (true|false) * to indicate that IE < 8 filters should be accepted and not throw * syntax errors. */ function Parser(options){ //inherit event functionality EventTarget.call(this); this.options = options || {}; this._tokenStream = null; } //Static constants 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 = { //restore constructor constructor: Parser, //instance constants - yuck 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, //----------------------------------------------------------------- // Grammar //----------------------------------------------------------------- _stylesheet: function(){ /* * stylesheet * : [ CHARSET_SYM S* STRING S* ';' ]? * [S|CDO|CDC]* [ import [S|CDO|CDC]* ]* * [ namespace [S|CDO|CDC]* ]* * [ [ ruleset | media | page | font_face | keyframes ] [S|CDO|CDC]* ]* * ; */ var tokenStream = this._tokenStream, charset = null, count, token, tt; this.fire("startstylesheet"); //try to read character set this._charset(); this._skipCruft(); //try to read imports - may be more than one while (tokenStream.peek() == Tokens.IMPORT_SYM){ this._import(); this._skipCruft(); } //try to read namespaces - may be more than one while (tokenStream.peek() == Tokens.NAMESPACE_SYM){ this._namespace(); this._skipCruft(); } //get the next token tt = tokenStream.peek(); //try to read the rest 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.UNKNOWN_SYM: //unknown @ rule tokenStream.get(); if (!this.options.strict){ //fire error event this.fire({ type: "error", error: null, message: "Unknown @ rule: " + tokenStream.LT(0).value + ".", line: tokenStream.LT(0).startLine, col: tokenStream.LT(0).startCol }); //skip braces 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 { //not a syntax error, rethrow it throw new SyntaxError("Unknown @ rule.", tokenStream.LT(0).startLine, tokenStream.LT(0).startCol); } break; case Tokens.S: this._readWhitespace(); break; default: if(!this._ruleset()){ //error handling for known issues 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){ /* * import * : IMPORT_SYM S* * [STRING|URI] S* media_query_list? ';' S* */ var tokenStream = this._tokenStream, tt, uri, importToken, mediaList = []; //read import symbol tokenStream.mustMatch(Tokens.IMPORT_SYM); importToken = tokenStream.token(); this._readWhitespace(); tokenStream.mustMatch([Tokens.STRING, Tokens.URI]); //grab the URI value uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1"); this._readWhitespace(); mediaList = this._media_query_list(); //must end with a semicolon 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){ /* * namespace * : NAMESPACE_SYM S* [namespace_prefix S*]? [STRING|URI] S* ';' S* */ var tokenStream = this._tokenStream, line, col, prefix, uri; //read import symbol tokenStream.mustMatch(Tokens.NAMESPACE_SYM); line = tokenStream.token().startLine; col = tokenStream.token().startCol; this._readWhitespace(); //it's a namespace prefix - no _namespace_prefix() method because it's just an IDENT if (tokenStream.match(Tokens.IDENT)){ prefix = tokenStream.token().value; this._readWhitespace(); } tokenStream.mustMatch([Tokens.STRING, Tokens.URI]); //grab the URI value uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1"); this._readWhitespace(); //must end with a semicolon tokenStream.mustMatch(Tokens.SEMICOLON); this._readWhitespace(); if (emit !== false){ this.fire({ type: "namespace", prefix: prefix, uri: uri, line: line, col: col }); } }, _media: function(){ /* * media * : MEDIA_SYM S* media_query_list S* '{' S* ruleset* '}' S* * ; */ var tokenStream = this._tokenStream, line, col, mediaList;// = []; //look for @media 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 (!this._ruleset()){ break; } } tokenStream.mustMatch(Tokens.RBRACE); this._readWhitespace(); this.fire({ type: "endmedia", media: mediaList, line: line, col: col }); }, //CSS3 Media Queries _media_query_list: function(){ /* * media_query_list * : S* [media_query [ ',' S* media_query ]* ]? * ; */ 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; }, /* * Note: "expression" in the grammar maps to the _media_expression * method. */ _media_query: function(){ /* * media_query * : [ONLY | NOT]? S* media_type S* [ AND S* expression ]* * | expression [ AND S* expression ]* * ; */ var tokenStream = this._tokenStream, type = null, ident = null, token = null, expressions = []; if (tokenStream.match(Tokens.IDENT)){ ident = tokenStream.token().value.toLowerCase(); //since there's no custom tokens for these, need to manually check 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); }, //CSS3 Media Queries _media_type: function(){ /* * media_type * : IDENT * ; */ return this._media_feature(); }, /** * Note: in CSS3 Media Queries, this is called "expression". * Renamed here to avoid conflict with CSS3 Selectors * definition of "expression". Also note that "expr" in the * grammar now maps to "expression" from CSS3 selectors. * @method _media_expression * @private */ _media_expression: function(){ /* * expression * : '(' S* media_feature S* [ ':' S* expr ]? ')' S* * ; */ 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)); }, //CSS3 Media Queries _media_feature: function(){ /* * media_feature * : IDENT * ; */ var tokenStream = this._tokenStream; tokenStream.mustMatch(Tokens.IDENT); return SyntaxUnit.fromToken(tokenStream.token()); }, //CSS3 Paged Media _page: function(){ /* * page: * PAGE_SYM S* IDENT? pseudo_page? S* * '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S* * ; */ var tokenStream = this._tokenStream, line, col, identifier = null, pseudoPage = null; //look for @page tokenStream.mustMatch(Tokens.PAGE_SYM); line = tokenStream.token().startLine; col = tokenStream.token().startCol; this._readWhitespace(); if (tokenStream.match(Tokens.IDENT)){ identifier = tokenStream.token().value; //The value 'auto' may not be used as a page name and MUST be treated as a syntax error. if (identifier.toLowerCase() === "auto"){ this._unexpectedToken(tokenStream.token()); } } //see if there's a colon upcoming 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 }); }, //CSS3 Paged Media _margin: function(){ /* * margin : * margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S* * ; */ 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; } }, //CSS3 Paged Media _margin_sym: function(){ /* * margin_sym : * TOPLEFTCORNER_SYM | * TOPLEFT_SYM | * TOPCENTER_SYM | * TOPRIGHT_SYM | * TOPRIGHTCORNER_SYM | * BOTTOMLEFTCORNER_SYM | * BOTTOMLEFT_SYM | * BOTTOMCENTER_SYM | * BOTTOMRIGHT_SYM | * BOTTOMRIGHTCORNER_SYM | * LEFTTOP_SYM | * LEFTMIDDLE_SYM | * LEFTBOTTOM_SYM | * RIGHTTOP_SYM | * RIGHTMIDDLE_SYM | * RIGHTBOTTOM_SYM * ; */ 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(){ /* * pseudo_page * : ':' IDENT * ; */ var tokenStream = this._tokenStream; tokenStream.mustMatch(Tokens.COLON); tokenStream.mustMatch(Tokens.IDENT); //TODO: CSS3 Paged Media says only "left", "center", and "right" are allowed return tokenStream.token().value; }, _font_face: function(){ /* * font_face * : FONT_FACE_SYM S* * '{' S* declaration [ ';' S* declaration ]* '}' S* * ; */ var tokenStream = this._tokenStream, line, col; //look for @page 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 }); }, _operator: function(){ /* * operator * : '/' S* | ',' S* | /( empty )/ * ; */ var tokenStream = this._tokenStream, token = null; if (tokenStream.match([Tokens.SLASH, Tokens.COMMA])){ token = tokenStream.token(); this._readWhitespace(); } return token ? PropertyValuePart.fromToken(token) : null; }, _combinator: function(){ /* * combinator * : PLUS S* | GREATER S* | TILDE S* | S+ * ; */ 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(){ /* * unary_operator * : '-' | '+' * ; */ var tokenStream = this._tokenStream; if (tokenStream.match([Tokens.MINUS, Tokens.PLUS])){ return tokenStream.token().value; } else { return null; } }, _property: function(){ /* * property * : IDENT S* * ; */ var tokenStream = this._tokenStream, value = null, hack = null, tokenValue, token, line, col; //check for star hack - throws error if not allowed 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; //check for underscore hack - no error if not allowed because it's valid CSS syntax 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; }, //Augmented with CSS3 Selectors _ruleset: function(){ /* * ruleset * : selectors_group * '{' S* declaration? [ ';' S* declaration? ]* '}' S* * ; */ var tokenStream = this._tokenStream, tt, selectors; try { selectors = this._selectors_group(); } catch (ex){ if (ex instanceof SyntaxError && !this.options.strict){ //fire error event this.fire({ type: "error", error: ex, message: ex.message, line: ex.line, col: ex.col }); //skip over everything until closing brace tt = tokenStream.advance([Tokens.RBRACE]); if (tt == Tokens.RBRACE){ //if there's a right brace, the rule is finished so don't do anything } else { //otherwise, rethrow the error because it wasn't handled properly throw ex; } } else { //not a syntax error, rethrow it throw ex; } //trigger parser to continue return true; } //if it got here, all selectors parsed 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; }, //CSS3 Selectors _selectors_group: function(){ /* * selectors_group * : selector [ COMMA S* selector ]* * ; */ 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; }, //CSS3 Selectors _selector: function(){ /* * selector * : simple_selector_sequence [ combinator simple_selector_sequence ]* * ; */ var tokenStream = this._tokenStream, selector = [], nextSelector = null, combinator = null, ws = null; //if there's no simple selector, then there's no selector nextSelector = this._simple_selector_sequence(); if (nextSelector === null){ return null; } selector.push(nextSelector); do { //look for a combinator combinator = this._combinator(); if (combinator !== null){ selector.push(combinator); nextSelector = this._simple_selector_sequence(); //there must be a next selector if (nextSelector === null){ this._unexpectedToken(this.LT(1)); } else { //nextSelector is an instance of SelectorPart selector.push(nextSelector); } } else { //if there's not whitespace, we're done if (this._readWhitespace()){ //add whitespace separator ws = new Combinator(tokenStream.token().value, tokenStream.token().startLine, tokenStream.token().startCol); //combinator is not required combinator = this._combinator(); //selector is required if there's a 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); }, //CSS3 Selectors _simple_selector_sequence: function(){ /* * simple_selector_sequence * : [ type_selector | universal ] * [ HASH | class | attrib | pseudo | negation ]* * | [ HASH | class | attrib | pseudo | negation ]+ * ; */ var tokenStream = this._tokenStream, //parts of a simple selector elementName = null, modifiers = [], //complete selector text selectorText= "", //the different parts after the element name to search for components = [ //HASH 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; //get starting line and column for the selector 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){ //whitespace means we're done if (tokenStream.peek() === Tokens.S){ break; } //check for each component while(i < len && component === null){ component = components[i++].call(this); } if (component === null){ //we don't have a selector 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; }, //CSS3 Selectors _type_selector: function(){ /* * type_selector * : [ namespace_prefix ]? element_name * ; */ var tokenStream = this._tokenStream, ns = this._namespace_prefix(), elementName = this._element_name(); if (!elementName){ /* * Need to back out the namespace that was read due to both * type_selector and universal reading namespace_prefix * first. Kind of hacky, but only way I can figure out * right now how to not change the grammar. */ 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; } }, //CSS3 Selectors _class: function(){ /* * class * : '.' IDENT * ; */ 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; } }, //CSS3 Selectors _element_name: function(){ /* * element_name * : IDENT * ; */ 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; } }, //CSS3 Selectors _namespace_prefix: function(){ /* * namespace_prefix * : [ IDENT | '*' ]? '|' * ; */ var tokenStream = this._tokenStream, value = ""; //verify that this is a namespace prefix 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; }, //CSS3 Selectors _universal: function(){ /* * universal * : [ namespace_prefix ]? '*' * ; */ 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; }, //CSS3 Selectors _attrib: function(){ /* * attrib * : '[' S* [ namespace_prefix ]? IDENT S* * [ [ PREFIXMATCH | * SUFFIXMATCH | * SUBSTRINGMATCH | * '=' | * INCLUDES | * DASHMATCH ] S* [ IDENT | STRING ] S* * ]? ']' * ; */ 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; } }, //CSS3 Selectors _pseudo: function(){ /* * pseudo * : ':' ':'? [ IDENT | functional_pseudo ] * ; */ 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; }, //CSS3 Selectors _functional_pseudo: function(){ /* * functional_pseudo * : FUNCTION S* expression ')' * ; */ 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; }, //CSS3 Selectors _expression: function(){ /* * expression * : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+ * ; */ 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])){ value += tokenStream.token().value; value += this._readWhitespace(); } return value.length ? value : null; }, //CSS3 Selectors _negation: function(){ /* * negation * : NOT S* negation_arg S* ')' * ; */ 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; }, //CSS3 Selectors _negation_arg: function(){ /* * negation_arg * : type_selector | universal | HASH | class | attrib | pseudo * ; */ 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++; } //must be a negation arg if (arg === null){ this._unexpectedToken(tokenStream.LT(1)); } //it's an element name 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(){ /* * declaration * : property ':' S* expr prio? * | /( empty )/ * ; */ var tokenStream = this._tokenStream, property = null, expr = null, prio = null, error = null, invalid = null; property = this._property(); if (property !== null){ tokenStream.mustMatch(Tokens.COLON); this._readWhitespace(); expr = this._expr(); //if there's no parts for the value, it's an error if (!expr || expr.length === 0){ this._unexpectedToken(tokenStream.LT(1)); } prio = this._prio(); try { this._validateProperty(property, 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(){ /* * prio * : IMPORTANT_SYM S* * ; */ var tokenStream = this._tokenStream, result = tokenStream.match(Tokens.IMPORTANT_SYM); this._readWhitespace(); return result; }, _expr: function(){ /* * expr * : term [ operator term ]* * ; */ var tokenStream = this._tokenStream, values = [], //valueParts = [], value = null, operator = null; value = this._term(); if (value !== null){ values.push(value); do { operator = this._operator(); //if there's an operator, keep building up the value parts if (operator){ values.push(operator); } /*else { //if there's not an operator, you have a full value values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col)); valueParts = []; }*/ value = this._term(); if (value === null){ break; } else { values.push(value); } } while(true); } //cleanup /*if (valueParts.length){ values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col)); }*/ return values.length > 0 ? new PropertyValue(values, values[0].line, values[0].col) : null; }, _term: function(){ /* * term * : unary_operator? * [ NUMBER S* | PERCENTAGE S* | LENGTH S* | ANGLE S* | * TIME S* | FREQ S* | function | ie_function ] * | STRING S* | IDENT S* | URI S* | UNICODERANGE S* | hexcolor * ; */ var tokenStream = this._tokenStream, unary = null, value = null, token, line, col; //returns the operator or null unary = this._unary_operator(); if (unary !== null){ line = tokenStream.token().startLine; col = tokenStream.token().startCol; } //exception for IE filters if (tokenStream.peek() == Tokens.IE_FUNCTION && this.options.ieFilters){ value = this._ie_function(); if (unary === null){ line = tokenStream.token().startLine; col = tokenStream.token().startCol; } //see if there's a simple match } 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 { //see if it's a color token = this._hexcolor(); if (token === null){ //if there's no unary, get the start of the next token for line/col info if (unary === null){ line = tokenStream.LT(1).startLine; col = tokenStream.LT(1).startCol; } //has to be a function if (value === null){ /* * This checks for alpha(opacity=0) style of IE * functions. IE_FUNCTION only presents progid: style. */ if (tokenStream.LA(3) == Tokens.EQUALS && this.options.ieFilters){ value = this._ie_function(); } else { value = this._function(); } } /*if (value === null){ return null; //throw new Error("Expected identifier at line " + tokenStream.token().startLine + ", character " + tokenStream.token().startCol + "."); }*/ } 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(){ /* * function * : FUNCTION S* expr ')' S* * ; */ var tokenStream = this._tokenStream, functionText = null, expr = null, lt; if (tokenStream.match(Tokens.FUNCTION)){ functionText = tokenStream.token().value; this._readWhitespace(); expr = this._expr(); functionText += expr; //START: Horrible hack in case it's an IE filter if (this.options.ieFilters && tokenStream.peek() == Tokens.EQUALS){ do { if (this._readWhitespace()){ functionText += tokenStream.token().value; } //might be second time in the loop 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; //functionText += this._term(); 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])); } //END: Horrible Hack tokenStream.match(Tokens.RPAREN); functionText += ")"; this._readWhitespace(); } return functionText; }, _ie_function: function(){ /* (My own extension) * ie_function * : IE_FUNCTION S* IDENT '=' term [S* ','? IDENT '=' term]+ ')' S* * ; */ var tokenStream = this._tokenStream, functionText = null, expr = null, lt; //IE function can begin like a regular function, too if (tokenStream.match([Tokens.IE_FUNCTION, Tokens.FUNCTION])){ functionText = tokenStream.token().value; do { if (this._readWhitespace()){ functionText += tokenStream.token().value; } //might be second time in the loop 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; //functionText += this._term(); 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(){ /* * There is a constraint on the color that it must * have either 3 or 6 hex-digits (i.e., [0-9a-fA-F]) * after the "#"; e.g., "#000" is OK, but "#abcd" is not. * * hexcolor * : HASH S* * ; */ var tokenStream = this._tokenStream, token = null, color; if(tokenStream.match(Tokens.HASH)){ //need to do some validation here 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; }, //----------------------------------------------------------------- // Animations methods //----------------------------------------------------------------- _keyframes: function(){ /* * keyframes: * : KEYFRAMES_SYM S* keyframe_name S* '{' S* keyframe_rule* '}' { * ; */ var tokenStream = this._tokenStream, token, tt, name; tokenStream.mustMatch(Tokens.KEYFRAMES_SYM); this._readWhitespace(); name = this._keyframe_name(); this._readWhitespace(); tokenStream.mustMatch(Tokens.LBRACE); this.fire({ type: "startkeyframes", name: name, line: name.line, col: name.col }); this._readWhitespace(); tt = tokenStream.peek(); //check for key while(tt == Tokens.IDENT || tt == Tokens.PERCENTAGE) { this._keyframe_rule(); this._readWhitespace(); tt = tokenStream.peek(); } this.fire({ type: "endkeyframes", name: name, line: name.line, col: name.col }); this._readWhitespace(); tokenStream.mustMatch(Tokens.RBRACE); }, _keyframe_name: function(){ /* * keyframe_name: * : IDENT * | STRING * ; */ var tokenStream = this._tokenStream, token; tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]); return SyntaxUnit.fromToken(tokenStream.token()); }, _keyframe_rule: function(){ /* * keyframe_rule: * : key_list S* * '{' S* declaration [ ';' S* declaration ]* '}' S* * ; */ 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(){ /* * key_list: * : key [ S* ',' S* key]* * ; */ var tokenStream = this._tokenStream, token, key, keyList = []; //must be least one key keyList.push(this._key()); this._readWhitespace(); while(tokenStream.match(Tokens.COMMA)){ this._readWhitespace(); keyList.push(this._key()); this._readWhitespace(); } return keyList; }, _key: function(){ /* * There is a restriction that IDENT can be only "from" or "to". * * key * : PERCENTAGE * | IDENT * ; */ 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(); } //if it gets here, there wasn't a valid token, so time to explode this._unexpectedToken(tokenStream.LT(1)); }, //----------------------------------------------------------------- // Helper methods //----------------------------------------------------------------- /** * Not part of CSS grammar, but useful for skipping over * combination of white space and HTML-style comments. * @return {void} * @method _skipCruft * @private */ _skipCruft: function(){ while(this._tokenStream.match([Tokens.S, Tokens.CDO, Tokens.CDC])){ //noop } }, /** * Not part of CSS grammar, but this pattern occurs frequently * in the official CSS grammar. Split out here to eliminate * duplicate code. * @param {Boolean} checkStart Indicates if the rule should check * for the left brace at the beginning. * @param {Boolean} readMargins Indicates if the rule should check * for margin patterns. * @return {void} * @method _readDeclarations * @private */ _readDeclarations: function(checkStart, readMargins){ /* * Reads the pattern * S* '{' S* declaration [ ';' S* declaration ]* '}' S* * or * S* '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S* * Note that this is how it is described in CSS3 Paged Media, but is actually incorrect. * A semicolon is only necessary following a delcaration is there's another declaration * or margin afterwards. */ 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())){ //noop } else if (this._declaration()){ if (!tokenStream.match(Tokens.SEMICOLON)){ break; } } else { break; } //if ((!this._margin() && !this._declaration()) || !tokenStream.match(Tokens.SEMICOLON)){ // break; //} this._readWhitespace(); } tokenStream.mustMatch(Tokens.RBRACE); this._readWhitespace(); } catch (ex) { if (ex instanceof SyntaxError && !this.options.strict){ //fire error event this.fire({ type: "error", error: ex, message: ex.message, line: ex.line, col: ex.col }); //see if there's another declaration tt = tokenStream.advance([Tokens.SEMICOLON, Tokens.RBRACE]); if (tt == Tokens.SEMICOLON){ //if there's a semicolon, then there might be another declaration this._readDeclarations(false, readMargins); } else if (tt != Tokens.RBRACE){ //if there's a right brace, the rule is finished so don't do anything //otherwise, rethrow the error because it wasn't handled properly throw ex; } } else { //not a syntax error, rethrow it throw ex; } } }, /** * In some cases, you can end up with two white space tokens in a * row. Instead of making a change in every function that looks for * white space, this function is used to match as much white space * as necessary. * @method _readWhitespace * @return {String} The white space if found, empty string if not. * @private */ _readWhitespace: function(){ var tokenStream = this._tokenStream, ws = ""; while(tokenStream.match(Tokens.S)){ ws += tokenStream.token().value; } return ws; }, /** * Throws an error when an unexpected token is found. * @param {Object} token The token that was found. * @method _unexpectedToken * @return {void} * @private */ _unexpectedToken: function(token){ throw new SyntaxError("Unexpected token '" + token.value + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol); }, /** * Helper method used for parsing subparts of a style sheet. * @return {void} * @method _verifyEnd * @private */ _verifyEnd: function(){ if (this._tokenStream.LA(1) != Tokens.EOF){ this._unexpectedToken(this._tokenStream.LT(1)); } }, //----------------------------------------------------------------- // Validation methods //----------------------------------------------------------------- _validateProperty: function(property, value){ Validation.validate(property, value); }, //----------------------------------------------------------------- // Parsing methods //----------------------------------------------------------------- parse: function(input){ this._tokenStream = new TokenStream(input, Tokens); this._stylesheet(); }, parseStyleSheet: function(input){ //just passthrough return this.parse(input); }, parseMediaQuery: function(input){ this._tokenStream = new TokenStream(input, Tokens); var result = this._media_query(); //if there's anything more, then it's an invalid selector this._verifyEnd(); //otherwise return result return result; }, /** * Parses a property value (everything after the semicolon). * @return {parserlib.css.PropertyValue} The property value. * @throws parserlib.util.SyntaxError If an unexpected token is found. * @method parserPropertyValue */ parsePropertyValue: function(input){ this._tokenStream = new TokenStream(input, Tokens); this._readWhitespace(); var result = this._expr(); //okay to have a trailing white space this._readWhitespace(); //if there's anything more, then it's an invalid selector this._verifyEnd(); //otherwise return result return result; }, /** * Parses a complete CSS rule, including selectors and * properties. * @param {String} input The text to parser. * @return {Boolean} True if the parse completed successfully, false if not. * @method parseRule */ parseRule: function(input){ this._tokenStream = new TokenStream(input, Tokens); //skip any leading white space this._readWhitespace(); var result = this._ruleset(); //skip any trailing white space this._readWhitespace(); //if there's anything more, then it's an invalid selector this._verifyEnd(); //otherwise return result return result; }, /** * Parses a single CSS selector (no comma) * @param {String} input The text to parse as a CSS selector. * @return {Selector} An object representing the selector. * @throws parserlib.util.SyntaxError If an unexpected token is found. * @method parseSelector */ parseSelector: function(input){ this._tokenStream = new TokenStream(input, Tokens); //skip any leading white space this._readWhitespace(); var result = this._selector(); //skip any trailing white space this._readWhitespace(); //if there's anything more, then it's an invalid selector this._verifyEnd(); //otherwise return result return result; }, /** * Parses an HTML style attribute: a set of CSS declarations * separated by semicolons. * @param {String} input The text to parse as a style attribute * @return {void} * @method parseStyleAttribute */ parseStyleAttribute: function(input){ input += "}"; // for error recovery in _readDeclarations() this._tokenStream = new TokenStream(input, Tokens); this._readDeclarations(); } }; //copy over onto prototype for (prop in additions){ if (additions.hasOwnProperty(prop)){ proto[prop] = additions[prop]; } } return proto; }(); /*global Validation, ValidationTypes, ValidationError*/ var Properties = { //A "alignment-adjust" : "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>", "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: "<time>", comma: true }, "animation-direction" : { multi: "normal | alternate", comma: true }, "animation-duration" : { multi: "<time>", comma: true }, "animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "animation-name" : { multi: "none | <ident>", comma: true }, "animation-play-state" : { multi: "running | paused", comma: true }, "animation-timing-function" : 1, //vendor prefixed "-moz-animation-delay" : { multi: "<time>", comma: true }, "-moz-animation-direction" : { multi: "normal | alternate", comma: true }, "-moz-animation-duration" : { multi: "<time>", comma: true }, "-moz-animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "-moz-animation-name" : { multi: "none | <ident>", comma: true }, "-moz-animation-play-state" : { multi: "running | paused", comma: true }, "-ms-animation-delay" : { multi: "<time>", comma: true }, "-ms-animation-direction" : { multi: "normal | alternate", comma: true }, "-ms-animation-duration" : { multi: "<time>", comma: true }, "-ms-animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "-ms-animation-name" : { multi: "none | <ident>", comma: true }, "-ms-animation-play-state" : { multi: "running | paused", comma: true }, "-webkit-animation-delay" : { multi: "<time>", comma: true }, "-webkit-animation-direction" : { multi: "normal | alternate", comma: true }, "-webkit-animation-duration" : { multi: "<time>", comma: true }, "-webkit-animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "-webkit-animation-name" : { multi: "none | <ident>", comma: true }, "-webkit-animation-play-state" : { multi: "running | paused", comma: true }, "-o-animation-delay" : { multi: "<time>", comma: true }, "-o-animation-direction" : { multi: "normal | alternate", comma: true }, "-o-animation-duration" : { multi: "<time>", comma: true }, "-o-animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "-o-animation-name" : { multi: "none | <ident>", comma: true }, "-o-animation-play-state" : { multi: "running | paused", comma: true }, "appearance" : "icon | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal | inherit", "azimuth" : function (expression) { var simple = "<angle> | leftwards | rightwards | inherit", direction = "left-side | far-left | left | center-left | center | center-right | right | far-right | right-side", behind = false, valid = false, part; if (!ValidationTypes.isAny(expression, simple)) { if (ValidationTypes.isAny(expression, "behind")) { behind = true; valid = true; } if (ValidationTypes.isAny(expression, direction)) { valid = true; if (!behind) { ValidationTypes.isAny(expression, "behind"); } } } if (expression.hasNext()) { part = expression.next(); if (valid) { throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (<'azimuth'>) but found '" + part + "'.", part.line, part.col); } } }, //B "backface-visibility" : "visible | hidden", "background" : 1, "background-attachment" : { multi: "<attachment>", comma: true }, "background-clip" : { multi: "<box>", comma: true }, "background-color" : "<color> | inherit", "background-image" : { multi: "<bg-image>", comma: true }, "background-origin" : { multi: "<box>", comma: true }, "background-position" : { multi: "<bg-position>", comma: true }, "background-repeat" : { multi: "<repeat-style>" }, "background-size" : { multi: "<bg-size>", comma: true }, "baseline-shift" : "baseline | sub | super | <percentage> | <length>", "binding" : 1, "bleed" : "<length>", "bookmark-label" : "<content> | <attr> | <string>", "bookmark-level" : "none | <integer>", "bookmark-state" : "open | closed", "bookmark-target" : "none | <uri> | <attr>", "border" : "<border-width> || <border-style> || <color>", "border-bottom" : "<border-width> || <border-style> || <color>", "border-bottom-color" : "<color>", "border-bottom-left-radius" : "<x-one-radius>", "border-bottom-right-radius" : "<x-one-radius>", "border-bottom-style" : "<border-style>", "border-bottom-width" : "<border-width>", "border-collapse" : "collapse | separate | inherit", "border-color" : { multi: "<color> | inherit", max: 4 }, "border-image" : 1, "border-image-outset" : { multi: "<length> | <number>", max: 4 }, "border-image-repeat" : { multi: "stretch | repeat | round", max: 2 }, "border-image-slice" : function(expression) { var valid = false, numeric = "<number> | <percentage>", fill = false, count = 0, max = 4, part; if (ValidationTypes.isAny(expression, "fill")) { fill = true; valid = true; } while (expression.hasNext() && count < max) { valid = ValidationTypes.isAny(expression, numeric); if (!valid) { break; } count++; } if (!fill) { ValidationTypes.isAny(expression, "fill"); } else { valid = true; } if (expression.hasNext()) { part = expression.next(); if (valid) { throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected ([<number> | <percentage>]{1,4} && fill?) but found '" + part + "'.", part.line, part.col); } } }, "border-image-source" : "<image> | none", "border-image-width" : { multi: "<length> | <percentage> | <number> | auto", max: 4 }, "border-left" : "<border-width> || <border-style> || <color>", "border-left-color" : "<color> | inherit", "border-left-style" : "<border-style>", "border-left-width" : "<border-width>", "border-radius" : function(expression) { var valid = false, numeric = "<length> | <percentage>", slash = false, fill = false, count = 0, max = 8, part; while (expression.hasNext() && count < max) { valid = ValidationTypes.isAny(expression, numeric); if (!valid) { if (expression.peek() == "/" && count > 1 && !slash) { slash = true; max = count + 5; expression.next(); } else { break; } } count++; } if (expression.hasNext()) { part = expression.next(); if (valid) { throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (<'border-radius'>) but found '" + part + "'.", part.line, part.col); } } }, "border-right" : "<border-width> || <border-style> || <color>", "border-right-color" : "<color> | inherit", "border-right-style" : "<border-style>", "border-right-width" : "<border-width>", "border-spacing" : { multi: "<length> | inherit", max: 2 }, "border-style" : { multi: "<border-style>", max: 4 }, "border-top" : "<border-width> || <border-style> || <color>", "border-top-color" : "<color> | inherit", "border-top-left-radius" : "<x-one-radius>", "border-top-right-radius" : "<x-one-radius>", "border-top-style" : "<border-style>", "border-top-width" : "<border-width>", "border-width" : { multi: "<border-width>", max: 4 }, "bottom" : "<margin-width> | inherit", "box-align" : "start | end | center | baseline | stretch", //http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/ "box-decoration-break" : "slice |clone", "box-direction" : "normal | reverse | inherit", "box-flex" : "<number>", "box-flex-group" : "<integer>", "box-lines" : "single | multiple", "box-ordinal-group" : "<integer>", "box-orient" : "horizontal | vertical | inline-axis | block-axis | inherit", "box-pack" : "start | end | center | justify", "box-shadow" : function (expression) { var result = false, part; if (!ValidationTypes.isAny(expression, "none")) { Validation.multiProperty("<shadow>", expression, true, Infinity); } else { if (expression.hasNext()) { part = expression.next(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } } }, "box-sizing" : "content-box | border-box | inherit", "break-after" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column", "break-before" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column", "break-inside" : "auto | avoid | avoid-page | avoid-column", //C "caption-side" : "top | bottom | inherit", "clear" : "none | right | left | both | inherit", "clip" : 1, "color" : "<color> | inherit", "color-profile" : 1, "column-count" : "<integer> | auto", //http://www.w3.org/TR/css3-multicol/ "column-fill" : "auto | balance", "column-gap" : "<length> | normal", "column-rule" : "<border-width> || <border-style> || <color>", "column-rule-color" : "<color>", "column-rule-style" : "<border-style>", "column-rule-width" : "<border-width>", "column-span" : "none | all", "column-width" : "<length> | auto", "columns" : 1, "content" : 1, "counter-increment" : 1, "counter-reset" : 1, "crop" : "<shape> | auto", "cue" : "cue-after | cue-before | inherit", "cue-after" : 1, "cue-before" : 1, "cursor" : 1, //D "direction" : "ltr | rtl | inherit", "display" : "inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | box | inline-box | grid | inline-grid | none | inherit", "dominant-baseline" : 1, "drop-initial-after-adjust" : "central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>", "drop-initial-after-align" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical", "drop-initial-before-adjust" : "before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>", "drop-initial-before-align" : "caps-height | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical", "drop-initial-size" : "auto | line | <length> | <percentage>", "drop-initial-value" : "initial | <integer>", //E "elevation" : "<angle> | below | level | above | higher | lower | inherit", "empty-cells" : "show | hide | inherit", //F "filter" : 1, "fit" : "fill | hidden | meet | slice", "fit-position" : 1, "float" : "left | right | none | inherit", "float-offset" : 1, "font" : 1, "font-family" : 1, "font-size" : "<absolute-size> | <relative-size> | <length> | <percentage> | inherit", "font-size-adjust" : "<number> | none | inherit", "font-stretch" : "normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit", "font-style" : "normal | italic | oblique | inherit", "font-variant" : "normal | small-caps | inherit", "font-weight" : "normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit", //G "grid-cell-stacking" : "columns | rows | layer", "grid-column" : 1, "grid-columns" : 1, "grid-column-align" : "start | end | center | stretch", "grid-column-sizing" : 1, "grid-column-span" : "<integer>", "grid-flow" : "none | rows | columns", "grid-layer" : "<integer>", "grid-row" : 1, "grid-rows" : 1, "grid-row-align" : "start | end | center | stretch", "grid-row-span" : "<integer>", "grid-row-sizing" : 1, //H "hanging-punctuation" : 1, "height" : "<margin-width> | inherit", "hyphenate-after" : "<integer> | auto", "hyphenate-before" : "<integer> | auto", "hyphenate-character" : "<string> | auto", "hyphenate-lines" : "no-limit | <integer>", "hyphenate-resource" : 1, "hyphens" : "none | manual | auto", //I "icon" : 1, "image-orientation" : "angle | auto", "image-rendering" : 1, "image-resolution" : 1, "inline-box-align" : "initial | last | <integer>", //L "left" : "<margin-width> | inherit", "letter-spacing" : "<length> | normal | inherit", "line-height" : "<number> | <length> | <percentage> | normal | inherit", "line-break" : "auto | loose | normal | strict", "line-stacking" : 1, "line-stacking-ruby" : "exclude-ruby | include-ruby", "line-stacking-shift" : "consider-shifts | disregard-shifts", "line-stacking-strategy" : "inline-line-height | block-line-height | max-height | grid-height", "list-style" : 1, "list-style-image" : "<uri> | none | inherit", "list-style-position" : "inside | outside | inherit", "list-style-type" : "disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none | inherit", //M "margin" : { multi: "<margin-width> | inherit", max: 4 }, "margin-bottom" : "<margin-width> | inherit", "margin-left" : "<margin-width> | inherit", "margin-right" : "<margin-width> | inherit", "margin-top" : "<margin-width> | inherit", "mark" : 1, "mark-after" : 1, "mark-before" : 1, "marks" : 1, "marquee-direction" : 1, "marquee-play-count" : 1, "marquee-speed" : 1, "marquee-style" : 1, "max-height" : "<length> | <percentage> | none | inherit", "max-width" : "<length> | <percentage> | none | inherit", "min-height" : "<length> | <percentage> | inherit", "min-width" : "<length> | <percentage> | inherit", "move-to" : 1, //N "nav-down" : 1, "nav-index" : 1, "nav-left" : 1, "nav-right" : 1, "nav-up" : 1, //O "opacity" : "<number> | inherit", "orphans" : "<integer> | inherit", "outline" : 1, "outline-color" : "<color> | invert | inherit", "outline-offset" : 1, "outline-style" : "<border-style> | inherit", "outline-width" : "<border-width> | inherit", "overflow" : "visible | hidden | scroll | auto | inherit", "overflow-style" : 1, "overflow-x" : 1, "overflow-y" : 1, //P "padding" : { multi: "<padding-width> | inherit", max: 4 }, "padding-bottom" : "<padding-width> | inherit", "padding-left" : "<padding-width> | inherit", "padding-right" : "<padding-width> | inherit", "padding-top" : "<padding-width> | inherit", "page" : 1, "page-break-after" : "auto | always | avoid | left | right | inherit", "page-break-before" : "auto | always | avoid | left | right | inherit", "page-break-inside" : "auto | avoid | inherit", "page-policy" : 1, "pause" : 1, "pause-after" : 1, "pause-before" : 1, "perspective" : 1, "perspective-origin" : 1, "phonemes" : 1, "pitch" : 1, "pitch-range" : 1, "play-during" : 1, "position" : "static | relative | absolute | fixed | inherit", "presentation-level" : 1, "punctuation-trim" : 1, //Q "quotes" : 1, //R "rendering-intent" : 1, "resize" : 1, "rest" : 1, "rest-after" : 1, "rest-before" : 1, "richness" : 1, "right" : "<margin-width> | inherit", "rotation" : 1, "rotation-point" : 1, "ruby-align" : 1, "ruby-overhang" : 1, "ruby-position" : 1, "ruby-span" : 1, //S "size" : 1, "speak" : "normal | none | spell-out | inherit", "speak-header" : "once | always | inherit", "speak-numeral" : "digits | continuous | inherit", "speak-punctuation" : "code | none | inherit", "speech-rate" : 1, "src" : 1, "stress" : 1, "string-set" : 1, "table-layout" : "auto | fixed | inherit", "tab-size" : "<integer> | <length>", "target" : 1, "target-name" : 1, "target-new" : 1, "target-position" : 1, "text-align" : "left | right | center | justify | inherit" , "text-align-last" : 1, "text-decoration" : 1, "text-emphasis" : 1, "text-height" : 1, "text-indent" : "<length> | <percentage> | inherit", "text-justify" : "auto | none | inter-word | inter-ideograph | inter-cluster | distribute | kashida", "text-outline" : 1, "text-overflow" : 1, "text-shadow" : 1, "text-transform" : "capitalize | uppercase | lowercase | none | inherit", "text-wrap" : "normal | none | avoid", "top" : "<margin-width> | inherit", "transform" : 1, "transform-origin" : 1, "transform-style" : 1, "transition" : 1, "transition-delay" : 1, "transition-duration" : 1, "transition-property" : 1, "transition-timing-function" : 1, //U "unicode-bidi" : "normal | embed | bidi-override | inherit", "user-modify" : "read-only | read-write | write-only | inherit", "user-select" : "none | text | toggle | element | elements | all | inherit", //V "vertical-align" : "<percentage> | <length> | baseline | sub | super | top | text-top | middle | bottom | text-bottom | inherit", "visibility" : "visible | hidden | collapse | inherit", "voice-balance" : 1, "voice-duration" : 1, "voice-family" : 1, "voice-pitch" : 1, "voice-pitch-range" : 1, "voice-rate" : 1, "voice-stress" : 1, "voice-volume" : 1, "volume" : 1, //W "white-space" : "normal | pre | nowrap | pre-wrap | pre-line | inherit", "white-space-collapse" : 1, "widows" : "<integer> | inherit", "width" : "<length> | <percentage> | auto | inherit" , "word-break" : "normal | keep-all | break-all", "word-spacing" : "<length> | normal | inherit", "word-wrap" : 1, //Z "z-index" : "<integer> | auto | inherit", "zoom" : "<number> | <percentage> | normal" }; /** * Represents a selector combinator (whitespace, +, >). * @namespace parserlib.css * @class PropertyName * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} text The text representation of the unit. * @param {String} hack The type of IE hack applied ("*", "_", or null). * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function PropertyName(text, hack, line, col){ SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_NAME_TYPE); this.hack = hack; } PropertyName.prototype = new SyntaxUnit(); PropertyName.prototype.constructor = PropertyName; PropertyName.prototype.toString = function(){ return (this.hack ? this.hack : "") + this.text; }; /** * Represents a single part of a CSS property value, meaning that it represents * just everything single part between ":" and ";". If there are multiple values * separated by commas, this type represents just one of the values. * @param {String[]} parts An array of value parts making up this value. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. * @namespace parserlib.css * @class PropertyValue * @extends parserlib.util.SyntaxUnit * @constructor */ function PropertyValue(parts, line, col){ SyntaxUnit.call(this, parts.join(" "), line, col, Parser.PROPERTY_VALUE_TYPE); this.parts = parts; } PropertyValue.prototype = new SyntaxUnit(); PropertyValue.prototype.constructor = PropertyValue; /** * A utility class that allows for easy iteration over the various parts of a * property value. * @param {parserlib.css.PropertyValue} value The property value to iterate over. * @namespace parserlib.css * @class PropertyValueIterator * @constructor */ function PropertyValueIterator(value){ /** * Iterator value * @type int * @property _i * @private */ this._i = 0; this._parts = value.parts; this._marks = []; this.value = value; } /** * Returns the total number of parts in the value. * @return {int} The total number of parts in the value. * @method count */ PropertyValueIterator.prototype.count = function(){ return this._parts.length; }; PropertyValueIterator.prototype.isFirst = function(){ return this._i === 0; }; PropertyValueIterator.prototype.hasNext = function(){ return (this._i < this._parts.length); }; PropertyValueIterator.prototype.mark = function(){ this._marks.push(this._i); }; PropertyValueIterator.prototype.peek = function(count){ return this.hasNext() ? this._parts[this._i + (count || 0)] : null; }; PropertyValueIterator.prototype.next = function(){ return this.hasNext() ? this._parts[this._i++] : null; }; PropertyValueIterator.prototype.previous = function(){ return this._i > 0 ? this._parts[--this._i] : null; }; PropertyValueIterator.prototype.restore = function(){ if (this._marks.length){ this._i = this._marks.pop(); } }; /** * Represents a single part of a CSS property value, meaning that it represents * just one part of the data between ":" and ";". * @param {String} text The text representation of the unit. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. * @namespace parserlib.css * @class PropertyValuePart * @extends parserlib.util.SyntaxUnit * @constructor */ function PropertyValuePart(text, line, col){ SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_VALUE_PART_TYPE); this.type = "unknown"; //figure out what type of data it is var temp; //it is a measurement? if (/^([+\-]?[\d\.]+)([a-z]+)$/i.test(text)){ //dimension this.type = "dimension"; this.value = +RegExp.$1; this.units = RegExp.$2; //try to narrow down switch(this.units.toLowerCase()){ case "em": case "rem": case "ex": case "px": case "cm": case "mm": case "in": case "pt": case "pc": case "ch": this.type = "length"; break; case "deg": case "rad": case "grad": this.type = "angle"; break; case "ms": case "s": this.type = "time"; break; case "hz": case "khz": this.type = "frequency"; break; case "dpi": case "dpcm": this.type = "resolution"; break; //default } } else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage this.type = "percentage"; this.value = +RegExp.$1; } else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage this.type = "percentage"; this.value = +RegExp.$1; } else if (/^([+\-]?\d+)$/i.test(text)){ //integer this.type = "integer"; this.value = +RegExp.$1; } else if (/^([+\-]?[\d\.]+)$/i.test(text)){ //number this.type = "number"; this.value = +RegExp.$1; } else if (/^#([a-f0-9]{3,6})/i.test(text)){ //hexcolor this.type = "color"; temp = RegExp.$1; if (temp.length == 3){ this.red = parseInt(temp.charAt(0)+temp.charAt(0),16); this.green = parseInt(temp.charAt(1)+temp.charAt(1),16); this.blue = parseInt(temp.charAt(2)+temp.charAt(2),16); } else { this.red = parseInt(temp.substring(0,2),16); this.green = parseInt(temp.substring(2,4),16); this.blue = parseInt(temp.substring(4,6),16); } } else if (/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i.test(text)){ //rgb() color with absolute numbers this.type = "color"; this.red = +RegExp.$1; this.green = +RegExp.$2; this.blue = +RegExp.$3; } else if (/^rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //rgb() color with percentages this.type = "color"; this.red = +RegExp.$1 * 255 / 100; this.green = +RegExp.$2 * 255 / 100; this.blue = +RegExp.$3 * 255 / 100; } else if (/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with absolute numbers this.type = "color"; this.red = +RegExp.$1; this.green = +RegExp.$2; this.blue = +RegExp.$3; this.alpha = +RegExp.$4; } else if (/^rgba\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with percentages this.type = "color"; this.red = +RegExp.$1 * 255 / 100; this.green = +RegExp.$2 * 255 / 100; this.blue = +RegExp.$3 * 255 / 100; this.alpha = +RegExp.$4; } else if (/^hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //hsl() this.type = "color"; this.hue = +RegExp.$1; this.saturation = +RegExp.$2 / 100; this.lightness = +RegExp.$3 / 100; } else if (/^hsla\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //hsla() color with percentages this.type = "color"; this.hue = +RegExp.$1; this.saturation = +RegExp.$2 / 100; this.lightness = +RegExp.$3 / 100; this.alpha = +RegExp.$4; } else if (/^url\(["']?([^\)"']+)["']?\)/i.test(text)){ //URI this.type = "uri"; this.uri = RegExp.$1; } else if (/^([^\(]+)\(/i.test(text)){ this.type = "function"; this.name = RegExp.$1; this.value = text; } else if (/^["'][^"']*["']/.test(text)){ //string this.type = "string"; this.value = eval(text); } else if (Colors[text.toLowerCase()]){ //named color this.type = "color"; temp = Colors[text.toLowerCase()].substring(1); this.red = parseInt(temp.substring(0,2),16); this.green = parseInt(temp.substring(2,4),16); this.blue = parseInt(temp.substring(4,6),16); } else if (/^[\,\/]$/.test(text)){ this.type = "operator"; this.value = text; } else if (/^[a-z\-\u0080-\uFFFF][a-z0-9\-\u0080-\uFFFF]*$/i.test(text)){ this.type = "identifier"; this.value = text; } } PropertyValuePart.prototype = new SyntaxUnit(); PropertyValuePart.prototype.constructor = PropertyValuePart; PropertyValuePart.fromToken = function(token){ return new PropertyValuePart(token.value, token.startLine, token.startCol); }; var Pseudos = { ":first-letter": 1, ":first-line": 1, ":before": 1, ":after": 1 }; Pseudos.ELEMENT = 1; Pseudos.CLASS = 2; Pseudos.isElement = function(pseudo){ return pseudo.indexOf("::") === 0 || Pseudos[pseudo.toLowerCase()] == Pseudos.ELEMENT; }; /** * Represents an entire single selector, including all parts but not * including multiple selectors (those separated by commas). * @namespace parserlib.css * @class Selector * @extends parserlib.util.SyntaxUnit * @constructor * @param {Array} parts Array of selectors parts making up this selector. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function Selector(parts, line, col){ SyntaxUnit.call(this, parts.join(" "), line, col, Parser.SELECTOR_TYPE); this.parts = parts; this.specificity = Specificity.calculate(this); } Selector.prototype = new SyntaxUnit(); Selector.prototype.constructor = Selector; /** * Represents a single part of a selector string, meaning a single set of * element name and modifiers. This does not include combinators such as * spaces, +, >, etc. * @namespace parserlib.css * @class SelectorPart * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} elementName The element name in the selector or null * if there is no element name. * @param {Array} modifiers Array of individual modifiers for the element. * May be empty if there are none. * @param {String} text The text representation of the unit. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function SelectorPart(elementName, modifiers, text, line, col){ SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_PART_TYPE); this.elementName = elementName; this.modifiers = modifiers; } SelectorPart.prototype = new SyntaxUnit(); SelectorPart.prototype.constructor = SelectorPart; /** * Represents a selector modifier string, meaning a class name, element name, * element ID, pseudo rule, etc. * @namespace parserlib.css * @class SelectorSubPart * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} text The text representation of the unit. * @param {String} type The type of selector modifier. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function SelectorSubPart(text, type, line, col){ SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_SUB_PART_TYPE); this.type = type; this.args = []; } SelectorSubPart.prototype = new SyntaxUnit(); SelectorSubPart.prototype.constructor = SelectorSubPart; /** * Represents a selector's specificity. * @namespace parserlib.css * @class Specificity * @constructor * @param {int} a Should be 1 for inline styles, zero for stylesheet styles * @param {int} b Number of ID selectors * @param {int} c Number of classes and pseudo classes * @param {int} d Number of element names and pseudo elements */ function Specificity(a, b, c, d){ this.a = a; this.b = b; this.c = c; this.d = d; } Specificity.prototype = { constructor: Specificity, /** * Compare this specificity to another. * @param {Specificity} other The other specificity to compare to. * @return {int} -1 if the other specificity is larger, 1 if smaller, 0 if equal. * @method compare */ compare: function(other){ var comps = ["a", "b", "c", "d"], i, len; for (i=0, len=comps.length; i < len; i++){ if (this[comps[i]] < other[comps[i]]){ return -1; } else if (this[comps[i]] > other[comps[i]]){ return 1; } } return 0; }, /** * Creates a numeric value for the specificity. * @return {int} The numeric value for the specificity. * @method valueOf */ valueOf: function(){ return (this.a * 1000) + (this.b * 100) + (this.c * 10) + this.d; }, /** * Returns a string representation for specificity. * @return {String} The string representation of specificity. * @method toString */ toString: function(){ return this.a + "," + this.b + "," + this.c + "," + this.d; } }; Specificity.calculate = function(selector){ var i, len, part, b=0, c=0, d=0; function updateValues(part){ var i, j, len, num, elementName = part.elementName ? part.elementName.text : "", modifier; if (elementName && elementName.charAt(elementName.length-1) != "*") { d++; } for (i=0, len=part.modifiers.length; i < len; i++){ modifier = part.modifiers[i]; switch(modifier.type){ case "class": case "attribute": c++; break; case "id": b++; break; case "pseudo": if (Pseudos.isElement(modifier.text)){ d++; } else { c++; } break; case "not": for (j=0, num=modifier.args.length; j < num; j++){ updateValues(modifier.args[j]); } } } } for (i=0, len=selector.parts.length; i < len; i++){ part = selector.parts[i]; if (part instanceof SelectorPart){ updateValues(part); } } return new Specificity(0, b, c, d); }; var h = /^[0-9a-fA-F]$/, nonascii = /^[\u0080-\uFFFF]$/, nl = /\n|\r\n|\r|\f/; //----------------------------------------------------------------------------- // Helper functions //----------------------------------------------------------------------------- function isHexDigit(c){ return c !== null && h.test(c); } function isDigit(c){ return c !== null && /\d/.test(c); } function isWhitespace(c){ return c !== null && /\s/.test(c); } function isNewLine(c){ return c !== null && nl.test(c); } function isNameStart(c){ return c !== null && (/[a-z_\u0080-\uFFFF\\]/i.test(c)); } function isNameChar(c){ return c !== null && (isNameStart(c) || /[0-9\-\\]/.test(c)); } function isIdentStart(c){ return c !== null && (isNameStart(c) || /\-\\/.test(c)); } function mix(receiver, supplier){ for (var prop in supplier){ if (supplier.hasOwnProperty(prop)){ receiver[prop] = supplier[prop]; } } return receiver; } //----------------------------------------------------------------------------- // CSS Token Stream //----------------------------------------------------------------------------- /** * A token stream that produces CSS tokens. * @param {String|Reader} input The source of text to tokenize. * @constructor * @class TokenStream * @namespace parserlib.css */ function TokenStream(input){ TokenStreamBase.call(this, input, Tokens); } TokenStream.prototype = mix(new TokenStreamBase(), { /** * Overrides the TokenStreamBase method of the same name * to produce CSS tokens. * @param {variant} channel The name of the channel to use * for the next token. * @return {Object} A token object representing the next token. * @method _getToken * @private */ _getToken: function(channel){ var c, reader = this._reader, token = null, startLine = reader.getLine(), startCol = reader.getCol(); c = reader.read(); while(c){ switch(c){ /* * Potential tokens: * - COMMENT * - SLASH * - CHAR */ case "/": if(reader.peek() == "*"){ token = this.commentToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; case "|": case "~": case "^": case "$": case "*": if(reader.peek() == "="){ token = this.comparisonToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; case "\"": case "'": token = this.stringToken(c, startLine, startCol); break; case "#": if (isNameChar(reader.peek())){ token = this.hashToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; case ".": if (isDigit(reader.peek())){ token = this.numberToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; case "-": if (reader.peek() == "-"){ //could be closing HTML-style comment token = this.htmlCommentEndToken(c, startLine, startCol); } else if (isNameStart(reader.peek())){ token = this.identOrFunctionToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; case "!": token = this.importantToken(c, startLine, startCol); break; case "@": token = this.atRuleToken(c, startLine, startCol); break; case ":": token = this.notToken(c, startLine, startCol); break; case "<": token = this.htmlCommentStartToken(c, startLine, startCol); break; case "U": case "u": if (reader.peek() == "+"){ token = this.unicodeRangeToken(c, startLine, startCol); break; } /* falls through */ default: /* * Potential tokens: * - NUMBER * - DIMENSION * - LENGTH * - FREQ * - TIME * - EMS * - EXS * - ANGLE */ if (isDigit(c)){ token = this.numberToken(c, startLine, startCol); } else /* * Potential tokens: * - S */ if (isWhitespace(c)){ token = this.whitespaceToken(c, startLine, startCol); } else /* * Potential tokens: * - IDENT */ if (isIdentStart(c)){ token = this.identOrFunctionToken(c, startLine, startCol); } else /* * Potential tokens: * - CHAR * - PLUS */ { token = this.charToken(c, startLine, startCol); } } //make sure this token is wanted //TODO: check channel break; } if (!token && c === null){ token = this.createToken(Tokens.EOF,null,startLine,startCol); } return token; }, //------------------------------------------------------------------------- // Methods to create tokens //------------------------------------------------------------------------- /** * Produces a token based on available data and the current * reader position information. This method is called by other * private methods to create tokens and is never called directly. * @param {int} tt The token type. * @param {String} value The text value of the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @param {Object} options (Optional) Specifies a channel property * to indicate that a different channel should be scanned * and/or a hide property indicating that the token should * be hidden. * @return {Object} A token object. * @method createToken */ createToken: function(tt, value, startLine, startCol, options){ var reader = this._reader; options = options || {}; return { value: value, type: tt, channel: options.channel, hide: options.hide || false, startLine: startLine, startCol: startCol, endLine: reader.getLine(), endCol: reader.getCol() }; }, //------------------------------------------------------------------------- // Methods to create specific tokens //------------------------------------------------------------------------- /** * Produces a token for any at-rule. If the at-rule is unknown, then * the token is for a single "@" character. * @param {String} first The first character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method atRuleToken */ atRuleToken: function(first, startLine, startCol){ var rule = first, reader = this._reader, tt = Tokens.CHAR, valid = false, ident, c; reader.mark(); //try to find the at-keyword ident = this.readName(); rule = first + ident; tt = Tokens.type(rule.toLowerCase()); //if it's not valid, use the first character only and reset the reader if (tt == Tokens.CHAR || tt == Tokens.UNKNOWN){ if (rule.length > 1){ tt = Tokens.UNKNOWN_SYM; } else { tt = Tokens.CHAR; rule = first; reader.reset(); } } return this.createToken(tt, rule, startLine, startCol); }, /** * Produces a character token based on the given character * and location in the stream. If there's a special (non-standard) * token name, this is used; otherwise CHAR is used. * @param {String} c The character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method charToken */ charToken: function(c, startLine, startCol){ var tt = Tokens.type(c); if (tt == -1){ tt = Tokens.CHAR; } return this.createToken(tt, c, startLine, startCol); }, /** * Produces a character token based on the given character * and location in the stream. If there's a special (non-standard) * token name, this is used; otherwise CHAR is used. * @param {String} first The first character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method commentToken */ commentToken: function(first, startLine, startCol){ var reader = this._reader, comment = this.readComment(first); return this.createToken(Tokens.COMMENT, comment, startLine, startCol); }, /** * Produces a comparison token based on the given character * and location in the stream. The next character must be * read and is already known to be an equals sign. * @param {String} c The character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method comparisonToken */ comparisonToken: function(c, startLine, startCol){ var reader = this._reader, comparison = c + reader.read(), tt = Tokens.type(comparison) || Tokens.CHAR; return this.createToken(tt, comparison, startLine, startCol); }, /** * Produces a hash token based on the specified information. The * first character provided is the pound sign (#) and then this * method reads a name afterward. * @param {String} first The first character (#) in the hash name. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method hashToken */ hashToken: function(first, startLine, startCol){ var reader = this._reader, name = this.readName(first); return this.createToken(Tokens.HASH, name, startLine, startCol); }, /** * Produces a CDO or CHAR token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method htmlCommentStartToken */ htmlCommentStartToken: function(first, startLine, startCol){ var reader = this._reader, text = first; reader.mark(); text += reader.readCount(3); if (text == "<!--"){ return this.createToken(Tokens.CDO, text, startLine, startCol); } else { reader.reset(); return this.charToken(first, startLine, startCol); } }, /** * Produces a CDC or CHAR token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method htmlCommentEndToken */ htmlCommentEndToken: function(first, startLine, startCol){ var reader = this._reader, text = first; reader.mark(); text += reader.readCount(2); if (text == "-->"){ return this.createToken(Tokens.CDC, text, startLine, startCol); } else { reader.reset(); return this.charToken(first, startLine, startCol); } }, /** * Produces an IDENT or FUNCTION token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the identifier. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method identOrFunctionToken */ identOrFunctionToken: function(first, startLine, startCol){ var reader = this._reader, ident = this.readName(first), tt = Tokens.IDENT; //if there's a left paren immediately after, it's a URI or function if (reader.peek() == "("){ ident += reader.read(); if (ident.toLowerCase() == "url("){ tt = Tokens.URI; ident = this.readURI(ident); //didn't find a valid URL or there's no closing paren if (ident.toLowerCase() == "url("){ tt = Tokens.FUNCTION; } } else { tt = Tokens.FUNCTION; } } else if (reader.peek() == ":"){ //might be an IE function //IE-specific functions always being with progid: if (ident.toLowerCase() == "progid"){ ident += reader.readTo("("); tt = Tokens.IE_FUNCTION; } } return this.createToken(tt, ident, startLine, startCol); }, /** * Produces an IMPORTANT_SYM or CHAR token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method importantToken */ importantToken: function(first, startLine, startCol){ var reader = this._reader, important = first, tt = Tokens.CHAR, temp, c; reader.mark(); c = reader.read(); while(c){ //there can be a comment in here if (c == "/"){ //if the next character isn't a star, then this isn't a valid !important token if (reader.peek() != "*"){ break; } else { temp = this.readComment(c); if (temp === ""){ //broken! break; } } } else if (isWhitespace(c)){ important += c + this.readWhitespace(); } else if (/i/i.test(c)){ temp = reader.readCount(8); if (/mportant/i.test(temp)){ important += c + temp; tt = Tokens.IMPORTANT_SYM; } break; //we're done } else { break; } c = reader.read(); } if (tt == Tokens.CHAR){ reader.reset(); return this.charToken(first, startLine, startCol); } else { return this.createToken(tt, important, startLine, startCol); } }, /** * Produces a NOT or CHAR token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method notToken */ notToken: function(first, startLine, startCol){ var reader = this._reader, text = first; reader.mark(); text += reader.readCount(4); if (text.toLowerCase() == ":not("){ return this.createToken(Tokens.NOT, text, startLine, startCol); } else { reader.reset(); return this.charToken(first, startLine, startCol); } }, /** * Produces a number token based on the given character * and location in the stream. This may return a token of * NUMBER, EMS, EXS, LENGTH, ANGLE, TIME, FREQ, DIMENSION, * or PERCENTAGE. * @param {String} first The first character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method numberToken */ numberToken: function(first, startLine, startCol){ var reader = this._reader, value = this.readNumber(first), ident, tt = Tokens.NUMBER, c = reader.peek(); if (isIdentStart(c)){ ident = this.readName(reader.read()); value += ident; if (/^em$|^ex$|^px$|^gd$|^rem$|^vw$|^vh$|^vm$|^ch$|^cm$|^mm$|^in$|^pt$|^pc$/i.test(ident)){ tt = Tokens.LENGTH; } else if (/^deg|^rad$|^grad$/i.test(ident)){ tt = Tokens.ANGLE; } else if (/^ms$|^s$/i.test(ident)){ tt = Tokens.TIME; } else if (/^hz$|^khz$/i.test(ident)){ tt = Tokens.FREQ; } else if (/^dpi$|^dpcm$/i.test(ident)){ tt = Tokens.RESOLUTION; } else { tt = Tokens.DIMENSION; } } else if (c == "%"){ value += reader.read(); tt = Tokens.PERCENTAGE; } return this.createToken(tt, value, startLine, startCol); }, /** * Produces a string token based on the given character * and location in the stream. Since strings may be indicated * by single or double quotes, a failure to match starting * and ending quotes results in an INVALID token being generated. * The first character in the string is passed in and then * the rest are read up to and including the final quotation mark. * @param {String} first The first character in the string. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method stringToken */ stringToken: function(first, startLine, startCol){ var delim = first, string = first, reader = this._reader, prev = first, tt = Tokens.STRING, c = reader.read(); while(c){ string += c; //if the delimiter is found with an escapement, we're done. if (c == delim && prev != "\\"){ break; } //if there's a newline without an escapement, it's an invalid string if (isNewLine(reader.peek()) && c != "\\"){ tt = Tokens.INVALID; break; } //save previous and get next prev = c; c = reader.read(); } //if c is null, that means we're out of input and the string was never closed if (c === null){ tt = Tokens.INVALID; } return this.createToken(tt, string, startLine, startCol); }, unicodeRangeToken: function(first, startLine, startCol){ var reader = this._reader, value = first, temp, tt = Tokens.CHAR; //then it should be a unicode range if (reader.peek() == "+"){ reader.mark(); value += reader.read(); value += this.readUnicodeRangePart(true); //ensure there's an actual unicode range here if (value.length == 2){ reader.reset(); } else { tt = Tokens.UNICODE_RANGE; //if there's a ? in the first part, there can't be a second part if (value.indexOf("?") == -1){ if (reader.peek() == "-"){ reader.mark(); temp = reader.read(); temp += this.readUnicodeRangePart(false); //if there's not another value, back up and just take the first if (temp.length == 1){ reader.reset(); } else { value += temp; } } } } } return this.createToken(tt, value, startLine, startCol); }, /** * Produces a S token based on the specified information. Since whitespace * may have multiple characters, this consumes all whitespace characters * into a single token. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method whitespaceToken */ whitespaceToken: function(first, startLine, startCol){ var reader = this._reader, value = first + this.readWhitespace(); return this.createToken(Tokens.S, value, startLine, startCol); }, //------------------------------------------------------------------------- // Methods to read values from the string stream //------------------------------------------------------------------------- readUnicodeRangePart: function(allowQuestionMark){ var reader = this._reader, part = "", c = reader.peek(); //first read hex digits while(isHexDigit(c) && part.length < 6){ reader.read(); part += c; c = reader.peek(); } //then read question marks if allowed if (allowQuestionMark){ while(c == "?" && part.length < 6){ reader.read(); part += c; c = reader.peek(); } } //there can't be any other characters after this point return part; }, readWhitespace: function(){ var reader = this._reader, whitespace = "", c = reader.peek(); while(isWhitespace(c)){ reader.read(); whitespace += c; c = reader.peek(); } return whitespace; }, readNumber: function(first){ var reader = this._reader, number = first, hasDot = (first == "."), c = reader.peek(); while(c){ if (isDigit(c)){ number += reader.read(); } else if (c == "."){ if (hasDot){ break; } else { hasDot = true; number += reader.read(); } } else { break; } c = reader.peek(); } return number; }, readString: function(){ var reader = this._reader, delim = reader.read(), string = delim, prev = delim, c = reader.peek(); while(c){ c = reader.read(); string += c; //if the delimiter is found with an escapement, we're done. if (c == delim && prev != "\\"){ break; } //if there's a newline without an escapement, it's an invalid string if (isNewLine(reader.peek()) && c != "\\"){ string = ""; break; } //save previous and get next prev = c; c = reader.peek(); } //if c is null, that means we're out of input and the string was never closed if (c === null){ string = ""; } return string; }, readURI: function(first){ var reader = this._reader, uri = first, inner = "", c = reader.peek(); reader.mark(); //skip whitespace before while(c && isWhitespace(c)){ reader.read(); c = reader.peek(); } //it's a string if (c == "'" || c == "\""){ inner = this.readString(); } else { inner = this.readURL(); } c = reader.peek(); //skip whitespace after while(c && isWhitespace(c)){ reader.read(); c = reader.peek(); } //if there was no inner value or the next character isn't closing paren, it's not a URI if (inner === "" || c != ")"){ uri = first; reader.reset(); } else { uri += inner + reader.read(); } return uri; }, readURL: function(){ var reader = this._reader, url = "", c = reader.peek(); //TODO: Check for escape and nonascii while (/^[!#$%&\\*-~]$/.test(c)){ url += reader.read(); c = reader.peek(); } return url; }, readName: function(first){ var reader = this._reader, ident = first || "", c = reader.peek(); while(true){ if (c == "\\"){ ident += this.readEscape(reader.read()); c = reader.peek(); } else if(c && isNameChar(c)){ ident += reader.read(); c = reader.peek(); } else { break; } } return ident; }, readEscape: function(first){ var reader = this._reader, cssEscape = first || "", i = 0, c = reader.peek(); if (isHexDigit(c)){ do { cssEscape += reader.read(); c = reader.peek(); } while(c && isHexDigit(c) && ++i < 6); } if (cssEscape.length == 3 && /\s/.test(c) || cssEscape.length == 7 || cssEscape.length == 1){ reader.read(); } else { c = ""; } return cssEscape + c; }, readComment: function(first){ var reader = this._reader, comment = first || "", c = reader.read(); if (c == "*"){ while(c){ comment += c; //look for end of comment if (comment.length > 2 && c == "*" && reader.peek() == "/"){ comment += reader.read(); break; } c = reader.read(); } return comment; } else { return ""; } } }); var Tokens = [ /* * The following token names are defined in CSS3 Grammar: http://www.w3.org/TR/css3-syntax/#lexical */ //HTML-style comments { name: "CDO"}, { name: "CDC"}, //ignorables { name: "S", whitespace: true/*, channel: "ws"*/}, { name: "COMMENT", comment: true, hide: true, channel: "comment" }, //attribute equality { name: "INCLUDES", text: "~="}, { name: "DASHMATCH", text: "|="}, { name: "PREFIXMATCH", text: "^="}, { name: "SUFFIXMATCH", text: "$="}, { name: "SUBSTRINGMATCH", text: "*="}, //identifier types { name: "STRING"}, { name: "IDENT"}, { name: "HASH"}, //at-keywords { name: "IMPORT_SYM", text: "@import"}, { name: "PAGE_SYM", text: "@page"}, { name: "MEDIA_SYM", text: "@media"}, { name: "FONT_FACE_SYM", text: "@font-face"}, { name: "CHARSET_SYM", text: "@charset"}, { name: "NAMESPACE_SYM", text: "@namespace"}, { name: "UNKNOWN_SYM" }, //{ name: "ATKEYWORD"}, //CSS3 animations { name: "KEYFRAMES_SYM", text: [ "@keyframes", "@-webkit-keyframes", "@-moz-keyframes", "@-ms-keyframes" ] }, //important symbol { name: "IMPORTANT_SYM"}, //measurements { name: "LENGTH"}, { name: "ANGLE"}, { name: "TIME"}, { name: "FREQ"}, { name: "DIMENSION"}, { name: "PERCENTAGE"}, { name: "NUMBER"}, //functions { name: "URI"}, { name: "FUNCTION"}, //Unicode ranges { name: "UNICODE_RANGE"}, /* * The following token names are defined in CSS3 Selectors: http://www.w3.org/TR/css3-selectors/#selector-syntax */ //invalid string { name: "INVALID"}, //combinators { name: "PLUS", text: "+" }, { name: "GREATER", text: ">"}, { name: "COMMA", text: ","}, { name: "TILDE", text: "~"}, //modifier { name: "NOT"}, /* * Defined in CSS3 Paged Media */ { name: "TOPLEFTCORNER_SYM", text: "@top-left-corner"}, { name: "TOPLEFT_SYM", text: "@top-left"}, { name: "TOPCENTER_SYM", text: "@top-center"}, { name: "TOPRIGHT_SYM", text: "@top-right"}, { name: "TOPRIGHTCORNER_SYM", text: "@top-right-corner"}, { name: "BOTTOMLEFTCORNER_SYM", text: "@bottom-left-corner"}, { name: "BOTTOMLEFT_SYM", text: "@bottom-left"}, { name: "BOTTOMCENTER_SYM", text: "@bottom-center"}, { name: "BOTTOMRIGHT_SYM", text: "@bottom-right"}, { name: "BOTTOMRIGHTCORNER_SYM", text: "@bottom-right-corner"}, { name: "LEFTTOP_SYM", text: "@left-top"}, { name: "LEFTMIDDLE_SYM", text: "@left-middle"}, { name: "LEFTBOTTOM_SYM", text: "@left-bottom"}, { name: "RIGHTTOP_SYM", text: "@right-top"}, { name: "RIGHTMIDDLE_SYM", text: "@right-middle"}, { name: "RIGHTBOTTOM_SYM", text: "@right-bottom"}, /* * The following token names are defined in CSS3 Media Queries: http://www.w3.org/TR/css3-mediaqueries/#syntax */ /*{ name: "MEDIA_ONLY", state: "media"}, { name: "MEDIA_NOT", state: "media"}, { name: "MEDIA_AND", state: "media"},*/ { name: "RESOLUTION", state: "media"}, /* * The following token names are not defined in any CSS specification but are used by the lexer. */ //not a real token, but useful for stupid IE filters { name: "IE_FUNCTION" }, //part of CSS3 grammar but not the Flex code { name: "CHAR" }, //TODO: Needed? //Not defined as tokens, but might as well be { name: "PIPE", text: "|" }, { name: "SLASH", text: "/" }, { name: "MINUS", text: "-" }, { name: "STAR", text: "*" }, { name: "LBRACE", text: "{" }, { name: "RBRACE", text: "}" }, { name: "LBRACKET", text: "[" }, { name: "RBRACKET", text: "]" }, { name: "EQUALS", text: "=" }, { name: "COLON", text: ":" }, { name: "SEMICOLON", text: ";" }, { name: "LPAREN", text: "(" }, { name: "RPAREN", text: ")" }, { name: "DOT", text: "." } ]; (function(){ var nameMap = [], typeMap = {}; Tokens.UNKNOWN = -1; Tokens.unshift({name:"EOF"}); for (var i=0, len = Tokens.length; i < len; i++){ nameMap.push(Tokens[i].name); Tokens[Tokens[i].name] = i; if (Tokens[i].text){ if (Tokens[i].text instanceof Array){ for (var j=0; j < Tokens[i].text.length; j++){ typeMap[Tokens[i].text[j]] = i; } } else { typeMap[Tokens[i].text] = i; } } } Tokens.name = function(tt){ return nameMap[tt]; }; Tokens.type = function(c){ return typeMap[c] || -1; }; })(); //This file will likely change a lot! Very experimental! /*global Properties, ValidationTypes, ValidationError, PropertyValueIterator */ var Validation = { validate: function(property, value){ //normalize name var name = property.toString().toLowerCase(), parts = value.parts, expression = new PropertyValueIterator(value), spec = Properties[name], part, valid, j, count, msg, types, last, literals, max, multi, group; if (!spec) { if (name.indexOf("-") !== 0){ //vendor prefixed are ok throw new ValidationError("Unknown property '" + property + "'.", property.line, property.col); } } else if (typeof spec != "number"){ //initialization if (typeof spec == "string"){ if (spec.indexOf("||") > -1) { this.groupProperty(spec, expression); } else { this.singleProperty(spec, expression, 1); } } else if (spec.multi) { this.multiProperty(spec.multi, expression, spec.comma, spec.max || Infinity); } else if (typeof spec == "function") { spec(expression); } } }, singleProperty: function(types, expression, max, partial) { var result = false, value = expression.value, count = 0, part; while (expression.hasNext() && count < max) { result = ValidationTypes.isAny(expression, types); if (!result) { break; } count++; } if (!result) { if (expression.hasNext() && !expression.isFirst()) { part = expression.peek(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col); } } else if (expression.hasNext()) { part = expression.next(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } }, multiProperty: function (types, expression, comma, max) { var result = false, value = expression.value, count = 0, sep = false, part; while(expression.hasNext() && !result && count < max) { if (ValidationTypes.isAny(expression, types)) { count++; if (!expression.hasNext()) { result = true; } else if (comma) { if (expression.peek() == ",") { part = expression.next(); } else { break; } } } else { break; } } if (!result) { if (expression.hasNext() && !expression.isFirst()) { part = expression.peek(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { part = expression.previous(); if (comma && part == ",") { throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col); } } } else if (expression.hasNext()) { part = expression.next(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } }, groupProperty: function (types, expression, comma) { var result = false, value = expression.value, typeCount = types.split("||").length, groups = { count: 0 }, partial = false, name, part; while(expression.hasNext() && !result) { name = ValidationTypes.isAnyOfGroup(expression, types); if (name) { //no dupes if (groups[name]) { break; } else { groups[name] = 1; groups.count++; partial = true; if (groups.count == typeCount || !expression.hasNext()) { result = true; } } } else { break; } } if (!result) { if (partial && expression.hasNext()) { part = expression.peek(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col); } } else if (expression.hasNext()) { part = expression.next(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } } }; function ValidationError(message, line, col){ /** * The column at which the error occurred. * @type int * @property col */ this.col = col; this.line = line; this.message = message; } //inherit from Error ValidationError.prototype = new Error(); //This file will likely change a lot! Very experimental! /*global Properties, Validation, ValidationError, PropertyValueIterator, console*/ var ValidationTypes = { isLiteral: function (part, literals) { var text = part.text.toString().toLowerCase(), args = literals.split(" | "), i, len, found = false; for (i=0,len=args.length; i < len && !found; i++){ if (text == args[i]){ found = true; } } return found; }, isSimple: function(type) { return !!this.simple[type]; }, isComplex: function(type) { return !!this.complex[type]; }, /** * Determines if the next part(s) of the given expression * are any of the given types. */ isAny: function (expression, types) { var args = types.split(" | "), i, len, found = false; for (i=0,len=args.length; i < len && !found && expression.hasNext(); i++){ found = this.isType(expression, args[i]); } return found; }, /** * Determines if the next part(s) of the given expresion * are one of a group. */ isAnyOfGroup: function(expression, types) { var args = types.split(" || "), i, len, found = false; for (i=0,len=args.length; i < len && !found; i++){ found = this.isType(expression, args[i]); } return found ? args[i-1] : false; }, /** * Determines if the next part(s) of the given expression * are of a given type. */ isType: function (expression, type) { var part = expression.peek(), result = false; if (type.charAt(0) != "<") { result = this.isLiteral(part, type); if (result) { expression.next(); } } else if (this.simple[type]) { result = this.simple[type](part); if (result) { expression.next(); } } else { result = this.complex[type](expression); } return result; }, simple: { "<absolute-size>": function(part){ return ValidationTypes.isLiteral(part, "xx-small | x-small | small | medium | large | x-large | xx-large"); }, "<attachment>": function(part){ return ValidationTypes.isLiteral(part, "scroll | fixed | local"); }, "<attr>": function(part){ return part.type == "function" && part.name == "attr"; }, "<bg-image>": function(part){ return this["<image>"](part) || this["<gradient>"](part) || part == "none"; }, "<gradient>": function(part) { return part.type == "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?(?:repeating\-)?(?:radial|linear)\-gradient/i.test(part); }, "<box>": function(part){ return ValidationTypes.isLiteral(part, "padding-box | border-box | content-box"); }, "<content>": function(part){ return part.type == "function" && part.name == "content"; }, "<relative-size>": function(part){ return ValidationTypes.isLiteral(part, "smaller | larger"); }, //any identifier "<ident>": function(part){ return part.type == "identifier"; }, "<length>": function(part){ return part.type == "length" || part.type == "number" || part.type == "integer" || part == "0"; }, "<color>": function(part){ return part.type == "color" || part == "transparent"; }, "<number>": function(part){ return part.type == "number" || this["<integer>"](part); }, "<integer>": function(part){ return part.type == "integer"; }, "<line>": function(part){ return part.type == "integer"; }, "<angle>": function(part){ return part.type == "angle"; }, "<uri>": function(part){ return part.type == "uri"; }, "<image>": function(part){ return this["<uri>"](part); }, "<percentage>": function(part){ return part.type == "percentage" || part == "0"; }, "<border-width>": function(part){ return this["<length>"](part) || ValidationTypes.isLiteral(part, "thin | medium | thick"); }, "<border-style>": function(part){ return ValidationTypes.isLiteral(part, "none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset"); }, "<margin-width>": function(part){ return this["<length>"](part) || this["<percentage>"](part) || ValidationTypes.isLiteral(part, "auto"); }, "<padding-width>": function(part){ return this["<length>"](part) || this["<percentage>"](part); }, "<shape>": function(part){ return part.type == "function" && (part.name == "rect" || part.name == "inset-rect"); }, "<time>": function(part) { return part.type == "time"; } }, complex: { "<bg-position>": function(expression){ var types = this, result = false, numeric = "<percentage> | <length>", xDir = "left | center | right", yDir = "top | center | bottom", part, i, len; if (ValidationTypes.isAny(expression, "top | bottom")) { result = true; } else { //must be two-part if (ValidationTypes.isAny(expression, numeric)){ if (expression.hasNext()){ result = ValidationTypes.isAny(expression, numeric + " | " + yDir); } } else if (ValidationTypes.isAny(expression, xDir)){ if (expression.hasNext()){ //two- or three-part if (ValidationTypes.isAny(expression, yDir)){ result = true; ValidationTypes.isAny(expression, numeric); } else if (ValidationTypes.isAny(expression, numeric)){ //could also be two-part, so check the next part if (ValidationTypes.isAny(expression, yDir)){ ValidationTypes.isAny(expression, numeric); } result = true; } } } } return result; }, "<bg-size>": function(expression){ //<bg-size> = [ <length> | <percentage> | auto ]{1,2} | cover | contain var types = this, result = false, numeric = "<percentage> | <length> | auto", part, i, len; if (ValidationTypes.isAny(expression, "cover | contain")) { result = true; } else if (ValidationTypes.isAny(expression, numeric)) { result = true; ValidationTypes.isAny(expression, numeric); } return result; }, "<repeat-style>": function(expression){ //repeat-x | repeat-y | [repeat | space | round | no-repeat]{1,2} var result = false, values = "repeat | space | round | no-repeat", part; if (expression.hasNext()){ part = expression.next(); if (ValidationTypes.isLiteral(part, "repeat-x | repeat-y")) { result = true; } else if (ValidationTypes.isLiteral(part, values)) { result = true; if (expression.hasNext() && ValidationTypes.isLiteral(expression.peek(), values)) { expression.next(); } } } return result; }, "<shadow>": function(expression) { //inset? && [ <length>{2,4} && <color>? ] var result = false, count = 0, inset = false, color = false, part; if (expression.hasNext()) { if (ValidationTypes.isAny(expression, "inset")){ inset = true; } if (ValidationTypes.isAny(expression, "<color>")) { color = true; } while (ValidationTypes.isAny(expression, "<length>") && count < 4) { count++; } if (expression.hasNext()) { if (!color) { ValidationTypes.isAny(expression, "<color>"); } if (!inset) { ValidationTypes.isAny(expression, "inset"); } } result = (count >= 2 && count <= 4); } return result; }, "<x-one-radius>": function(expression) { //[ <length> | <percentage> ] [ <length> | <percentage> ]? var result = false, count = 0, numeric = "<length> | <percentage>", part; if (ValidationTypes.isAny(expression, numeric)){ result = true; ValidationTypes.isAny(expression, numeric); } return result; } } }; parserlib.css = { Colors :Colors, Combinator :Combinator, Parser :Parser, PropertyName :PropertyName, PropertyValue :PropertyValue, PropertyValuePart :PropertyValuePart, MediaFeature :MediaFeature, MediaQuery :MediaQuery, Selector :Selector, SelectorPart :SelectorPart, SelectorSubPart :SelectorSubPart, Specificity :Specificity, TokenStream :TokenStream, Tokens :Tokens, ValidationError :ValidationError }; })(); /*global parserlib, Reporter*/ var CSSLint = (function(){ var rules = [], formatters = [], api = new parserlib.util.EventTarget(); api.version = "0.9.7"; //------------------------------------------------------------------------- // Rule Management //------------------------------------------------------------------------- /** * Adds a new rule to the engine. * @param {Object} rule The rule to add. * @method addRule */ api.addRule = function(rule){ rules.push(rule); rules[rule.id] = rule; }; api.clearRules = function(){ rules = []; }; api.getRules = function(){ return [].concat(rules).sort(function(a,b){ return a.id > b.id ? 1 : 0; }); }; //------------------------------------------------------------------------- // Formatters //------------------------------------------------------------------------- /** * Adds a new formatter to the engine. * @param {Object} formatter The formatter to add. * @method addFormatter */ api.addFormatter = function(formatter) { // formatters.push(formatter); formatters[formatter.id] = formatter; }; api.getFormatter = function(formatId){ return formatters[formatId]; }; api.format = function(results, filename, formatId, options) { var formatter = this.getFormatter(formatId), result = null; if (formatter){ result = formatter.startFormat(); result += formatter.formatResults(results, filename, options || {}); result += formatter.endFormat(); } return result; }; api.hasFormat = function(formatId){ return formatters.hasOwnProperty(formatId); }; //------------------------------------------------------------------------- // Verification //------------------------------------------------------------------------- /** * Starts the verification process for the given CSS text. * @param {String} text The CSS text to verify. * @param {Object} ruleset (Optional) List of rules to apply. If null, then * all rules are used. If a rule has a value of 1 then it's a warning, * a value of 2 means it's an error. * @return {Object} Results of the verification. * @method verify */ api.verify = function(text, ruleset){ var i = 0, len = rules.length, reporter, lines, report, parser = new parserlib.css.Parser({ starHack: true, ieFilters: true, underscoreHack: true, strict: false }); lines = text.replace(/\n\r?/g, "$split$").split('$split$'); if (!ruleset){ ruleset = {}; while (i < len){ ruleset[rules[i++].id] = 1; //by default, everything is a warning } } reporter = new Reporter(lines, ruleset); ruleset.errors = 2; //always report parsing errors as errors for (i in ruleset){ if(ruleset.hasOwnProperty(i)){ if (rules[i]){ rules[i].init(parser, reporter); } } } //capture most horrible error type try { parser.parse(text); } catch (ex) { reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {}); } report = { messages : reporter.messages, stats : reporter.stats }; //sort by line numbers, rollups at the bottom report.messages.sort(function (a, b){ if (a.rollup && !b.rollup){ return 1; } else if (!a.rollup && b.rollup){ return -1; } else { return a.line - b.line; } }); return report; }; //------------------------------------------------------------------------- // Publish the API //------------------------------------------------------------------------- return api; })(); /** * An instance of Report is used to report results of the * verification back to the main API. * @class Reporter * @constructor * @param {String[]} lines The text lines of the source. * @param {Object} ruleset The set of rules to work with, including if * they are errors or warnings. */ function Reporter(lines, ruleset){ /** * List of messages being reported. * @property messages * @type String[] */ this.messages = []; this.stats = []; this.lines = lines; this.ruleset = ruleset; } Reporter.prototype = { //restore constructor constructor: Reporter, /** * Report an error. * @param {String} message The message to store. * @param {int} line The line number. * @param {int} col The column number. * @param {Object} rule The rule this message relates to. * @method error */ error: function(message, line, col, rule){ this.messages.push({ type : "error", line : line, col : col, message : message, evidence: this.lines[line-1], rule : rule || {} }); }, /** * Report an warning. * @param {String} message The message to store. * @param {int} line The line number. * @param {int} col The column number. * @param {Object} rule The rule this message relates to. * @method warn * @deprecated Use report instead. */ warn: function(message, line, col, rule){ this.report(message, line, col, rule); }, /** * Report an issue. * @param {String} message The message to store. * @param {int} line The line number. * @param {int} col The column number. * @param {Object} rule The rule this message relates to. * @method report */ report: function(message, line, col, rule){ this.messages.push({ type : this.ruleset[rule.id] == 2 ? "error" : "warning", line : line, col : col, message : message, evidence: this.lines[line-1], rule : rule }); }, /** * Report some informational text. * @param {String} message The message to store. * @param {int} line The line number. * @param {int} col The column number. * @param {Object} rule The rule this message relates to. * @method info */ info: function(message, line, col, rule){ this.messages.push({ type : "info", line : line, col : col, message : message, evidence: this.lines[line-1], rule : rule }); }, /** * Report some rollup error information. * @param {String} message The message to store. * @param {Object} rule The rule this message relates to. * @method rollupError */ rollupError: function(message, rule){ this.messages.push({ type : "error", rollup : true, message : message, rule : rule }); }, /** * Report some rollup warning information. * @param {String} message The message to store. * @param {Object} rule The rule this message relates to. * @method rollupWarn */ rollupWarn: function(message, rule){ this.messages.push({ type : "warning", rollup : true, message : message, rule : rule }); }, /** * Report a statistic. * @param {String} name The name of the stat to store. * @param {Variant} value The value of the stat. * @method stat */ stat: function(name, value){ this.stats[name] = value; } }; //expose for testing purposes CSSLint._Reporter = Reporter; /* * Utility functions that make life easier. */ CSSLint.Util = { /* * Adds all properties from supplier onto receiver, * overwriting if the same name already exists on * reciever. * @param {Object} The object to receive the properties. * @param {Object} The object to provide the properties. * @return {Object} The receiver */ mix: function(receiver, supplier){ var prop; for (prop in supplier){ if (supplier.hasOwnProperty(prop)){ receiver[prop] = supplier[prop]; } } return prop; }, /* * Polyfill for array indexOf() method. * @param {Array} values The array to search. * @param {Variant} value The value to search for. * @return {int} The index of the value if found, -1 if not. */ indexOf: function(values, value){ if (values.indexOf){ return values.indexOf(value); } else { for (var i=0, len=values.length; i < len; i++){ if (values[i] === value){ return i; } } return -1; } }, /* * Polyfill for array forEach() method. * @param {Array} values The array to operate on. * @param {Function} func The function to call on each item. * @return {void} */ forEach: function(values, func) { if (values.forEach){ return values.forEach(func); } else { for (var i=0, len=values.length; i < len; i++){ func(values[i], i, values); } } } }; /* * Rule: Don't use adjoining classes (.foo.bar). */ CSSLint.addRule({ //rule information id: "adjoining-classes", name: "Disallow adjoining classes", desc: "Don't use adjoining classes.", browsers: "IE6", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, classCount, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ classCount = 0; for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (modifier.type == "class"){ classCount++; } if (classCount > 1){ reporter.report("Don't use adjoining classes.", part.line, part.col, rule); } } } } } }); } }); /* * Rule: Don't use width or height when using padding or border. */ CSSLint.addRule({ //rule information id: "box-model", name: "Beware of broken box size", desc: "Don't use width or height when using padding or border.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, widthProperties = { border: 1, "border-left": 1, "border-right": 1, padding: 1, "padding-left": 1, "padding-right": 1 }, heightProperties = { border: 1, "border-bottom": 1, "border-top": 1, padding: 1, "padding-bottom": 1, "padding-top": 1 }, properties; function startRule(){ properties = {}; } function endRule(){ var prop; if (properties.height){ for (prop in heightProperties){ if (heightProperties.hasOwnProperty(prop) && properties[prop]){ //special case for padding if (!(prop == "padding" && properties[prop].value.parts.length === 2 && properties[prop].value.parts[0].value === 0)){ reporter.report("Using height with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule); } } } } if (properties.width){ for (prop in widthProperties){ if (widthProperties.hasOwnProperty(prop) && properties[prop]){ if (!(prop == "padding" && properties[prop].value.parts.length === 2 && properties[prop].value.parts[1].value === 0)){ reporter.report("Using width with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule); } } } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); if (heightProperties[name] || widthProperties[name]){ if (!/^0\S*$/.test(event.value) && !(name == "border" && event.value == "none")){ properties[name] = { line: event.property.line, col: event.property.col, value: event.value }; } } else { if (name == "width" || name == "height"){ properties[name] = 1; } } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); parser.addListener("endpage", endRule); parser.addListener("endpagemargin", endRule); parser.addListener("endkeyframerule", endRule); } }); /* * Rule: box-sizing doesn't work in IE6 and IE7. */ CSSLint.addRule({ //rule information id: "box-sizing", name: "Disallow use of box-sizing", desc: "The box-sizing properties isn't supported in IE6 and IE7.", browsers: "IE6, IE7", tags: ["Compatibility"], //initialization init: function(parser, reporter){ var rule = this; parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); if (name == "box-sizing"){ reporter.report("The box-sizing property isn't supported in IE6 and IE7.", event.line, event.col, rule); } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "compatible-vendor-prefixes", name: "Require compatible vendor prefixes", desc: "Include all compatible vendor prefixes to reach a wider range of users.", browsers: "All", //initialization init: function (parser, reporter) { var rule = this, compatiblePrefixes, properties, prop, variations, prefixed, i, len, arrayPush = Array.prototype.push, applyTo = []; // See http://peter.sh/experiments/vendor-prefixed-css-property-overview/ for details compatiblePrefixes = { "animation" : "webkit moz ms", "animation-delay" : "webkit moz ms", "animation-direction" : "webkit moz ms", "animation-duration" : "webkit moz ms", "animation-fill-mode" : "webkit moz ms", "animation-iteration-count" : "webkit moz ms", "animation-name" : "webkit moz ms", "animation-play-state" : "webkit moz ms", "animation-timing-function" : "webkit moz ms", "appearance" : "webkit moz", "border-end" : "webkit moz", "border-end-color" : "webkit moz", "border-end-style" : "webkit moz", "border-end-width" : "webkit moz", "border-image" : "webkit moz o", "border-radius" : "webkit moz", "border-start" : "webkit moz", "border-start-color" : "webkit moz", "border-start-style" : "webkit moz", "border-start-width" : "webkit moz", "box-align" : "webkit moz ms", "box-direction" : "webkit moz ms", "box-flex" : "webkit moz ms", "box-lines" : "webkit ms", "box-ordinal-group" : "webkit moz ms", "box-orient" : "webkit moz ms", "box-pack" : "webkit moz ms", "box-sizing" : "webkit moz", "box-shadow" : "webkit moz", "column-count" : "webkit moz ms", "column-gap" : "webkit moz ms", "column-rule" : "webkit moz ms", "column-rule-color" : "webkit moz ms", "column-rule-style" : "webkit moz ms", "column-rule-width" : "webkit moz ms", "column-width" : "webkit moz ms", "hyphens" : "epub moz", "line-break" : "webkit ms", "margin-end" : "webkit moz", "margin-start" : "webkit moz", "marquee-speed" : "webkit wap", "marquee-style" : "webkit wap", "padding-end" : "webkit moz", "padding-start" : "webkit moz", "tab-size" : "moz o", "text-size-adjust" : "webkit ms", "transform" : "webkit moz ms o", "transform-origin" : "webkit moz ms o", "transition" : "webkit moz o ms", "transition-delay" : "webkit moz o ms", "transition-duration" : "webkit moz o ms", "transition-property" : "webkit moz o ms", "transition-timing-function" : "webkit moz o ms", "user-modify" : "webkit moz", "user-select" : "webkit moz ms", "word-break" : "epub ms", "writing-mode" : "epub ms" }; for (prop in compatiblePrefixes) { if (compatiblePrefixes.hasOwnProperty(prop)) { variations = []; prefixed = compatiblePrefixes[prop].split(' '); for (i = 0, len = prefixed.length; i < len; i++) { variations.push('-' + prefixed[i] + '-' + prop); } compatiblePrefixes[prop] = variations; arrayPush.apply(applyTo, variations); } } parser.addListener("startrule", function () { properties = []; }); parser.addListener("property", function (event) { var name = event.property; if (CSSLint.Util.indexOf(applyTo, name.text) > -1) { properties.push(name); } }); parser.addListener("endrule", function (event) { if (!properties.length) { return; } var propertyGroups = {}, i, len, name, prop, variations, value, full, actual, item, propertiesSpecified; for (i = 0, len = properties.length; i < len; i++) { name = properties[i]; for (prop in compatiblePrefixes) { if (compatiblePrefixes.hasOwnProperty(prop)) { variations = compatiblePrefixes[prop]; if (CSSLint.Util.indexOf(variations, name.text) > -1) { if (!propertyGroups[prop]) { propertyGroups[prop] = { full : variations.slice(0), actual : [], actualNodes: [] }; } if (CSSLint.Util.indexOf(propertyGroups[prop].actual, name.text) === -1) { propertyGroups[prop].actual.push(name.text); propertyGroups[prop].actualNodes.push(name); } } } } } for (prop in propertyGroups) { if (propertyGroups.hasOwnProperty(prop)) { value = propertyGroups[prop]; full = value.full; actual = value.actual; if (full.length > actual.length) { for (i = 0, len = full.length; i < len; i++) { item = full[i]; if (CSSLint.Util.indexOf(actual, item) === -1) { propertiesSpecified = (actual.length === 1) ? actual[0] : (actual.length == 2) ? actual.join(" and ") : actual.join(", "); reporter.report("The property " + item + " is compatible with " + propertiesSpecified + " and should be included as well.", value.actualNodes[0].line, value.actualNodes[0].col, rule); } } } } } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "display-property-grouping", name: "Require properties appropriate for display", desc: "Certain properties shouldn't be used with certain display property values.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; var propertiesToCheck = { display: 1, "float": "none", height: 1, width: 1, margin: 1, "margin-left": 1, "margin-right": 1, "margin-bottom": 1, "margin-top": 1, padding: 1, "padding-left": 1, "padding-right": 1, "padding-bottom": 1, "padding-top": 1, "vertical-align": 1 }, properties; function reportProperty(name, display, msg){ if (properties[name]){ if (typeof propertiesToCheck[name] != "string" || properties[name].value.toLowerCase() != propertiesToCheck[name]){ reporter.report(msg || name + " can't be used with display: " + display + ".", properties[name].line, properties[name].col, rule); } } } function startRule(){ properties = {}; } function endRule(){ var display = properties.display ? properties.display.value : null; if (display){ switch(display){ case "inline": //height, width, margin-top, margin-bottom, float should not be used with inline reportProperty("height", display); reportProperty("width", display); reportProperty("margin", display); reportProperty("margin-top", display); reportProperty("margin-bottom", display); reportProperty("float", display, "display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug)."); break; case "block": //vertical-align should not be used with block reportProperty("vertical-align", display); break; case "inline-block": //float should not be used with inline-block reportProperty("float", display); break; default: //margin, float should not be used with table if (display.indexOf("table-") === 0){ reportProperty("margin", display); reportProperty("margin-left", display); reportProperty("margin-right", display); reportProperty("margin-top", display); reportProperty("margin-bottom", display); reportProperty("float", display); } //otherwise do nothing } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startpage", startRule); parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); if (propertiesToCheck[name]){ properties[name] = { value: event.value.text, line: event.property.line, col: event.property.col }; } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); parser.addListener("endkeyframerule", endRule); parser.addListener("endpagemargin", endRule); parser.addListener("endpage", endRule); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "duplicate-background-images", name: "Disallow duplicate background images", desc: "Every background-image should be unique. Use a common class for e.g. sprites.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, stack = {}; parser.addListener("property", function(event){ var name = event.property.text, value = event.value, i, len; if (name.match(/background/i)) { for (i=0, len=value.parts.length; i < len; i++) { if (value.parts[i].type == 'uri') { if (typeof stack[value.parts[i].uri] === 'undefined') { stack[value.parts[i].uri] = event; } else { reporter.report("Background image '" + value.parts[i].uri + "' was used multiple times, first declared at line " + stack[value.parts[i].uri].line + ", col " + stack[value.parts[i].uri].col + ".", event.line, event.col, rule); } } } } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "duplicate-properties", name: "Disallow duplicate properties", desc: "Duplicate properties must appear one after the other.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, properties, lastProperty; function startRule(event){ properties = {}; } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var property = event.property, name = property.text.toLowerCase(); if (properties[name] && (lastProperty != name || properties[name] == event.value.text)){ reporter.report("Duplicate property '" + event.property + "' found.", event.line, event.col, rule); } properties[name] = event.value.text; lastProperty = name; }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "empty-rules", name: "Disallow empty rules", desc: "Rules without any properties specified should be removed.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; parser.addListener("startrule", function(){ count=0; }); parser.addListener("property", function(){ count++; }); parser.addListener("endrule", function(event){ var selectors = event.selectors; if (count === 0){ reporter.report("Rule is empty.", selectors[0].line, selectors[0].col, rule); } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "errors", name: "Parsing Errors", desc: "This rule looks for recoverable syntax errors.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("error", function(event){ reporter.error(event.message, event.line, event.col, rule); }); } }); CSSLint.addRule({ //rule information id: "fallback-colors", name: "Require fallback colors", desc: "For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.", browsers: "IE6,IE7,IE8", //initialization init: function(parser, reporter){ var rule = this, lastProperty, propertiesToCheck = { color: 1, background: 1, "background-color": 1 }, properties; function startRule(event){ properties = {}; lastProperty = null; } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var property = event.property, name = property.text.toLowerCase(), parts = event.value.parts, i = 0, colorType = "", len = parts.length; if(propertiesToCheck[name]){ while(i < len){ if (parts[i].type == "color"){ if ("alpha" in parts[i] || "hue" in parts[i]){ if (/([^\)]+)\(/.test(parts[i])){ colorType = RegExp.$1.toUpperCase(); } if (!lastProperty || (lastProperty.property.text.toLowerCase() != name || lastProperty.colorType != "compat")){ reporter.report("Fallback " + name + " (hex or RGB) should precede " + colorType + " " + name + ".", event.line, event.col, rule); } } else { event.colorType = "compat"; } } i++; } } lastProperty = event; }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "floats", name: "Disallow too many floats", desc: "This rule tests if the float property is used too many times", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; var count = 0; //count how many times "float" is used parser.addListener("property", function(event){ if (event.property.text.toLowerCase() == "float" && event.value.text.toLowerCase() != "none"){ count++; } }); //report the results parser.addListener("endstylesheet", function(){ reporter.stat("floats", count); if (count >= 10){ reporter.rollupWarn("Too many floats (" + count + "), you're probably using them for layout. Consider using a grid system instead.", rule); } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "font-faces", name: "Don't use too many web fonts", desc: "Too many different web fonts in the same stylesheet.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; parser.addListener("startfontface", function(){ count++; }); parser.addListener("endstylesheet", function(){ if (count > 5){ reporter.rollupWarn("Too many @font-face declarations (" + count + ").", rule); } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "font-sizes", name: "Disallow too many font sizes", desc: "Checks the number of font-size declarations.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; //check for use of "font-size" parser.addListener("property", function(event){ if (event.property == "font-size"){ count++; } }); //report the results parser.addListener("endstylesheet", function(){ reporter.stat("font-sizes", count); if (count >= 10){ reporter.rollupWarn("Too many font-size declarations (" + count + "), abstraction needed.", rule); } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "gradients", name: "Require all gradient definitions", desc: "When using a vendor-prefixed gradient, make sure to use them all.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, gradients; parser.addListener("startrule", function(){ gradients = { moz: 0, webkit: 0, oldWebkit: 0, ms: 0, o: 0 }; }); parser.addListener("property", function(event){ if (/\-(moz|ms|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(event.value)){ gradients[RegExp.$1] = 1; } else if (/\-webkit\-gradient/i.test(event.value)){ gradients.oldWebkit = 1; } }); parser.addListener("endrule", function(event){ var missing = []; if (!gradients.moz){ missing.push("Firefox 3.6+"); } if (!gradients.webkit){ missing.push("Webkit (Safari 5+, Chrome)"); } if (!gradients.oldWebkit){ missing.push("Old Webkit (Safari 4+, Chrome)"); } if (!gradients.ms){ missing.push("Internet Explorer 10+"); } if (!gradients.o){ missing.push("Opera 11.1+"); } if (missing.length && missing.length < 5){ reporter.report("Missing vendor-prefixed CSS gradients for " + missing.join(", ") + ".", event.selectors[0].line, event.selectors[0].col, rule); } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "ids", name: "Disallow IDs in selectors", desc: "Selectors should not contain IDs.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, idCount, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; idCount = 0; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (modifier.type == "id"){ idCount++; } } } } if (idCount == 1){ reporter.report("Don't use IDs in selectors.", selector.line, selector.col, rule); } else if (idCount > 1){ reporter.report(idCount + " IDs in the selector, really?", selector.line, selector.col, rule); } } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "import", name: "Disallow @import", desc: "Don't use @import, use <link> instead.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("import", function(event){ reporter.report("@import prevents parallel downloads, use <link> instead.", event.line, event.col, rule); }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "important", name: "Disallow !important", desc: "Be careful when using !important declaration", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; //warn that important is used and increment the declaration counter parser.addListener("property", function(event){ if (event.important === true){ count++; reporter.report("Use of !important", event.line, event.col, rule); } }); //if there are more than 10, show an error parser.addListener("endstylesheet", function(){ reporter.stat("important", count); if (count >= 10){ reporter.rollupWarn("Too many !important declarations (" + count + "), try to use less than 10 to avoid specifity issues.", rule); } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "known-properties", name: "Require use of known properties", desc: "Properties should be known (listed in CSS specification) or be a vendor-prefixed property.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, properties = { "alignment-adjust": 1, "alignment-baseline": 1, "animation": 1, "animation-delay": 1, "animation-direction": 1, "animation-duration": 1, "animation-fill-mode": 1, "animation-iteration-count": 1, "animation-name": 1, "animation-play-state": 1, "animation-timing-function": 1, "appearance": 1, "azimuth": 1, "backface-visibility": 1, "background": 1, "background-attachment": 1, "background-break": 1, "background-clip": 1, "background-color": 1, "background-image": 1, "background-origin": 1, "background-position": 1, "background-repeat": 1, "background-size": 1, "baseline-shift": 1, "binding": 1, "bleed": 1, "bookmark-label": 1, "bookmark-level": 1, "bookmark-state": 1, "bookmark-target": 1, "border": 1, "border-bottom": 1, "border-bottom-color": 1, "border-bottom-left-radius": 1, "border-bottom-right-radius": 1, "border-bottom-style": 1, "border-bottom-width": 1, "border-collapse": 1, "border-color": 1, "border-image": 1, "border-image-outset": 1, "border-image-repeat": 1, "border-image-slice": 1, "border-image-source": 1, "border-image-width": 1, "border-left": 1, "border-left-color": 1, "border-left-style": 1, "border-left-width": 1, "border-radius": 1, "border-right": 1, "border-right-color": 1, "border-right-style": 1, "border-right-width": 1, "border-spacing": 1, "border-style": 1, "border-top": 1, "border-top-color": 1, "border-top-left-radius": 1, "border-top-right-radius": 1, "border-top-style": 1, "border-top-width": 1, "border-width": 1, "bottom": 1, "box-align": 1, "box-decoration-break": 1, "box-direction": 1, "box-flex": 1, "box-flex-group": 1, "box-lines": 1, "box-ordinal-group": 1, "box-orient": 1, "box-pack": 1, "box-shadow": 1, "box-sizing": 1, "break-after": 1, "break-before": 1, "break-inside": 1, "caption-side": 1, "clear": 1, "clip": 1, "color": 1, "color-profile": 1, "column-count": 1, "column-fill": 1, "column-gap": 1, "column-rule": 1, "column-rule-color": 1, "column-rule-style": 1, "column-rule-width": 1, "column-span": 1, "column-width": 1, "columns": 1, "content": 1, "counter-increment": 1, "counter-reset": 1, "crop": 1, "cue": 1, "cue-after": 1, "cue-before": 1, "cursor": 1, "direction": 1, "display": 1, "dominant-baseline": 1, "drop-initial-after-adjust": 1, "drop-initial-after-align": 1, "drop-initial-before-adjust": 1, "drop-initial-before-align": 1, "drop-initial-size": 1, "drop-initial-value": 1, "elevation": 1, "empty-cells": 1, "fit": 1, "fit-position": 1, "float": 1, "float-offset": 1, "font": 1, "font-family": 1, "font-size": 1, "font-size-adjust": 1, "font-stretch": 1, "font-style": 1, "font-variant": 1, "font-weight": 1, "grid-columns": 1, "grid-rows": 1, "hanging-punctuation": 1, "height": 1, "hyphenate-after": 1, "hyphenate-before": 1, "hyphenate-character": 1, "hyphenate-lines": 1, "hyphenate-resource": 1, "hyphens": 1, "icon": 1, "image-orientation": 1, "image-rendering": 1, "image-resolution": 1, "inline-box-align": 1, "left": 1, "letter-spacing": 1, "line-height": 1, "line-stacking": 1, "line-stacking-ruby": 1, "line-stacking-shift": 1, "line-stacking-strategy": 1, "list-style": 1, "list-style-image": 1, "list-style-position": 1, "list-style-type": 1, "margin": 1, "margin-bottom": 1, "margin-left": 1, "margin-right": 1, "margin-top": 1, "mark": 1, "mark-after": 1, "mark-before": 1, "marks": 1, "marquee-direction": 1, "marquee-play-count": 1, "marquee-speed": 1, "marquee-style": 1, "max-height": 1, "max-width": 1, "min-height": 1, "min-width": 1, "move-to": 1, "nav-down": 1, "nav-index": 1, "nav-left": 1, "nav-right": 1, "nav-up": 1, "opacity": 1, "orphans": 1, "outline": 1, "outline-color": 1, "outline-offset": 1, "outline-style": 1, "outline-width": 1, "overflow": 1, "overflow-style": 1, "overflow-x": 1, "overflow-y": 1, "padding": 1, "padding-bottom": 1, "padding-left": 1, "padding-right": 1, "padding-top": 1, "page": 1, "page-break-after": 1, "page-break-before": 1, "page-break-inside": 1, "page-policy": 1, "pause": 1, "pause-after": 1, "pause-before": 1, "perspective": 1, "perspective-origin": 1, "phonemes": 1, "pitch": 1, "pitch-range": 1, "play-during": 1, "position": 1, "presentation-level": 1, "punctuation-trim": 1, "quotes": 1, "rendering-intent": 1, "resize": 1, "rest": 1, "rest-after": 1, "rest-before": 1, "richness": 1, "right": 1, "rotation": 1, "rotation-point": 1, "ruby-align": 1, "ruby-overhang": 1, "ruby-position": 1, "ruby-span": 1, "size": 1, "speak": 1, "speak-header": 1, "speak-numeral": 1, "speak-punctuation": 1, "speech-rate": 1, "stress": 1, "string-set": 1, "table-layout": 1, "target": 1, "target-name": 1, "target-new": 1, "target-position": 1, "text-align": 1, "text-align-last": 1, "text-decoration": 1, "text-emphasis": 1, "text-height": 1, "text-indent": 1, "text-justify": 1, "text-outline": 1, "text-shadow": 1, "text-transform": 1, "text-wrap": 1, "top": 1, "transform": 1, "transform-origin": 1, "transform-style": 1, "transition": 1, "transition-delay": 1, "transition-duration": 1, "transition-property": 1, "transition-timing-function": 1, "unicode-bidi": 1, "user-modify": 1, "user-select": 1, "vertical-align": 1, "visibility": 1, "voice-balance": 1, "voice-duration": 1, "voice-family": 1, "voice-pitch": 1, "voice-pitch-range": 1, "voice-rate": 1, "voice-stress": 1, "voice-volume": 1, "volume": 1, "white-space": 1, "white-space-collapse": 1, "widows": 1, "width": 1, "word-break": 1, "word-spacing": 1, "word-wrap": 1, "z-index": 1, //IE "filter": 1, "zoom": 1, //@font-face "src": 1 }; parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); if (event.invalid) { reporter.report(event.invalid.message, event.line, event.col, rule); } //if (!properties[name] && name.charAt(0) != "-"){ // reporter.error("Unknown property '" + event.property + "'.", event.line, event.col, rule); //} }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "outline-none", name: "Disallow outline: none", desc: "Use of outline: none or outline: 0 should be limited to :focus rules.", browsers: "All", tags: ["Accessibility"], //initialization init: function(parser, reporter){ var rule = this, lastRule; function startRule(event){ if (event.selectors){ lastRule = { line: event.line, col: event.col, selectors: event.selectors, propCount: 0, outline: false }; } else { lastRule = null; } } function endRule(event){ if (lastRule){ if (lastRule.outline){ if (lastRule.selectors.toString().toLowerCase().indexOf(":focus") == -1){ reporter.report("Outlines should only be modified using :focus.", lastRule.line, lastRule.col, rule); } else if (lastRule.propCount == 1) { reporter.report("Outlines shouldn't be hidden unless other visual changes are made.", lastRule.line, lastRule.col, rule); } } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(), value = event.value; if (lastRule){ lastRule.propCount++; if (name == "outline" && (value == "none" || value == "0")){ lastRule.outline = true; } } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); parser.addListener("endpage", endRule); parser.addListener("endpagemargin", endRule); parser.addListener("endkeyframerule", endRule); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "overqualified-elements", name: "Disallow overqualified elements", desc: "Don't use classes or IDs with elements (a.foo or a#foo).", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, classes = {}; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (part.elementName && modifier.type == "id"){ reporter.report("Element (" + part + ") is overqualified, just use " + modifier + " without element name.", part.line, part.col, rule); } else if (modifier.type == "class"){ if (!classes[modifier]){ classes[modifier] = []; } classes[modifier].push({ modifier: modifier, part: part }); } } } } } }); parser.addListener("endstylesheet", function(){ var prop; for (prop in classes){ if (classes.hasOwnProperty(prop)){ //one use means that this is overqualified if (classes[prop].length == 1 && classes[prop][0].part.elementName){ reporter.report("Element (" + classes[prop][0].part + ") is overqualified, just use " + classes[prop][0].modifier + " without element name.", classes[prop][0].part.line, classes[prop][0].part.col, rule); } } } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "qualified-headings", name: "Disallow qualified headings", desc: "Headings should not be qualified (namespaced).", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, i, j; for (i=0; i < selectors.length; i++){ selector = selectors[i]; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ if (part.elementName && /h[1-6]/.test(part.elementName.toString()) && j > 0){ reporter.report("Heading (" + part.elementName + ") should not be qualified.", part.line, part.col, rule); } } } } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "regex-selectors", name: "Disallow selectors that look like regexs", desc: "Selectors that look like regular expressions are slow and should be avoided.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (modifier.type == "attribute"){ if (/([\~\|\^\$\*]=)/.test(modifier)){ reporter.report("Attribute selectors with " + RegExp.$1 + " are slow!", modifier.line, modifier.col, rule); } } } } } } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "rules-count", name: "Rules Count", desc: "Track how many rules there are.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; //count each rule parser.addListener("startrule", function(){ count++; }); parser.addListener("endstylesheet", function(){ reporter.stat("rule-count", count); }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "shorthand", name: "Require shorthand properties", desc: "Use shorthand properties where possible.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, prop, i, len, propertiesToCheck = {}, properties, mapping = { "margin": [ "margin-top", "margin-bottom", "margin-left", "margin-right" ], "padding": [ "padding-top", "padding-bottom", "padding-left", "padding-right" ] }; //initialize propertiesToCheck for (prop in mapping){ if (mapping.hasOwnProperty(prop)){ for (i=0, len=mapping[prop].length; i < len; i++){ propertiesToCheck[mapping[prop][i]] = prop; } } } function startRule(event){ properties = {}; } //event handler for end of rules function endRule(event){ var prop, i, len, total; //check which properties this rule has for (prop in mapping){ if (mapping.hasOwnProperty(prop)){ total=0; for (i=0, len=mapping[prop].length; i < len; i++){ total += properties[mapping[prop][i]] ? 1 : 0; } if (total == mapping[prop].length){ reporter.report("The properties " + mapping[prop].join(", ") + " can be replaced by " + prop + ".", event.line, event.col, rule); } } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); //check for use of "font-size" parser.addListener("property", function(event){ var name = event.property.toString().toLowerCase(), value = event.value.parts[0].value; if (propertiesToCheck[name]){ properties[name] = 1; } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "text-indent", name: "Disallow negative text-indent", desc: "Checks for text indent less than -99px", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, textIndent = false; function startRule(event){ textIndent = false; } //event handler for end of rules function endRule(event){ if (textIndent){ reporter.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.", textIndent.line, textIndent.col, rule); } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); //check for use of "font-size" parser.addListener("property", function(event){ var name = event.property.toString().toLowerCase(), value = event.value; if (name == "text-indent" && value.parts[0].value < -99){ textIndent = event.property; } else if (name == "direction" && value == "ltr"){ textIndent = false; } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "unique-headings", name: "Headings should only be defined once", desc: "Headings should be defined only once.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; var headings = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 }; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, pseudo, i, j; for (i=0; i < selectors.length; i++){ selector = selectors[i]; part = selector.parts[selector.parts.length-1]; if (part.elementName && /(h[1-6])/i.test(part.elementName.toString())){ for (j=0; j < part.modifiers.length; j++){ if (part.modifiers[j].type == "pseudo"){ pseudo = true; break; } } if (!pseudo){ headings[RegExp.$1]++; if (headings[RegExp.$1] > 1) { reporter.report("Heading (" + part.elementName + ") has already been defined.", part.line, part.col, rule); } } } } }); parser.addListener("endstylesheet", function(event){ var prop, messages = []; for (prop in headings){ if (headings.hasOwnProperty(prop)){ if (headings[prop] > 1){ messages.push(headings[prop] + " " + prop + "s"); } } } if (messages.length){ reporter.rollupWarn("You have " + messages.join(", ") + " defined in this stylesheet.", rule); } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "universal-selector", name: "Disallow universal selector", desc: "The universal selector (*) is known to be slow.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; part = selector.parts[selector.parts.length-1]; if (part.elementName == "*"){ reporter.report(rule.desc, part.line, part.col, rule); } } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "unqualified-attributes", name: "Disallow unqualified attribute selectors", desc: "Unqualified attribute selectors are known to be slow.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; part = selector.parts[selector.parts.length-1]; if (part.type == parser.SELECTOR_PART_TYPE){ for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (modifier.type == "attribute" && (!part.elementName || part.elementName == "*")){ reporter.report(rule.desc, part.line, part.col, rule); } } } } }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "vendor-prefix", name: "Require standard property with vendor prefix", desc: "When using a vendor-prefixed property, make sure to include the standard one.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, properties, num, propertiesToCheck = { "-webkit-border-radius": "border-radius", "-webkit-border-top-left-radius": "border-top-left-radius", "-webkit-border-top-right-radius": "border-top-right-radius", "-webkit-border-bottom-left-radius": "border-bottom-left-radius", "-webkit-border-bottom-right-radius": "border-bottom-right-radius", "-o-border-radius": "border-radius", "-o-border-top-left-radius": "border-top-left-radius", "-o-border-top-right-radius": "border-top-right-radius", "-o-border-bottom-left-radius": "border-bottom-left-radius", "-o-border-bottom-right-radius": "border-bottom-right-radius", "-moz-border-radius": "border-radius", "-moz-border-radius-topleft": "border-top-left-radius", "-moz-border-radius-topright": "border-top-right-radius", "-moz-border-radius-bottomleft": "border-bottom-left-radius", "-moz-border-radius-bottomright": "border-bottom-right-radius", "-moz-column-count": "column-count", "-webkit-column-count": "column-count", "-moz-column-gap": "column-gap", "-webkit-column-gap": "column-gap", "-moz-column-rule": "column-rule", "-webkit-column-rule": "column-rule", "-moz-column-rule-style": "column-rule-style", "-webkit-column-rule-style": "column-rule-style", "-moz-column-rule-color": "column-rule-color", "-webkit-column-rule-color": "column-rule-color", "-moz-column-rule-width": "column-rule-width", "-webkit-column-rule-width": "column-rule-width", "-moz-column-width": "column-width", "-webkit-column-width": "column-width", "-webkit-column-span": "column-span", "-webkit-columns": "columns", "-moz-box-shadow": "box-shadow", "-webkit-box-shadow": "box-shadow", "-moz-transform" : "transform", "-webkit-transform" : "transform", "-o-transform" : "transform", "-ms-transform" : "transform", "-moz-transform-origin" : "transform-origin", "-webkit-transform-origin" : "transform-origin", "-o-transform-origin" : "transform-origin", "-ms-transform-origin" : "transform-origin", "-moz-box-sizing" : "box-sizing", "-webkit-box-sizing" : "box-sizing", "-moz-user-select" : "user-select", "-khtml-user-select" : "user-select", "-webkit-user-select" : "user-select" }; //event handler for beginning of rules function startRule(){ properties = {}; num=1; } //event handler for end of rules function endRule(event){ var prop, i, len, standard, needed, actual, needsStandard = []; for (prop in properties){ if (propertiesToCheck[prop]){ needsStandard.push({ actual: prop, needed: propertiesToCheck[prop]}); } } for (i=0, len=needsStandard.length; i < len; i++){ needed = needsStandard[i].needed; actual = needsStandard[i].actual; if (!properties[needed]){ reporter.report("Missing standard property '" + needed + "' to go along with '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule); } else { //make sure standard property is last if (properties[needed][0].pos < properties[actual][0].pos){ reporter.report("Standard property '" + needed + "' should come after vendor-prefixed property '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule); } } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); if (!properties[name]){ properties[name] = []; } properties[name].push({ name: event.property, value : event.value, pos:num++ }); }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); parser.addListener("endpage", endRule); parser.addListener("endpagemargin", endRule); parser.addListener("endkeyframerule", endRule); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "zero-units", name: "Disallow units for 0 values", desc: "You don't need to specify units when a value is 0.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; //count how many times "float" is used parser.addListener("property", function(event){ var parts = event.value.parts, i = 0, len = parts.length; while(i < len){ if ((parts[i].units || parts[i].type == "percentage") && parts[i].value === 0 && parts[i].type != "time"){ reporter.report("Values of 0 shouldn't have units specified.", parts[i].line, parts[i].col, rule); } i++; } }); } }); CSSLint.addFormatter({ //format information id: "checkstyle-xml", name: "Checkstyle XML format", /** * Return opening root XML tag. * @return {String} to prepend before all results */ startFormat: function(){ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><checkstyle>"; }, /** * Return closing root XML tag. * @return {String} to append after all results */ endFormat: function(){ return "</checkstyle>"; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (UNUSED for now) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = []; var generateSource = function(rule) { if (!rule || !('name' in rule)) { return ""; } return 'net.csslint.' + rule.name.replace(/\s/g,''); }; var escapeSpecialCharacters = function(str) { if (!str || str.constructor !== String) { return ""; } return str.replace(/\"/g, "'").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }; if (messages.length > 0) { output.push("<file name=\""+filename+"\">"); CSSLint.Util.forEach(messages, function (message, i) { //ignore rollups for now if (!message.rollup) { output.push("<error line=\"" + message.line + "\" column=\"" + message.col + "\" severity=\"" + message.type + "\"" + " message=\"" + escapeSpecialCharacters(message.message) + "\" source=\"" + generateSource(message.rule) +"\"/>"); } }); output.push("</file>"); } return output.join(""); } }); CSSLint.addFormatter({ //format information id: "compact", name: "Compact, 'porcelain' format", /** * Return content to be printed before all file results. * @return {String} to prepend before all results */ startFormat: function() { return ""; }, /** * Return content to be printed after all file results. * @return {String} to append after all results */ endFormat: function() { return ""; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (Optional) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = ""; options = options || {}; var capitalize = function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }; if (messages.length === 0) { return options.quiet ? "" : filename + ": Lint Free!"; } CSSLint.Util.forEach(messages, function(message, i) { if (message.rollup) { output += filename + ": " + capitalize(message.type) + " - " + message.message + "\n"; } else { output += filename + ": " + "line " + message.line + ", col " + message.col + ", " + capitalize(message.type) + " - " + message.message + "\n"; } }); return output; } }); CSSLint.addFormatter({ //format information id: "csslint-xml", name: "CSSLint XML format", /** * Return opening root XML tag. * @return {String} to prepend before all results */ startFormat: function(){ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><csslint>"; }, /** * Return closing root XML tag. * @return {String} to append after all results */ endFormat: function(){ return "</csslint>"; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (UNUSED for now) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = []; var escapeSpecialCharacters = function(str) { if (!str || str.constructor !== String) { return ""; } return str.replace(/\"/g, "'").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }; if (messages.length > 0) { output.push("<file name=\""+filename+"\">"); CSSLint.Util.forEach(messages, function (message, i) { if (message.rollup) { output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>"); } else { output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" + " reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>"); } }); output.push("</file>"); } return output.join(""); } }); CSSLint.addFormatter({ //format information id: "lint-xml", name: "Lint XML format", /** * Return opening root XML tag. * @return {String} to prepend before all results */ startFormat: function(){ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><lint>"; }, /** * Return closing root XML tag. * @return {String} to append after all results */ endFormat: function(){ return "</lint>"; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (UNUSED for now) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = []; var escapeSpecialCharacters = function(str) { if (!str || str.constructor !== String) { return ""; } return str.replace(/\"/g, "'").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }; if (messages.length > 0) { output.push("<file name=\""+filename+"\">"); CSSLint.Util.forEach(messages, function (message, i) { if (message.rollup) { output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>"); } else { output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" + " reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>"); } }); output.push("</file>"); } return output.join(""); } }); CSSLint.addFormatter({ //format information id: "text", name: "Plain Text", /** * Return content to be printed before all file results. * @return {String} to prepend before all results */ startFormat: function() { return ""; }, /** * Return content to be printed after all file results. * @return {String} to append after all results */ endFormat: function() { return ""; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (Optional) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = ""; options = options || {}; if (messages.length === 0) { return options.quiet ? "" : "\n\ncsslint: No errors in " + filename + "."; } output = "\n\ncsslint: There are " + messages.length + " problems in " + filename + "."; var pos = filename.lastIndexOf("/"), shortFilename = filename; if (pos === -1){ pos = filename.lastIndexOf("\\"); } if (pos > -1){ shortFilename = filename.substring(pos+1); } CSSLint.Util.forEach(messages, function (message, i) { output = output + "\n\n" + shortFilename; if (message.rollup) { output += "\n" + (i+1) + ": " + message.type; output += "\n" + message.message; } else { output += "\n" + (i+1) + ": " + message.type + " at line " + message.line + ", col " + message.col; output += "\n" + message.message; output += "\n" + message.evidence; } }); return output; } }); exports.CSSLint = CSSLint; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/worker-css.js
JavaScript
asf20
376,824
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * John Roepke <john AT justjohn DOT us> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/less', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/less_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var LessHighlightRules = require("./less_highlight_rules").LessHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new LessHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/less_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LessHighlightRules = function() { var properties = lang.arrayToMap( (function () { var browserPrefix = ("-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-").split("|"); var prefixProperties = ("appearance|background-clip|background-inline-policy|background-origin|" + "background-size|binding|border-bottom-colors|border-left-colors|" + "border-right-colors|border-top-colors|border-end|border-end-color|" + "border-end-style|border-end-width|border-image|border-start|" + "border-start-color|border-start-style|border-start-width|box-align|" + "box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|" + "box-pack|box-sizing|column-count|column-gap|column-width|column-rule|" + "column-rule-width|column-rule-style|column-rule-color|float-edge|" + "font-feature-settings|font-language-override|force-broken-image-icon|" + "image-region|margin-end|margin-start|opacity|outline|outline-color|" + "outline-offset|outline-radius|outline-radius-bottomleft|" + "outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|" + "outline-style|outline-width|padding-end|padding-start|stack-sizing|" + "tab-size|text-blink|text-decoration-color|text-decoration-line|" + "text-decoration-style|transform|transform-origin|transition|" + "transition-delay|transition-duration|transition-property|" + "transition-timing-function|user-focus|user-input|user-modify|user-select|" + "window-shadow|border-radius").split("|"); var properties = ("azimuth|background-attachment|background-color|background-image|" + "background-position|background-repeat|background|border-bottom-color|" + "border-bottom-style|border-bottom-width|border-bottom|border-collapse|" + "border-color|border-left-color|border-left-style|border-left-width|" + "border-left|border-right-color|border-right-style|border-right-width|" + "border-right|border-spacing|border-style|border-top-color|" + "border-top-style|border-top-width|border-top|border-width|border|" + "bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" + "counter-reset|cue-after|cue-before|cue|cursor|direction|display|" + "elevation|empty-cells|float|font-family|font-size-adjust|font-size|" + "font-stretch|font-style|font-variant|font-weight|font|height|left|" + "letter-spacing|line-height|list-style-image|list-style-position|" + "list-style-type|list-style|margin-bottom|margin-left|margin-right|" + "margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" + "min-width|opacity|orphans|outline-color|" + "outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" + "padding-left|padding-right|padding-top|padding|page-break-after|" + "page-break-before|page-break-inside|page|pause-after|pause-before|" + "pause|pitch-range|pitch|play-during|position|quotes|richness|right|" + "size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" + "stress|table-layout|text-align|text-decoration|text-indent|" + "text-shadow|text-transform|top|unicode-bidi|vertical-align|" + "visibility|voice-family|volume|white-space|widows|width|word-spacing|" + "z-index").split("|"); //The return array var ret = []; //All prefixProperties will get the browserPrefix in //the begning by join the prefixProperties array with the value of browserPrefix for (var i=0, ln=browserPrefix.length; i<ln; i++) { Array.prototype.push.apply( ret, (( browserPrefix[i] + prefixProperties.join("|" + browserPrefix[i]) ).split("|")) ); } //Add also prefixProperties and properties without any browser prefix Array.prototype.push.apply(ret, prefixProperties); Array.prototype.push.apply(ret, properties); return ret; })() ); var functions = lang.arrayToMap( ("hsl|hsla|rgb|rgba|url|attr|counter|counters|lighten|darken|saturate|" + "desaturate|fadein|fadeout|fade|spin|mix|hue|saturation|lightness|" + "alpha|round|ceil|floor|percentage|color|iscolor|isnumber|isstring|" + "iskeyword|isurl|ispixel|ispercentage|isem").split("|") ); var constants = lang.arrayToMap( ("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" + "block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" + "char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" + "decimal-leading-zero|decimal|default|disabled|disc|" + "distribute-all-lines|distribute-letter|distribute-space|" + "distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" + "hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|" + "ideograph-alpha|ideograph-numeric|ideograph-parenthesis|" + "ideograph-space|inactive|inherit|inline-block|inline|inset|inside|" + "inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|" + "keep-all|left|lighter|line-edge|line-through|line|list-item|loose|" + "lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|" + "medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|" + "nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|" + "overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|" + "ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|" + "solid|square|static|strict|super|sw-resize|table-footer-group|" + "table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|" + "transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|" + "vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|" + "zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var keywords = lang.arrayToMap( ("@mixin|@extend|@include|@import|@media|@debug|@warn|@if|@for|@each|" + "@while|@else|@font-face|@-webkit-keyframes|if|and|!default|module|" + "def|end|declare|when|not|and").split("|") ); var tags = lang.arrayToMap( ("a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdo|" + "big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" + "command|datalist|dd|del|details|dfn|dir|div|dl|dt|em|embed|fieldset|" + "figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|" + "header|hgroup|hr|html|i|iframe|img|input|ins|keygen|kbd|label|legend|li|" + "link|map|mark|menu|meta|meter|nav|noframes|noscript|object|ol|optgroup|" + "option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|" + "small|source|span|strike|strong|style|sub|summary|sup|table|tbody|td|" + "textarea|tfoot|th|thead|time|title|tr|tt|u|ul|var|video|wbr|xmp").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : "constant.numeric", regex : numRe }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else return "variable"; }, regex : "@[a-z0-9_\\-@]*\\b" }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) return "support.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (constants.hasOwnProperty(value)) return "constant.language"; else if (functions.hasOwnProperty(value)) return "support.function"; else if (colors.hasOwnProperty(value.toLowerCase())) return "support.constant.color"; else if (tags.hasOwnProperty(value.toLowerCase())) return "variable.language"; else return "text"; }, regex : "\\-?[@a-z_][@a-z0-9_\\-]*" }, { token: "variable.language", regex: "#[a-z0-9-_]+" }, { token: "variable.language", regex: "\\.[a-z0-9-_]+" }, { token: "variable.language", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { token : "keyword.operator", regex : "<|>|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; }; oop.inherits(LessHighlightRules, TextHighlightRules); exports.LessHighlightRules = LessHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-less.js
JavaScript
asf20
20,181
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("csslint", function(e) { var errors = []; e.data.forEach(function(message) { errors.push({ row: message.line - 1, column: message.col - 1, text: message.message, type: message.type, lint: message }); }); session.setAnnotations(errors); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-css.js
JavaScript
asf20
21,512
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/tomorrow', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-tomorrow"; exports.cssText = "\ .ace-tomorrow .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tomorrow .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tomorrow .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-tomorrow .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tomorrow .ace_scroller {\ background-color: #FFFFFF;\ }\ \ .ace-tomorrow .ace_text-layer {\ cursor: text;\ color: #4D4D4C;\ }\ \ .ace-tomorrow .ace_cursor {\ border-left: 2px solid #AEAFAD;\ }\ \ .ace-tomorrow .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #AEAFAD;\ }\ \ .ace-tomorrow .ace_marker-layer .ace_selection {\ background: #D6D6D6;\ }\ \ .ace-tomorrow.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #FFFFFF;\ border-radius: 2px;\ }\ \ .ace-tomorrow .ace_marker-layer .ace_step {\ background: rgb(255, 255, 0);\ }\ \ .ace-tomorrow .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #D1D1D1;\ }\ \ .ace-tomorrow .ace_marker-layer .ace_active_line {\ background: #EFEFEF;\ }\ \ .ace-tomorrow .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-tomorrow .ace_marker-layer .ace_selected_word {\ border: 1px solid #D6D6D6;\ }\ \ .ace-tomorrow .ace_invisible {\ color: #D1D1D1;\ }\ \ .ace-tomorrow .ace_keyword, .ace-tomorrow .ace_meta {\ color:#8959A8;\ }\ \ .ace-tomorrow .ace_keyword.ace_operator {\ color:#3E999F;\ }\ \ .ace-tomorrow .ace_constant.ace_language {\ color:#F5871F;\ }\ \ .ace-tomorrow .ace_constant.ace_numeric {\ color:#F5871F;\ }\ \ .ace-tomorrow .ace_constant.ace_other {\ color:#666969;\ }\ \ .ace-tomorrow .ace_invalid {\ color:#FFFFFF;\ background-color:#C82829;\ }\ \ .ace-tomorrow .ace_invalid.ace_deprecated {\ color:#FFFFFF;\ background-color:#8959A8;\ }\ \ .ace-tomorrow .ace_support.ace_constant {\ color:#F5871F;\ }\ \ .ace-tomorrow .ace_fold {\ background-color: #4271AE;\ border-color: #4D4D4C;\ }\ \ .ace-tomorrow .ace_support.ace_function {\ color:#4271AE;\ }\ \ .ace-tomorrow .ace_storage {\ color:#8959A8;\ }\ \ .ace-tomorrow .ace_storage.ace_type, .ace-tomorrow .ace_support.ace_type{\ color:#8959A8;\ }\ \ .ace-tomorrow .ace_variable {\ color:#4271AE;\ }\ \ .ace-tomorrow .ace_variable.ace_parameter {\ color:#F5871F;\ }\ \ .ace-tomorrow .ace_string {\ color:#718C00;\ }\ \ .ace-tomorrow .ace_string.ace_regexp {\ color:#C82829;\ }\ \ .ace-tomorrow .ace_comment {\ color:#8E908C;\ }\ \ .ace-tomorrow .ace_variable {\ color:#C82829;\ }\ \ .ace-tomorrow .ace_meta.ace_tag {\ color:#C82829;\ }\ \ .ace-tomorrow .ace_entity.ace_other.ace_attribute-name {\ color:#C82829;\ }\ \ .ace-tomorrow .ace_entity.ace_name.ace_function {\ color:#4271AE;\ }\ \ .ace-tomorrow .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-tomorrow .ace_markup.ace_heading {\ color:#718C00;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-tomorrow.js
JavaScript
asf20
4,929
"no use strict"; var console = { log: function(msg) { postMessage({type: "log", data: msg}); } }; var window = { console: console }; 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("/"); var moduleName = base + "/" + moduleName; while(moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; var moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; var require = function(parentId, id) { var id = normalizeModule(parentId, id); var module = require.modules[id]; if (module) { if (!module.initialized) { module.exports = module.factory().exports; module.initialized = true; } return module.exports; } var chunks = id.split("/"); chunks[0] = require.tlns[chunks[0]] || chunks[0]; var path = chunks.join("/") + ".js"; require.id = id; importScripts(path); return require(parentId, id); }; require.modules = {}; require.tlns = {}; var define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; } else if (arguments.length == 1) { factory = id; id = require.id; } if (id.indexOf("text!") === 0) return; var req = function(deps, factory) { return require(id, deps, factory); }; require.modules[id] = { factory: function() { var module = { exports: {} }; var returnExports = factory(req, module.exports, module); if (returnExports) module.exports = returnExports; return module; } }; }; function initBaseUrls(topLevelNamespaces) { require.tlns = topLevelNamespaces; } function initSender() { var EventEmitter = require(null, "ace/lib/event_emitter").EventEmitter; var oop = require(null, "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; var sender; onmessage = function(e) { var msg = e.data; if (msg.command) { main[msg.command].apply(main, msg.args); } else if (msg.init) { initBaseUrls(msg.tlns); require(null, "ace/lib/fixoldbrowsers"); sender = initSender(); var clazz = require(null, msg.module)[msg.classname]; main = new clazz(sender); } else if (msg.event && sender) { sender._emit(msg.event, msg.data); } }; // vim:set ts=4 sts=4 sw=4 st: // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Irakli Gozalishvili Copyright (C) 2010 MIT License /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) { require("./regexp"); require("./es5-shim"); }); define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) { //--------------------------------- // Private variables //--------------------------------- 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; //--------------------------------- // Overriden native methods //--------------------------------- // Adds named capture support (with backreferences returned as `result.name`), and fixes two // cross-browser issues per ES3: // - Captured values for nonparticipating capturing groups should be returned as `undefined`, // rather than the empty string. // - `lastIndex` should not be incremented after zero-length matches. RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed // matching due to characters outside the match 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; } }); } // Attach named capture properties 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]; } } // Fix browsers that increment `lastIndex` after zero-length matches if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; } return match; }; // Don't override `test` if it won't change anything if (!compliantLastIndexIncrement) { // Fix browser bug in native method RegExp.prototype.test = function (str) { // Use the native `exec` to skip some processing overhead, even though the overriden // `exec` would take care of the `lastIndex` fix var match = real.exec.call(this, str); // Fix browsers that increment `lastIndex` after zero-length matches if (match && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; return !!match; }; } //--------------------------------- // Private helper functions //--------------------------------- 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; }; }); // vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License // -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License // -- kossnocorp Sasha Koss XXX TODO License or CLA // -- bryanforbes Bryan Forbes XXX TODO License or CLA // -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence // -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License // -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License // -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain) // -- iwyg XXX TODO License or CLA // -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License // -- xavierm02 Montillet Xavier XXX TODO License or CLA // -- Raynos Raynos XXX TODO License or CLA // -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License // -- rwldrn Rick Waldron Copyright (C) 2011 MIT License // -- lexer Alexey Zakharov XXX TODO License or CLA /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) { /* * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * * @module */ /*whatsupdoc*/ // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (typeof target != "function") throw new TypeError(); // TODO message // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){}; F.prototype = target.prototype; var self = new F; var result = target.apply( self, args.concat(slice.call(arguments)) ); if (result !== null && Object(result) === result) return result; return self; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(slice.call(arguments)) ); } }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. 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); // If JS engine supports accessors creating shortcuts. 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__); } // // Array // ===== // // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function isArray(obj) { return toString(obj) == "[object Array]"; }; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var self = toObject(this), thisp = arguments[1], i = 0, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object context fun.call(thisp, self[i], i, self); } i++; } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var self = toObject(this), length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, self); } return result; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, result = [], thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) result.push(self[i]); } return result; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, self)) return false; } return true; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) return true; } return false; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value and an empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) throw new TypeError(); // TODO message } while (true); } for (; i < length; i++) { if (i in self) result = fun.call(void 0, result, self[i], i, self); } return result; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value, empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) throw new TypeError(); // TODO message } while (true); } do { if (i in this) result = fun.call(void 0, result, self[i], i, self); } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = toObject(this), length = self.length >>> 0; if (!length) return -1; var i = 0; if (arguments.length > 1) i = toInteger(arguments[1]); // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = 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])); // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) return i; } return -1; }; } // // Object // ====== // // ES5 15.2.3.2 // http://es5.github.com/#x15.2.3.2 if (!Object.getPrototypeOf) { // https://github.com/kriskowal/es5-shim/issues#issue/2 // http://ejohn.org/blog/objectgetprototypeof/ // recommended by fschaefer on github Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } // ES5 15.2.3.3 // http://es5.github.com/#x15.2.3.3 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 object does not owns property return undefined immediately. if (!owns(object, property)) return; var descriptor, getter, setter; // If object has a property then it's for sure both `enumerable` and // `configurable`. descriptor = { enumerable: true, configurable: true }; // If JS engine supports accessor properties then property may be a // getter or setter. if (supportsAccessors) { // Unfortunately `__lookupGetter__` will return a getter even // if object has own non getter property along with a same named // inherited getter. To avoid misbehavior we temporary remove // `__proto__` so that `__lookupGetter__` will return getter only // if it's owned by an object. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); // Once we have getter and setter we can put values back. object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; // If it was accessor property we're done and return here // in order to avoid adding `value` to the descriptor. return descriptor; } } // If we got this far we know that object has an own property that is // not an accessor so we set it as a value and return descriptor. descriptor.value = object[property]; return descriptor; }; } // ES5 15.2.3.4 // http://es5.github.com/#x15.2.3.4 if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!Object.create) { Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = { "__proto__": null }; } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); // IE has no built-in implementation of `Object.getPrototypeOf` // neither `__proto__`, but this manually setting `__proto__` will // guarantee that `Object.getPrototypeOf` will work as expected with // objects created using `Object.create` object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } // ES5 15.2.3.6 // http://es5.github.com/#x15.2.3.6 // Patch for WebKit and IE8 standard mode // Designed by hax <hax.github.com> // related issue: https://github.com/kriskowal/es5-shim/issues#issue/5 // IE8 Reference: // http://msdn.microsoft.com/en-us/library/dd282900.aspx // http://msdn.microsoft.com/en-us/library/dd229916.aspx // WebKit Bugs: // https://bugs.webkit.org/show_bug.cgi?id=36423 function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { // returns falsy } } // check whether defineProperty works if it's given. Otherwise, // shim partially. 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); // make a valiant attempt to use the real defineProperty // for I8's DOM elements. if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { // try the shim if the real one doesn't work } } // If it's a data property. if (owns(descriptor, "value")) { // fail silently if "writable", "enumerable", or "configurable" // are requested but not supported /* // alternate approach: if ( // can't implement these features; allow false but not true !(owns(descriptor, "writable") ? descriptor.writable : true) || !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) || !(owns(descriptor, "configurable") ? descriptor.configurable : true) ) throw new RangeError( "This implementation of Object.defineProperty does not " + "support configurable, enumerable, or writable." ); */ if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { // As accessors are supported only on engines implementing // `__proto__` we can safely override `__proto__` while defining // a property to make sure that we don't hit an inherited // accessor. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; // Deleting a property anyway since getter / setter may be // defined on object itself. delete object[property]; object[property] = descriptor.value; // Setting original `__proto__` back now. object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); // If we got that far then getters and setters can be defined !! if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 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; }; } // ES5 15.2.3.8 // http://es5.github.com/#x15.2.3.8 if (!Object.seal) { Object.seal = function seal(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.9 // http://es5.github.com/#x15.2.3.9 if (!Object.freeze) { Object.freeze = function freeze(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // detect a Rhino bug and patch it 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); } // ES5 15.2.3.10 // http://es5.github.com/#x15.2.3.10 if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.11 // http://es5.github.com/#x15.2.3.11 if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } // ES5 15.2.3.12 // http://es5.github.com/#x15.2.3.12 if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } // ES5 15.2.3.13 // http://es5.github.com/#x15.2.3.13 if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { // 1. If Type(O) is not Object throw a TypeError exception. if (Object(object) === object) { throw new TypeError(); // TODO message } // 2. Return the Boolean value of the [[Extensible]] internal property of O. var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation 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; }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) { Date.prototype.toISOString = function toISOString() { var result, length, value, year; if (!isFinite(this)) throw new RangeError; // the date time string format is specified in 15.9.1.15. result = [this.getUTCMonth() + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = this.getUTCFullYear(); year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two digits. if (value < 10) result[length] = "0" + value; } // pad milliseconds to have three digits. return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z"; } } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). if (!Date.prototype.toJSON) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be ToPrimitive(O, hint Number). // 3. If tv is a Number and is not finite, return null. // XXX // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof this.toISOString != "function") throw new TypeError(); // TODO message // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return this.toISOString(); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function(NativeDate) { // Date.length === 7 var Date = function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length == 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); }; // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:\\.(\\d{3}))?" + // milliseconds capture ")?" + "(?:" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) Date[key] = NativeDate[key]; // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { match.shift(); // kill match[0], the full match // parse months, days, hours, minutes, seconds, and milliseconds for (var i = 1; i < 7; i++) { // provide default values if necessary match[i] = +(match[i] || (i < 3 ? 1 : 0)); // match[1] is the month. Months are 0-11 in JavaScript // `Date` objects, but 1-12 in ISO notation, so we // decrement. if (i == 1) match[i]--; } // parse the UTC offset component var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop(); // compute the explicit time zone offset if specified var offset = 0; if (sign) { // detect invalid offsets and return early if (hourOffset > 23 || minuteOffset > 59) return NaN; // express the provided time zone offset in minutes. The offset is // negative for time zones west of UTC; positive otherwise. offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1); } // Date.UTC for years between 0 and 99 converts year to 1900 + year // The Gregorian calendar has a 400-year cycle, so // to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...), // where 12622780800000 - number of milliseconds in Gregorian calendar 400 years var year = +match[0]; if (0 <= year && year <= 99) { match[0] = year + 400; return NativeDate.UTC.apply(this, match) + offset - 12622780800000; } // compute a new UTC date value, accounting for the optional offset return NativeDate.UTC.apply(this, match) + offset; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // // String // ====== // // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 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()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ 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, ""); }; } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer var toInteger = function (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; }; var prepareString = "a"[0] != "a", // ES5 9.9 // http://es5.github.com/#x9.9 toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError(); // TODO message } // If the implementation doesn't support by-index access of // string characters (ex. IE < 7), split the string if (prepareString && typeof o == "string" && o) { return o.split(""); } return Object(o); }; }); define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) { var EventEmitter = {}; 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; e = e || {}; e.type = eventName; if (!e.stopPropagation) { e.stopPropagation = function() { this.propagationStopped = true; }; } if (!e.preventDefault) { e.preventDefault = function() { this.defaultPrevented = true; }; } for (var i=0; i<listeners.length; i++) { listeners[i](e); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e); }; EventEmitter.setDefaultHandler = function(eventName, callback) { this._defaultHandlers = this._defaultHandlers || {}; if (this._defaultHandlers[eventName]) throw new Error("The default handler for '" + eventName + "' is already set"); this._defaultHandlers[eventName] = callback; }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) var listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners.push(callback); }; EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) { exports.inherits = (function() { var tempCtor = function() {}; return function(ctor, superCtor) { tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor.prototype; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }; }()); exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); define('ace/mode/coffee_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/mode/coffee/coffee-script'], function(require, exports, module) { var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var coffee = require("../mode/coffee/coffee-script"); window.addEventListener = function() {}; var Worker = exports.Worker = function(sender) { Mirror.call(this, sender); this.setTimeout(200); }; oop.inherits(Worker, Mirror); (function() { this.onUpdate = function() { var value = this.doc.getValue(); try { coffee.parse(value); } catch(e) { var m = e.message.match(/Parse error on line (\d+): (.*)/); if (m) { this.sender.emit("error", { row: parseInt(m[1], 10) - 1, column: null, text: m[2], type: "error" }); return; } if (e instanceof SyntaxError) { var m = e.message.match(/ on line (\d+)/); if (m) { this.sender.emit("error", { row: parseInt(m[1], 10) - 1, column: null, text: e.message.replace(m[0], ""), type: "error" }); } } return; } this.sender.emit("ok"); }; }).call(Worker.prototype); }); define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) { 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.deferredCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { doc.applyDeltas([e.data]); deferredUpdate.schedule(_self.$timeout); }); }; (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() { // abstract method }; }).call(Mirror.prototype); }); define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; /** * new Document([text]) * - text (String | Array): The starting text * * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * **/ var Document = function(text) { this.$lines = []; // There has to be one line at least in the document. If you pass an empty // string to the insert function, nothing will happen. Workaround. if (text.length == 0) { this.$lines = [""]; } else if (Array.isArray(text)) { this.insertLines(0, text); } else { this.insert({row: 0, column:0}, text); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength(); this.remove(new Range(0, 0, len, this.getLine(len-1).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); }; // check for IE split bug 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); if (match) { this.$autoNewLine = match[1]; } else { this.$autoNewLine = "\n"; } }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; case "auto": return this.$autoNewLine; } }; this.$autoNewLine = "\n"; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; }; 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) { if (range.start.row == range.end.row) { return this.$lines[range.start.row].substring(range.start.column, range.end.column); } else { var lines = this.getLines(range.start.row+1, range.end.row-1); lines.unshift((this.$lines[range.start.row] || "").substring(range.start.column)); lines.push((this.$lines[range.end.row] || "").substring(0, range.end.column)); return lines.join(this.getNewLineCharacter()); } }; 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; } return position; }; this.insert = function(position, text) { if (!text || text.length === 0) return position; position = this.$clipPosition(position); // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); var lines = this.$split(text); var firstLine = lines.splice(0, 1)[0]; var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0]; position = this.insertInLine(position, firstLine); if (lastLine !== null) { position = this.insertNewLine(position); // terminate first line position = this.insertLines(position.row, lines); position = this.insertInLine(position, lastLine || ""); } return position; }; this.insertLines = function(row, lines) { if (lines.length == 0) return {row: row, column: 0}; // apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF) // to circumvent that we have to break huge inserts into smaller chunks here if (lines.length > 0xFFFF) { var end = this.insertLines(row, lines.slice(0xFFFF)); lines = lines.slice(0, 0xFFFF); } var args = [row, 0]; args.push.apply(args, lines); this.$lines.splice.apply(this.$lines, args); var range = new Range(row, 0, row + lines.length, 0); var delta = { action: "insertLines", range: range, lines: lines }; this._emit("change", { data: delta }); return end || range.end; }; this.insertNewLine = function(position) { position = this.$clipPosition(position); var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column); this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length)); var end = { row : position.row + 1, column : 0 }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); return end; }; this.insertInLine = function(position, text) { if (text.length == 0) return position; var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column) + text + line.substring(position.column); var end = { row : position.row, column : position.column + text.length }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: text }; this._emit("change", { data: delta }); return end; }; this.remove = function(range) { // clip to document range.start = this.$clipPosition(range.start); range.end = this.$clipPosition(range.end); if (range.isEmpty()) return range.start; var firstRow = range.start.row; var lastRow = range.end.row; if (range.isMultiLine()) { var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1; var lastFullRow = lastRow - 1; if (range.end.column > 0) this.removeInLine(lastRow, 0, range.end.column); if (lastFullRow >= firstFullRow) this.removeLines(firstFullRow, lastFullRow); if (firstFullRow != firstRow) { this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length); this.removeNewLine(range.start.row); } } else { this.removeInLine(firstRow, range.start.column, range.end.column); } return range.start; }; this.removeInLine = function(row, startColumn, endColumn) { if (startColumn == endColumn) return; var range = new Range(row, startColumn, row, endColumn); var line = this.getLine(row); var removed = line.substring(startColumn, endColumn); var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length); this.$lines.splice(row, 1, newLine); var delta = { action: "removeText", range: range, text: removed }; this._emit("change", { data: delta }); return range.start; }; this.removeLines = function(firstRow, lastRow) { var range = new Range(firstRow, 0, lastRow + 1, 0); var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1); var delta = { action: "removeLines", range: range, nl: this.getNewLineCharacter(), lines: removed }; this._emit("change", { data: delta }); return removed; }; this.removeNewLine = function(row) { var firstLine = this.getLine(row); var secondLine = this.getLine(row+1); var range = new Range(row, firstLine.length, row+1, 0); var line = firstLine + secondLine; this.$lines.splice(row, 2, line); var delta = { action: "removeText", range: range, text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); }; this.replace = function(range, text) { if (text.length == 0 && range.isEmpty()) return range.start; // Shortcut: If the text we want to insert is the same as it is already // in the document, we don't have to replace anything. if (text == this.getTextRange(range)) return range.end; this.remove(range); if (text) { var end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "insertText") this.insert(range.start, delta.text); else if (delta.action == "removeLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "removeText") this.remove(range); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "insertText") this.remove(range); else if (delta.action == "removeLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "removeText") this.insert(range.start, delta.text); } }; }).call(Document.prototype); exports.Document = Document; }); define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class Range * * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. * **/ /** * new Range(startRow, startColumn, endRow, endColumn) * - startRow (Number): The starting row * - startColumn (Number): The starting column * - endRow (Number): The ending row * - endColumn (Number): The ending column * * Creates a new `Range` object with the given starting and ending row and column points. * **/ var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { /** * Range.isEqual(range) -> Boolean * - range (Range): A range to check against * * Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`. * **/ 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; } } } /** related to: Range.compare * Range.comparePoint(p) -> Number * - p (Range): A point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1<br/> * * Checks the row and column points of `p` with the row and column points of the calling range. * * * **/ this.comparePoint = function(p) { return this.compare(p.row, p.column); } /** related to: Range.comparePoint * Range.containsRange(range) -> Boolean * - range (Range): A range to compare with * * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. * **/ this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } /** * Range.intersects(range) -> Boolean * - range (Range): A range to compare with * * Returns `true` if passed in `range` intersects with the one calling this method. * **/ this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); } /** * Range.isEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. * **/ this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } /** * Range.isStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. * **/ this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; } /** * Range.setStart(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** * Range.setEnd(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** related to: Range.compare * Range.inside(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range. * **/ 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; } /** related to: Range.compare * Range.insideStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's starting points. * **/ this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; } /** related to: Range.compare * Range.insideEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's ending points. * **/ this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; } /** * Range.compare(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal <br/> * * `-1` if `p.row` is less then the calling range <br/> * * `1` if `p.row` is greater than the calling range <br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> * <br/> * If the ending row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0` <br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ 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); } } /** * Range.compareEnd(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } } /** * Range.compareInside(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`<br/> * * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`<br/> * <br/> * Otherwise, it returns the value after calling [[Range.compare `compare()`]]. * * Checks the row and column points with the row and column points of the calling range. * * * **/ 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); } } /** * Range.clipRows(firstRow, lastRow) -> Range * - firstRow (Number): The starting row * - lastRow (Number): The ending row * * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. * **/ this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) { var end = { row: lastRow+1, column: 0 }; } if (this.start.row > lastRow) { var start = { row: lastRow+1, column: 0 }; } if (this.start.row < firstRow) { var start = { row: firstRow, column: 0 }; } if (this.end.row < firstRow) { var end = { 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 ); }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; exports.Range = Range; }); define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; /** * new Anchor(doc, row, column) * - doc (Document): The document to associate with the anchor * - row (Number): The starting row position * - column (Number): The starting column position * * Creates a new `Anchor` and associates it with a document. * **/ var Anchor = exports.Anchor = function(doc, row, column) { this.document = doc; if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); this.$onChange = this.onChange.bind(this); doc.on("change", this.$onChange); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.onChange = function(e) { var delta = e.data; var range = delta.range; if (range.start.row == range.end.row && range.start.row != this.row) return; if (range.start.row > this.row) return; if (range.start.row == this.row && range.start.column > this.column) return; var row = this.row; var column = this.column; if (delta.action === "insertText") { if (range.start.row === row && range.start.column <= column) { if (range.start.row === range.end.row) { column += range.end.column - range.start.column; } else { column -= range.start.column; row += range.end.row - range.start.row; } } else if (range.start.row !== range.end.row && range.start.row < row) { row += range.end.row - range.start.row; } } else if (delta.action === "insertLines") { if (range.start.row <= row) { row += range.end.row - range.start.row; } } else if (delta.action == "removeText") { if (range.start.row == row && range.start.column < column) { if (range.end.column >= column) column = range.start.column; else column = Math.max(0, column - (range.end.column - range.start.column)); } else if (range.start.row !== range.end.row && range.start.row < row) { if (range.end.row == row) { column = Math.max(0, column - range.end.column) + range.start.column; } row -= (range.end.row - range.start.row); } else if (range.end.row == row) { row -= range.end.row - range.start.row; column = Math.max(0, column - range.end.column) + range.start.column; } } else if (delta.action == "removeLines") { if (range.start.row <= row) { if (range.end.row <= row) row -= range.end.row - range.start.row; else { row = range.start.row; column = 0; } } } this.setPosition(row, column, true); }; 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._emit("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("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); }); define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) { exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { return new Array(count + 1).join(string); }; 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<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function (obj) { if (typeof obj != "object") { return obj; } var copy = obj.constructor(); for (var key in obj) { if (typeof obj[key] == "object") { copy[key] = this.deepCopy(obj[key]); } else { copy[key] = obj[key]; } } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; return deferred; }; }); define('ace/mode/coffee/coffee-script', ['require', 'exports', 'module' , 'ace/mode/coffee/lexer', 'ace/mode/coffee/parser', 'ace/mode/coffee/nodes'], function(require, exports, module) { var Lexer = require("./lexer").Lexer; var parser = require("./parser"); var lexer = new Lexer(); parser.lexer = { lex: function() { var tag, _ref2; _ref2 = this.tokens[this.pos++] || [''], tag = _ref2[0], this.yytext = _ref2[1], this.yylineno = _ref2[2]; return tag; }, setInput: function(tokens) { this.tokens = tokens; return this.pos = 0; }, upcomingInput: function() { return ""; } }; parser.yy = require('./nodes'); exports.parse = function(code) { return parser.parse(lexer.tokenize(code)); }; }); define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coffee/rewriter', 'ace/mode/coffee/helpers'], function(require, exports, module) { // Generated by CoffeeScript 1.2.1-pre var BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HEREDOC, HEREDOC_ILLEGAL, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDEXABLE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NOT_REGEX, NOT_SPACED_REGEX, NUMBER, OPERATOR, REGEX, RELATION, RESERVED, Rewriter, SHIFT, SIMPLESTR, STRICT_PROSCRIBED, TRAILING_SPACES, UNARY, WHITESPACE, compact, count, key, last, starts, _ref, _ref1, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; _ref = require('./rewriter'), Rewriter = _ref.Rewriter, INVERSES = _ref.INVERSES; _ref1 = require('./helpers'), count = _ref1.count, starts = _ref1.starts, compact = _ref1.compact, last = _ref1.last; exports.Lexer = Lexer = (function() { Lexer.name = 'Lexer'; function Lexer() {} Lexer.prototype.tokenize = function(code, opts) { var i, tag; if (opts == null) opts = {}; if (WHITESPACE.test(code)) code = "\n" + code; code = code.replace(/\r/g, '').replace(TRAILING_SPACES, ''); this.code = code; this.line = opts.line || 0; this.indent = 0; this.indebt = 0; this.outdebt = 0; this.indents = []; this.ends = []; this.tokens = []; i = 0; while (this.chunk = code.slice(i)) { i += this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.heredocToken() || this.stringToken() || this.numberToken() || this.regexToken() || this.jsToken() || this.literalToken(); } this.closeIndentation(); if (tag = this.ends.pop()) this.error("missing " + tag); if (opts.rewrite === false) return this.tokens; return (new Rewriter).rewrite(this.tokens); }; Lexer.prototype.identifierToken = function() { var colon, forcedIdentifier, id, input, match, prev, tag, _ref2, _ref3; if (!(match = IDENTIFIER.exec(this.chunk))) return 0; input = match[0], id = match[1], colon = match[2]; if (id === 'own' && this.tag() === 'FOR') { this.token('OWN', id); return id.length; } forcedIdentifier = colon || (prev = last(this.tokens)) && (((_ref2 = prev[0]) === '.' || _ref2 === '?.' || _ref2 === '::') || !prev.spaced && prev[0] === '@'); tag = 'IDENTIFIER'; if (!forcedIdentifier && (__indexOf.call(JS_KEYWORDS, id) >= 0 || __indexOf.call(COFFEE_KEYWORDS, id) >= 0)) { tag = id.toUpperCase(); if (tag === 'WHEN' && (_ref3 = this.tag(), __indexOf.call(LINE_BREAK, _ref3) >= 0)) { tag = 'LEADING_WHEN'; } else if (tag === 'FOR') { this.seenFor = true; } else if (tag === 'UNLESS') { tag = 'IF'; } else if (__indexOf.call(UNARY, tag) >= 0) { tag = 'UNARY'; } else if (__indexOf.call(RELATION, tag) >= 0) { if (tag !== 'INSTANCEOF' && this.seenFor) { tag = 'FOR' + tag; this.seenFor = false; } else { tag = 'RELATION'; if (this.value() === '!') { this.tokens.pop(); id = '!' + id; } } } } if (__indexOf.call(JS_FORBIDDEN, id) >= 0) { if (forcedIdentifier) { tag = 'IDENTIFIER'; id = new String(id); id.reserved = true; } else if (__indexOf.call(RESERVED, id) >= 0) { this.error("reserved word \"" + id + "\""); } } if (!forcedIdentifier) { if (__indexOf.call(COFFEE_ALIASES, id) >= 0) id = COFFEE_ALIAS_MAP[id]; tag = (function() { switch (id) { case '!': return 'UNARY'; case '==': case '!=': return 'COMPARE'; case '&&': case '||': return 'LOGIC'; case 'true': case 'false': case 'null': case 'undefined': return 'BOOL'; case 'break': case 'continue': return 'STATEMENT'; default: return tag; } })(); } this.token(tag, id); if (colon) this.token(':', ':'); return input.length; }; Lexer.prototype.numberToken = function() { var binaryLiteral, lexedLength, match, number, octalLiteral; if (!(match = NUMBER.exec(this.chunk))) return 0; number = match[0]; if (/E/.test(number)) { this.error("exponential notation '" + number + "' must be indicated with a lowercase 'e'"); } else if (/[BOX]/.test(number)) { this.error("radix prefix '" + number + "' must be lowercase"); } else if (/^0[89]/.test(number)) { this.error("decimal literal '" + number + "' must not be prefixed with '0'"); } else if (/^0[0-7]/.test(number)) { this.error("octal literal '" + number + "' must be prefixed with '0o'"); } lexedLength = number.length; if (octalLiteral = /0o([0-7]+)/.exec(number)) { number = (parseInt(octalLiteral[1], 8)).toString(); } if (binaryLiteral = /0b([01]+)/.exec(number)) { number = (parseInt(binaryLiteral[1], 2)).toString(); } this.token('NUMBER', number); return lexedLength; }; Lexer.prototype.stringToken = function() { var match, octalEsc, string; switch (this.chunk.charAt(0)) { case "'": if (!(match = SIMPLESTR.exec(this.chunk))) return 0; this.token('STRING', (string = match[0]).replace(MULTILINER, '\\\n')); break; case '"': if (!(string = this.balancedString(this.chunk, '"'))) return 0; if (0 < string.indexOf('#{', 1)) { this.interpolateString(string.slice(1, -1)); } else { this.token('STRING', this.escapeLines(string)); } break; default: return 0; } if (octalEsc = /^(?:\\.|[^\\])*\\[0-7]/.test(string)) { this.error("octal escape sequences " + string + " are not allowed"); } this.line += count(string, '\n'); return string.length; }; Lexer.prototype.heredocToken = function() { var doc, heredoc, match, quote; if (!(match = HEREDOC.exec(this.chunk))) return 0; heredoc = match[0]; quote = heredoc.charAt(0); doc = this.sanitizeHeredoc(match[2], { quote: quote, indent: null }); if (quote === '"' && 0 <= doc.indexOf('#{')) { this.interpolateString(doc, { heredoc: true }); } else { this.token('STRING', this.makeString(doc, quote, true)); } this.line += count(heredoc, '\n'); return heredoc.length; }; Lexer.prototype.commentToken = function() { var comment, here, match; if (!(match = this.chunk.match(COMMENT))) return 0; comment = match[0], here = match[1]; if (here) { this.token('HERECOMMENT', this.sanitizeHeredoc(here, { herecomment: true, indent: Array(this.indent + 1).join(' ') })); } this.line += count(comment, '\n'); return comment.length; }; Lexer.prototype.jsToken = function() { var match, script; if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) { return 0; } this.token('JS', (script = match[0]).slice(1, -1)); return script.length; }; Lexer.prototype.regexToken = function() { var flags, length, match, prev, regex, _ref2, _ref3; if (this.chunk.charAt(0) !== '/') return 0; if (match = HEREGEX.exec(this.chunk)) { length = this.heregexToken(match); this.line += count(match[0], '\n'); return length; } prev = last(this.tokens); if (prev && (_ref2 = prev[0], __indexOf.call((prev.spaced ? NOT_REGEX : NOT_SPACED_REGEX), _ref2) >= 0)) { return 0; } if (!(match = REGEX.exec(this.chunk))) return 0; _ref3 = match, match = _ref3[0], regex = _ref3[1], flags = _ref3[2]; if (regex.slice(0, 2) === '/*') { this.error('regular expressions cannot begin with `*`'); } if (regex === '//') regex = '/(?:)/'; this.token('REGEX', "" + regex + flags); return match.length; }; Lexer.prototype.heregexToken = function(match) { var body, flags, heregex, re, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4, _ref5; heregex = match[0], body = match[1], flags = match[2]; if (0 > body.indexOf('#{')) { re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/'); if (re.match(/^\*/)) { this.error('regular expressions cannot begin with `*`'); } this.token('REGEX', "/" + (re || '(?:)') + "/" + flags); return heregex.length; } this.token('IDENTIFIER', 'RegExp'); this.tokens.push(['CALL_START', '(']); tokens = []; _ref2 = this.interpolateString(body, { regex: true }); for (_i = 0, _len = _ref2.length; _i < _len; _i++) { _ref3 = _ref2[_i], tag = _ref3[0], value = _ref3[1]; if (tag === 'TOKENS') { tokens.push.apply(tokens, value); } else { if (!(value = value.replace(HEREGEX_OMIT, ''))) continue; value = value.replace(/\\/g, '\\\\'); tokens.push(['STRING', this.makeString(value, '"', true)]); } tokens.push(['+', '+']); } tokens.pop(); if (((_ref4 = tokens[0]) != null ? _ref4[0] : void 0) !== 'STRING') { this.tokens.push(['STRING', '""'], ['+', '+']); } (_ref5 = this.tokens).push.apply(_ref5, tokens); if (flags) this.tokens.push([',', ','], ['STRING', '"' + flags + '"']); this.token(')', ')'); return heregex.length; }; Lexer.prototype.lineToken = function() { var diff, indent, match, noNewlines, prev, size; if (!(match = MULTI_DENT.exec(this.chunk))) return 0; indent = match[0]; this.line += count(indent, '\n'); this.seenFor = false; prev = last(this.tokens, 1); size = indent.length - 1 - indent.lastIndexOf('\n'); noNewlines = this.unfinished(); if (size - this.indebt === this.indent) { if (noNewlines) { this.suppressNewlines(); } else { this.newlineToken(); } return indent.length; } if (size > this.indent) { if (noNewlines) { this.indebt = size - this.indent; this.suppressNewlines(); return indent.length; } diff = size - this.indent + this.outdebt; this.token('INDENT', diff); this.indents.push(diff); this.ends.push('OUTDENT'); this.outdebt = this.indebt = 0; } else { this.indebt = 0; this.outdentToken(this.indent - size, noNewlines); } this.indent = size; return indent.length; }; Lexer.prototype.outdentToken = function(moveOut, noNewlines) { var dent, len; while (moveOut > 0) { len = this.indents.length - 1; if (this.indents[len] === void 0) { moveOut = 0; } else if (this.indents[len] === this.outdebt) { moveOut -= this.outdebt; this.outdebt = 0; } else if (this.indents[len] < this.outdebt) { this.outdebt -= this.indents[len]; moveOut -= this.indents[len]; } else { dent = this.indents.pop() - this.outdebt; moveOut -= dent; this.outdebt = 0; this.pair('OUTDENT'); this.token('OUTDENT', dent); } } if (dent) this.outdebt -= moveOut; while (this.value() === ';') { this.tokens.pop(); } if (!(this.tag() === 'TERMINATOR' || noNewlines)) { this.token('TERMINATOR', '\n'); } return this; }; Lexer.prototype.whitespaceToken = function() { var match, nline, prev; if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) { return 0; } prev = last(this.tokens); if (prev) prev[match ? 'spaced' : 'newLine'] = true; if (match) { return match[0].length; } else { return 0; } }; Lexer.prototype.newlineToken = function() { while (this.value() === ';') { this.tokens.pop(); } if (this.tag() !== 'TERMINATOR') this.token('TERMINATOR', '\n'); return this; }; Lexer.prototype.suppressNewlines = function() { if (this.value() === '\\') this.tokens.pop(); return this; }; Lexer.prototype.literalToken = function() { var match, prev, tag, value, _ref2, _ref3, _ref4, _ref5; if (match = OPERATOR.exec(this.chunk)) { value = match[0]; if (CODE.test(value)) this.tagParameters(); } else { value = this.chunk.charAt(0); } tag = value; prev = last(this.tokens); if (value === '=' && prev) { if (!prev[1].reserved && (_ref2 = prev[1], __indexOf.call(JS_FORBIDDEN, _ref2) >= 0)) { this.error("reserved word \"" + (this.value()) + "\" can't be assigned"); } if ((_ref3 = prev[1]) === '||' || _ref3 === '&&') { prev[0] = 'COMPOUND_ASSIGN'; prev[1] += '='; return value.length; } } if (value === ';') { this.seenFor = false; tag = 'TERMINATOR'; } else if (__indexOf.call(MATH, value) >= 0) { tag = 'MATH'; } else if (__indexOf.call(COMPARE, value) >= 0) { tag = 'COMPARE'; } else if (__indexOf.call(COMPOUND_ASSIGN, value) >= 0) { tag = 'COMPOUND_ASSIGN'; } else if (__indexOf.call(UNARY, value) >= 0) { tag = 'UNARY'; } else if (__indexOf.call(SHIFT, value) >= 0) { tag = 'SHIFT'; } else if (__indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : void 0)) { tag = 'LOGIC'; } else if (prev && !prev.spaced) { if (value === '(' && (_ref4 = prev[0], __indexOf.call(CALLABLE, _ref4) >= 0)) { if (prev[0] === '?') prev[0] = 'FUNC_EXIST'; tag = 'CALL_START'; } else if (value === '[' && (_ref5 = prev[0], __indexOf.call(INDEXABLE, _ref5) >= 0)) { tag = 'INDEX_START'; switch (prev[0]) { case '?': prev[0] = 'INDEX_SOAK'; } } } switch (value) { case '(': case '{': case '[': this.ends.push(INVERSES[value]); break; case ')': case '}': case ']': this.pair(value); } this.token(tag, value); return value.length; }; Lexer.prototype.sanitizeHeredoc = function(doc, options) { var attempt, herecomment, indent, match, _ref2; indent = options.indent, herecomment = options.herecomment; if (herecomment) { if (HEREDOC_ILLEGAL.test(doc)) { this.error("block comment cannot contain \"*/\", starting"); } if (doc.indexOf('\n') <= 0) return doc; } else { while (match = HEREDOC_INDENT.exec(doc)) { attempt = match[1]; if (indent === null || (0 < (_ref2 = attempt.length) && _ref2 < indent.length)) { indent = attempt; } } } if (indent) doc = doc.replace(RegExp("\\n" + indent, "g"), '\n'); if (!herecomment) doc = doc.replace(/^\n/, ''); return doc; }; Lexer.prototype.tagParameters = function() { var i, stack, tok, tokens; if (this.tag() !== ')') return this; stack = []; tokens = this.tokens; i = tokens.length; tokens[--i][0] = 'PARAM_END'; while (tok = tokens[--i]) { switch (tok[0]) { case ')': stack.push(tok); break; case '(': case 'CALL_START': if (stack.length) { stack.pop(); } else if (tok[0] === '(') { tok[0] = 'PARAM_START'; return this; } else { return this; } } } return this; }; Lexer.prototype.closeIndentation = function() { return this.outdentToken(this.indent); }; Lexer.prototype.balancedString = function(str, end) { var continueCount, i, letter, match, prev, stack, _i, _ref2; continueCount = 0; stack = [end]; for (i = _i = 1, _ref2 = str.length; 1 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 1 <= _ref2 ? ++_i : --_i) { if (continueCount) { --continueCount; continue; } switch (letter = str.charAt(i)) { case '\\': ++continueCount; continue; case end: stack.pop(); if (!stack.length) return str.slice(0, i + 1 || 9e9); end = stack[stack.length - 1]; continue; } if (end === '}' && (letter === '"' || letter === "'")) { stack.push(end = letter); } else if (end === '}' && letter === '/' && (match = HEREGEX.exec(str.slice(i)) || REGEX.exec(str.slice(i)))) { continueCount += match[0].length - 1; } else if (end === '}' && letter === '{') { stack.push(end = '}'); } else if (end === '"' && prev === '#' && letter === '{') { stack.push(end = '}'); } prev = letter; } return this.error("missing " + (stack.pop()) + ", starting"); }; Lexer.prototype.interpolateString = function(str, options) { var expr, heredoc, i, inner, interpolated, len, letter, nested, pi, regex, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4; if (options == null) options = {}; heredoc = options.heredoc, regex = options.regex; tokens = []; pi = 0; i = -1; while (letter = str.charAt(i += 1)) { if (letter === '\\') { i += 1; continue; } if (!(letter === '#' && str.charAt(i + 1) === '{' && (expr = this.balancedString(str.slice(i + 1), '}')))) { continue; } if (pi < i) tokens.push(['NEOSTRING', str.slice(pi, i)]); inner = expr.slice(1, -1); if (inner.length) { nested = new Lexer().tokenize(inner, { line: this.line, rewrite: false }); nested.pop(); if (((_ref2 = nested[0]) != null ? _ref2[0] : void 0) === 'TERMINATOR') { nested.shift(); } if (len = nested.length) { if (len > 1) { nested.unshift(['(', '(', this.line]); nested.push([')', ')', this.line]); } tokens.push(['TOKENS', nested]); } } i += expr.length; pi = i + 1; } if ((i > pi && pi < str.length)) tokens.push(['NEOSTRING', str.slice(pi)]); if (regex) return tokens; if (!tokens.length) return this.token('STRING', '""'); if (tokens[0][0] !== 'NEOSTRING') tokens.unshift(['', '']); if (interpolated = tokens.length > 1) this.token('(', '('); for (i = _i = 0, _len = tokens.length; _i < _len; i = ++_i) { _ref3 = tokens[i], tag = _ref3[0], value = _ref3[1]; if (i) this.token('+', '+'); if (tag === 'TOKENS') { (_ref4 = this.tokens).push.apply(_ref4, value); } else { this.token('STRING', this.makeString(value, '"', heredoc)); } } if (interpolated) this.token(')', ')'); return tokens; }; Lexer.prototype.pair = function(tag) { var size, wanted; if (tag !== (wanted = last(this.ends))) { if ('OUTDENT' !== wanted) this.error("unmatched " + tag); this.indent -= size = last(this.indents); this.outdentToken(size, true); return this.pair(tag); } return this.ends.pop(); }; Lexer.prototype.token = function(tag, value) { return this.tokens.push([tag, value, this.line]); }; Lexer.prototype.tag = function(index, tag) { var tok; return (tok = last(this.tokens, index)) && (tag ? tok[0] = tag : tok[0]); }; Lexer.prototype.value = function(index, val) { var tok; return (tok = last(this.tokens, index)) && (val ? tok[1] = val : tok[1]); }; Lexer.prototype.unfinished = function() { var _ref2; return LINE_CONTINUER.test(this.chunk) || ((_ref2 = this.tag()) === '\\' || _ref2 === '.' || _ref2 === '?.' || _ref2 === 'UNARY' || _ref2 === 'MATH' || _ref2 === '+' || _ref2 === '-' || _ref2 === 'SHIFT' || _ref2 === 'RELATION' || _ref2 === 'COMPARE' || _ref2 === 'LOGIC' || _ref2 === 'THROW' || _ref2 === 'EXTENDS'); }; Lexer.prototype.escapeLines = function(str, heredoc) { return str.replace(MULTILINER, heredoc ? '\\n' : ''); }; Lexer.prototype.makeString = function(body, quote, heredoc) { if (!body) return quote + quote; body = body.replace(/\\([\s\S])/g, function(match, contents) { if (contents === '\n' || contents === quote) { return contents; } else { return match; } }); body = body.replace(RegExp("" + quote, "g"), '\\$&'); return quote + this.escapeLines(body, heredoc) + quote; }; Lexer.prototype.error = function(message) { throw SyntaxError("" + message + " on line " + (this.line + 1)); }; return Lexer; })(); JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super']; COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when']; COFFEE_ALIAS_MAP = { and: '&&', or: '||', is: '==', isnt: '!=', not: '!', yes: 'true', no: 'false', on: 'true', off: 'false' }; COFFEE_ALIASES = (function() { var _results; _results = []; for (key in COFFEE_ALIAS_MAP) { _results.push(key); } return _results; })(); COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES); RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind', '__indexOf', 'implements', 'interface', 'let', 'package', 'private', 'protected', 'public', 'static', 'yield']; STRICT_PROSCRIBED = ['arguments', 'eval']; JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED); exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED); exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED; IDENTIFIER = /^([$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)([^\n\S]*:(?!:))?/; NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i; HEREDOC = /^("""|''')([\s\S]*?)(?:\n[^\n\S]*)?\1/; OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/; WHITESPACE = /^[^\n\S]+/; COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|(?:###)?$)|^(?:\s*#(?!##[^#]).*)+/; CODE = /^[-=]>/; MULTI_DENT = /^(?:\n[^\n\S]*)+/; SIMPLESTR = /^'[^\\']*(?:\\.[^\\']*)*'/; JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/; REGEX = /^(\/(?![\s=])[^[\/\n\\]*(?:(?:\\[\s\S]|\[[^\]\n\\]*(?:\\[\s\S][^\]\n\\]*)*])[^[\/\n\\]*)*\/)([imgy]{0,4})(?!\w)/; HEREGEX = /^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?!\w)/; HEREGEX_OMIT = /\s+(?:#.*)?/g; MULTILINER = /\n/g; HEREDOC_INDENT = /\n+([^\n\S]*)/g; HEREDOC_ILLEGAL = /\*\//; LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/; TRAILING_SPACES = /\s+$/; COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|=']; UNARY = ['!', '~', 'NEW', 'TYPEOF', 'DELETE', 'DO']; LOGIC = ['&&', '||', '&', '|', '^']; SHIFT = ['<<', '>>', '>>>']; COMPARE = ['==', '!=', '<', '>', '<=', '>=']; MATH = ['*', '/', '%']; RELATION = ['IN', 'OF', 'INSTANCEOF']; BOOL = ['TRUE', 'FALSE', 'NULL', 'UNDEFINED']; NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', '++', '--', ']']; NOT_SPACED_REGEX = NOT_REGEX.concat(')', '}', 'THIS', 'IDENTIFIER', 'STRING'); CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER']; INDEXABLE = CALLABLE.concat('NUMBER', 'BOOL'); LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR']; }); define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(require, exports, module) { // Generated by CoffeeScript 1.2.1-pre var BALANCED_PAIRS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_BLOCK, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, left, rite, _i, _len, _ref, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, __slice = [].slice; exports.Rewriter = (function() { Rewriter.name = 'Rewriter'; function Rewriter() {} Rewriter.prototype.rewrite = function(tokens) { this.tokens = tokens; this.removeLeadingNewlines(); this.removeMidExpressionNewlines(); this.closeOpenCalls(); this.closeOpenIndexes(); this.addImplicitIndentation(); this.tagPostfixConditionals(); this.addImplicitBraces(); this.addImplicitParentheses(); return this.tokens; }; Rewriter.prototype.scanTokens = function(block) { var i, token, tokens; tokens = this.tokens; i = 0; while (token = tokens[i]) { i += block.call(this, token, i, tokens); } return true; }; Rewriter.prototype.detectEnd = function(i, condition, action) { var levels, token, tokens, _ref, _ref1; tokens = this.tokens; levels = 0; while (token = tokens[i]) { if (levels === 0 && condition.call(this, token, i)) { return action.call(this, token, i); } if (!token || levels < 0) return action.call(this, token, i - 1); if (_ref = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0) { levels += 1; } else if (_ref1 = token[0], __indexOf.call(EXPRESSION_END, _ref1) >= 0) { levels -= 1; } i += 1; } return i - 1; }; Rewriter.prototype.removeLeadingNewlines = function() { var i, tag, _i, _len, _ref; _ref = this.tokens; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { tag = _ref[i][0]; if (tag !== 'TERMINATOR') break; } if (i) return this.tokens.splice(0, i); }; Rewriter.prototype.removeMidExpressionNewlines = function() { return this.scanTokens(function(token, i, tokens) { var _ref; if (!(token[0] === 'TERMINATOR' && (_ref = this.tag(i + 1), __indexOf.call(EXPRESSION_CLOSE, _ref) >= 0))) { return 1; } tokens.splice(i, 1); return 0; }); }; Rewriter.prototype.closeOpenCalls = function() { var action, condition; condition = function(token, i) { var _ref; return ((_ref = token[0]) === ')' || _ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')'; }; action = function(token, i) { return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END'; }; return this.scanTokens(function(token, i) { if (token[0] === 'CALL_START') this.detectEnd(i + 1, condition, action); return 1; }); }; Rewriter.prototype.closeOpenIndexes = function() { var action, condition; condition = function(token, i) { var _ref; return (_ref = token[0]) === ']' || _ref === 'INDEX_END'; }; action = function(token, i) { return token[0] = 'INDEX_END'; }; return this.scanTokens(function(token, i) { if (token[0] === 'INDEX_START') this.detectEnd(i + 1, condition, action); return 1; }); }; Rewriter.prototype.addImplicitBraces = function() { var action, condition, sameLine, stack, start, startIndent, startsLine; stack = []; start = null; startsLine = null; sameLine = true; startIndent = 0; condition = function(token, i) { var one, tag, three, two, _ref, _ref1; _ref = this.tokens.slice(i + 1, (i + 3) + 1 || 9e9), one = _ref[0], two = _ref[1], three = _ref[2]; if ('HERECOMMENT' === (one != null ? one[0] : void 0)) return false; tag = token[0]; if (__indexOf.call(LINEBREAKS, tag) >= 0) sameLine = false; return (((tag === 'TERMINATOR' || tag === 'OUTDENT') || (__indexOf.call(IMPLICIT_END, tag) >= 0 && sameLine)) && ((!startsLine && this.tag(i - 1) !== ',') || !((two != null ? two[0] : void 0) === ':' || (one != null ? one[0] : void 0) === '@' && (three != null ? three[0] : void 0) === ':'))) || (tag === ',' && one && ((_ref1 = one[0]) !== 'IDENTIFIER' && _ref1 !== 'NUMBER' && _ref1 !== 'STRING' && _ref1 !== '@' && _ref1 !== 'TERMINATOR' && _ref1 !== 'OUTDENT')); }; action = function(token, i) { var tok; tok = this.generate('}', '}', token[2]); return this.tokens.splice(i, 0, tok); }; return this.scanTokens(function(token, i, tokens) { var ago, idx, prevTag, tag, tok, value, _ref, _ref1; if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) { stack.push([(tag === 'INDENT' && this.tag(i - 1) === '{' ? '{' : tag), i]); return 1; } if (__indexOf.call(EXPRESSION_END, tag) >= 0) { start = stack.pop(); return 1; } if (!(tag === ':' && ((ago = this.tag(i - 2)) === ':' || ((_ref1 = stack[stack.length - 1]) != null ? _ref1[0] : void 0) !== '{'))) { return 1; } sameLine = true; stack.push(['{']); idx = ago === '@' ? i - 2 : i - 1; while (this.tag(idx - 2) === 'HERECOMMENT') { idx -= 2; } prevTag = this.tag(idx - 1); startsLine = !prevTag || (__indexOf.call(LINEBREAKS, prevTag) >= 0); value = new String('{'); value.generated = true; tok = this.generate('{', value, token[2]); tokens.splice(idx, 0, tok); this.detectEnd(i + 2, condition, action); return 2; }); }; Rewriter.prototype.addImplicitParentheses = function() { var action, condition, noCall, seenControl, seenSingle; noCall = seenSingle = seenControl = false; condition = function(token, i) { var post, tag, _ref, _ref1; tag = token[0]; if (!seenSingle && token.fromThen) return true; if (tag === 'IF' || tag === 'ELSE' || tag === 'CATCH' || tag === '->' || tag === '=>' || tag === 'CLASS') { seenSingle = true; } if (tag === 'IF' || tag === 'ELSE' || tag === 'SWITCH' || tag === 'TRY' || tag === '=') { seenControl = true; } if ((tag === '.' || tag === '?.' || tag === '::') && this.tag(i - 1) === 'OUTDENT') { return true; } return !token.generated && this.tag(i - 1) !== ',' && (__indexOf.call(IMPLICIT_END, tag) >= 0 || (tag === 'INDENT' && !seenControl)) && (tag !== 'INDENT' || (((_ref = this.tag(i - 2)) !== 'CLASS' && _ref !== 'EXTENDS') && (_ref1 = this.tag(i - 1), __indexOf.call(IMPLICIT_BLOCK, _ref1) < 0) && !((post = this.tokens[i + 1]) && post.generated && post[0] === '{'))); }; action = function(token, i) { return this.tokens.splice(i, 0, this.generate('CALL_END', ')', token[2])); }; return this.scanTokens(function(token, i, tokens) { var callObject, current, next, prev, tag, _ref, _ref1, _ref2; tag = token[0]; if (tag === 'CLASS' || tag === 'IF' || tag === 'FOR' || tag === 'WHILE') { noCall = true; } _ref = tokens.slice(i - 1, (i + 1) + 1 || 9e9), prev = _ref[0], current = _ref[1], next = _ref[2]; callObject = !noCall && tag === 'INDENT' && next && next.generated && next[0] === '{' && prev && (_ref1 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref1) >= 0); seenSingle = false; seenControl = false; if (__indexOf.call(LINEBREAKS, tag) >= 0) noCall = false; if (prev && !prev.spaced && tag === '?') token.call = true; if (token.fromThen) return 1; if (!(callObject || (prev != null ? prev.spaced : void 0) && (prev.call || (_ref2 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref2) >= 0)) && (__indexOf.call(IMPLICIT_CALL, tag) >= 0 || !(token.spaced || token.newLine) && __indexOf.call(IMPLICIT_UNSPACED_CALL, tag) >= 0))) { return 1; } tokens.splice(i, 0, this.generate('CALL_START', '(', token[2])); this.detectEnd(i + 1, condition, action); if (prev[0] === '?') prev[0] = 'FUNC_EXIST'; return 2; }); }; Rewriter.prototype.addImplicitIndentation = function() { var action, condition, indent, outdent, starter; starter = indent = outdent = null; condition = function(token, i) { var _ref; return token[1] !== ';' && (_ref = token[0], __indexOf.call(SINGLE_CLOSERS, _ref) >= 0) && !(token[0] === 'ELSE' && (starter !== 'IF' && starter !== 'THEN')); }; action = function(token, i) { return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent); }; return this.scanTokens(function(token, i, tokens) { var tag, _ref, _ref1; tag = token[0]; if (tag === 'TERMINATOR' && this.tag(i + 1) === 'THEN') { tokens.splice(i, 1); return 0; } if (tag === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') { tokens.splice.apply(tokens, [i, 0].concat(__slice.call(this.indentation(token)))); return 2; } if (tag === 'CATCH' && ((_ref = this.tag(i + 2)) === 'OUTDENT' || _ref === 'TERMINATOR' || _ref === 'FINALLY')) { tokens.splice.apply(tokens, [i + 2, 0].concat(__slice.call(this.indentation(token)))); return 4; } if (__indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) { starter = tag; _ref1 = this.indentation(token, true), indent = _ref1[0], outdent = _ref1[1]; if (starter === 'THEN') indent.fromThen = true; tokens.splice(i + 1, 0, indent); this.detectEnd(i + 2, condition, action); if (tag === 'THEN') tokens.splice(i, 1); return 1; } return 1; }); }; Rewriter.prototype.tagPostfixConditionals = function() { var action, condition, original; original = null; condition = function(token, i) { var _ref; return (_ref = token[0]) === 'TERMINATOR' || _ref === 'INDENT'; }; action = function(token, i) { if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) { return original[0] = 'POST_' + original[0]; } }; return this.scanTokens(function(token, i) { if (token[0] !== 'IF') return 1; original = token; this.detectEnd(i + 1, condition, action); return 1; }); }; Rewriter.prototype.indentation = function(token, implicit) { var indent, outdent; if (implicit == null) implicit = false; indent = ['INDENT', 2, token[2]]; outdent = ['OUTDENT', 2, token[2]]; if (implicit) indent.generated = outdent.generated = true; return [indent, outdent]; }; Rewriter.prototype.generate = function(tag, value, line) { var tok; tok = [tag, value, line]; tok.generated = true; return tok; }; Rewriter.prototype.tag = function(i) { var _ref; return (_ref = this.tokens[i]) != null ? _ref[0] : void 0; }; return Rewriter; })(); BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END']]; exports.INVERSES = INVERSES = {}; EXPRESSION_START = []; EXPRESSION_END = []; for (_i = 0, _len = BALANCED_PAIRS.length; _i < _len; _i++) { _ref = BALANCED_PAIRS[_i], left = _ref[0], rite = _ref[1]; EXPRESSION_START.push(INVERSES[rite] = left); EXPRESSION_END.push(INVERSES[left] = rite); } EXPRESSION_CLOSE = ['CATCH', 'WHEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END); IMPLICIT_FUNC = ['IDENTIFIER', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS']; IMPLICIT_CALL = ['IDENTIFIER', 'NUMBER', 'STRING', 'JS', 'REGEX', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'BOOL', 'UNARY', 'SUPER', '@', '->', '=>', '[', '(', '{', '--', '++']; IMPLICIT_UNSPACED_CALL = ['+', '-']; IMPLICIT_BLOCK = ['->', '=>', '{', '[', ',']; IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR']; SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN']; SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN']; LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT']; }); define('ace/mode/coffee/helpers', ['require', 'exports', 'module' ], function(require, exports, module) { // Generated by CoffeeScript 1.2.1-pre var extend, flatten; exports.starts = function(string, literal, start) { return literal === string.substr(start, literal.length); }; exports.ends = function(string, literal, back) { var len; len = literal.length; return literal === string.substr(string.length - len - (back || 0), len); }; exports.compact = function(array) { var item, _i, _len, _results; _results = []; for (_i = 0, _len = array.length; _i < _len; _i++) { item = array[_i]; if (item) _results.push(item); } return _results; }; exports.count = function(string, substr) { var num, pos; num = pos = 0; if (!substr.length) return 1 / 0; while (pos = 1 + string.indexOf(substr, pos)) { num++; } return num; }; exports.merge = function(options, overrides) { return extend(extend({}, options), overrides); }; extend = exports.extend = function(object, properties) { var key, val; for (key in properties) { val = properties[key]; object[key] = val; } return object; }; exports.flatten = flatten = function(array) { var element, flattened, _i, _len; flattened = []; for (_i = 0, _len = array.length; _i < _len; _i++) { element = array[_i]; if (element instanceof Array) { flattened = flattened.concat(flatten(element)); } else { flattened.push(element); } } return flattened; }; exports.del = function(obj, key) { var val; val = obj[key]; delete obj[key]; return val; }; exports.last = function(array, back) { return array[array.length - (back || 0) - 1]; }; }); define('ace/mode/coffee/parser', ['require', 'exports', 'module' ], function(require, exports, module) { /* Jison generated parser */ undefined var parser = {trace: function trace() { }, yy: {}, symbols_: {"error":2,"Root":3,"Body":4,"Block":5,"TERMINATOR":6,"Line":7,"Expression":8,"Statement":9,"Return":10,"Comment":11,"STATEMENT":12,"Value":13,"Invocation":14,"Code":15,"Operation":16,"Assign":17,"If":18,"Try":19,"While":20,"For":21,"Switch":22,"Class":23,"Throw":24,"INDENT":25,"OUTDENT":26,"Identifier":27,"IDENTIFIER":28,"AlphaNumeric":29,"NUMBER":30,"STRING":31,"Literal":32,"JS":33,"REGEX":34,"DEBUGGER":35,"BOOL":36,"Assignable":37,"=":38,"AssignObj":39,"ObjAssignable":40,":":41,"ThisProperty":42,"RETURN":43,"HERECOMMENT":44,"PARAM_START":45,"ParamList":46,"PARAM_END":47,"FuncGlyph":48,"->":49,"=>":50,"OptComma":51,",":52,"Param":53,"ParamVar":54,"...":55,"Array":56,"Object":57,"Splat":58,"SimpleAssignable":59,"Accessor":60,"Parenthetical":61,"Range":62,"This":63,".":64,"?.":65,"::":66,"Index":67,"INDEX_START":68,"IndexValue":69,"INDEX_END":70,"INDEX_SOAK":71,"Slice":72,"{":73,"AssignList":74,"}":75,"CLASS":76,"EXTENDS":77,"OptFuncExist":78,"Arguments":79,"SUPER":80,"FUNC_EXIST":81,"CALL_START":82,"CALL_END":83,"ArgList":84,"THIS":85,"@":86,"[":87,"]":88,"RangeDots":89,"..":90,"Arg":91,"SimpleArgs":92,"TRY":93,"Catch":94,"FINALLY":95,"CATCH":96,"THROW":97,"(":98,")":99,"WhileSource":100,"WHILE":101,"WHEN":102,"UNTIL":103,"Loop":104,"LOOP":105,"ForBody":106,"FOR":107,"ForStart":108,"ForSource":109,"ForVariables":110,"OWN":111,"ForValue":112,"FORIN":113,"FOROF":114,"BY":115,"SWITCH":116,"Whens":117,"ELSE":118,"When":119,"LEADING_WHEN":120,"IfBlock":121,"IF":122,"POST_IF":123,"UNARY":124,"-":125,"+":126,"--":127,"++":128,"?":129,"MATH":130,"SHIFT":131,"COMPARE":132,"LOGIC":133,"RELATION":134,"COMPOUND_ASSIGN":135,"$accept":0,"$end":1}, terminals_: {2:"error",6:"TERMINATOR",12:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",31:"STRING",33:"JS",34:"REGEX",35:"DEBUGGER",36:"BOOL",38:"=",41:":",43:"RETURN",44:"HERECOMMENT",45:"PARAM_START",47:"PARAM_END",49:"->",50:"=>",52:",",55:"...",64:".",65:"?.",66:"::",68:"INDEX_START",70:"INDEX_END",71:"INDEX_SOAK",73:"{",75:"}",76:"CLASS",77:"EXTENDS",80:"SUPER",81:"FUNC_EXIST",82:"CALL_START",83:"CALL_END",85:"THIS",86:"@",87:"[",88:"]",90:"..",93:"TRY",95:"FINALLY",96:"CATCH",97:"THROW",98:"(",99:")",101:"WHILE",102:"WHEN",103:"UNTIL",105:"LOOP",107:"FOR",111:"OWN",113:"FORIN",114:"FOROF",115:"BY",116:"SWITCH",118:"ELSE",120:"LEADING_WHEN",122:"IF",123:"POST_IF",124:"UNARY",125:"-",126:"+",127:"--",128:"++",129:"?",130:"MATH",131:"SHIFT",132:"COMPARE",133:"LOGIC",134:"RELATION",135:"COMPOUND_ASSIGN"}, productions_: [0,[3,0],[3,1],[3,2],[4,1],[4,3],[4,2],[7,1],[7,1],[9,1],[9,1],[9,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[5,2],[5,3],[27,1],[29,1],[29,1],[32,1],[32,1],[32,1],[32,1],[32,1],[17,3],[17,4],[17,5],[39,1],[39,3],[39,5],[39,1],[40,1],[40,1],[40,1],[10,2],[10,1],[11,1],[15,5],[15,2],[48,1],[48,1],[51,0],[51,1],[46,0],[46,1],[46,3],[53,1],[53,2],[53,3],[54,1],[54,1],[54,1],[54,1],[58,2],[59,1],[59,2],[59,2],[59,1],[37,1],[37,1],[37,1],[13,1],[13,1],[13,1],[13,1],[13,1],[60,2],[60,2],[60,2],[60,1],[60,1],[67,3],[67,2],[69,1],[69,1],[57,4],[74,0],[74,1],[74,3],[74,4],[74,6],[23,1],[23,2],[23,3],[23,4],[23,2],[23,3],[23,4],[23,5],[14,3],[14,3],[14,1],[14,2],[78,0],[78,1],[79,2],[79,4],[63,1],[63,1],[42,2],[56,2],[56,4],[89,1],[89,1],[62,5],[72,3],[72,2],[72,2],[72,1],[84,1],[84,3],[84,4],[84,4],[84,6],[91,1],[91,1],[92,1],[92,3],[19,2],[19,3],[19,4],[19,5],[94,3],[24,2],[61,3],[61,5],[100,2],[100,4],[100,2],[100,4],[20,2],[20,2],[20,2],[20,1],[104,2],[104,2],[21,2],[21,2],[21,2],[106,2],[106,2],[108,2],[108,3],[112,1],[112,1],[112,1],[110,1],[110,3],[109,2],[109,2],[109,4],[109,4],[109,4],[109,6],[109,6],[22,5],[22,7],[22,4],[22,6],[117,1],[117,2],[119,3],[119,4],[121,3],[121,5],[18,1],[18,3],[18,3],[18,3],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,5],[16,3]], performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { var $0 = $$.length - 1; switch (yystate) { case 1:return this.$ = new yy.Block; break; case 2:return this.$ = $$[$0]; break; case 3:return this.$ = $$[$0-1]; break; case 4:this.$ = yy.Block.wrap([$$[$0]]); break; case 5:this.$ = $$[$0-2].push($$[$0]); break; case 6:this.$ = $$[$0-1]; break; case 7:this.$ = $$[$0]; break; case 8:this.$ = $$[$0]; break; case 9:this.$ = $$[$0]; break; case 10:this.$ = $$[$0]; break; case 11:this.$ = new yy.Literal($$[$0]); break; case 12:this.$ = $$[$0]; break; case 13:this.$ = $$[$0]; break; case 14:this.$ = $$[$0]; break; case 15:this.$ = $$[$0]; break; case 16:this.$ = $$[$0]; break; case 17:this.$ = $$[$0]; break; case 18:this.$ = $$[$0]; break; case 19:this.$ = $$[$0]; break; case 20:this.$ = $$[$0]; break; case 21:this.$ = $$[$0]; break; case 22:this.$ = $$[$0]; break; case 23:this.$ = $$[$0]; break; case 24:this.$ = new yy.Block; break; case 25:this.$ = $$[$0-1]; break; case 26:this.$ = new yy.Literal($$[$0]); break; case 27:this.$ = new yy.Literal($$[$0]); break; case 28:this.$ = new yy.Literal($$[$0]); break; case 29:this.$ = $$[$0]; break; case 30:this.$ = new yy.Literal($$[$0]); break; case 31:this.$ = new yy.Literal($$[$0]); break; case 32:this.$ = new yy.Literal($$[$0]); break; case 33:this.$ = (function () { var val; val = new yy.Literal($$[$0]); if ($$[$0] === 'undefined') val.isUndefined = true; return val; }()); break; case 34:this.$ = new yy.Assign($$[$0-2], $$[$0]); break; case 35:this.$ = new yy.Assign($$[$0-3], $$[$0]); break; case 36:this.$ = new yy.Assign($$[$0-4], $$[$0-1]); break; case 37:this.$ = new yy.Value($$[$0]); break; case 38:this.$ = new yy.Assign(new yy.Value($$[$0-2]), $$[$0], 'object'); break; case 39:this.$ = new yy.Assign(new yy.Value($$[$0-4]), $$[$0-1], 'object'); break; case 40:this.$ = $$[$0]; break; case 41:this.$ = $$[$0]; break; case 42:this.$ = $$[$0]; break; case 43:this.$ = $$[$0]; break; case 44:this.$ = new yy.Return($$[$0]); break; case 45:this.$ = new yy.Return; break; case 46:this.$ = new yy.Comment($$[$0]); break; case 47:this.$ = new yy.Code($$[$0-3], $$[$0], $$[$0-1]); break; case 48:this.$ = new yy.Code([], $$[$0], $$[$0-1]); break; case 49:this.$ = 'func'; break; case 50:this.$ = 'boundfunc'; break; case 51:this.$ = $$[$0]; break; case 52:this.$ = $$[$0]; break; case 53:this.$ = []; break; case 54:this.$ = [$$[$0]]; break; case 55:this.$ = $$[$0-2].concat($$[$0]); break; case 56:this.$ = new yy.Param($$[$0]); break; case 57:this.$ = new yy.Param($$[$0-1], null, true); break; case 58:this.$ = new yy.Param($$[$0-2], $$[$0]); break; case 59:this.$ = $$[$0]; break; case 60:this.$ = $$[$0]; break; case 61:this.$ = $$[$0]; break; case 62:this.$ = $$[$0]; break; case 63:this.$ = new yy.Splat($$[$0-1]); break; case 64:this.$ = new yy.Value($$[$0]); break; case 65:this.$ = $$[$0-1].add($$[$0]); break; case 66:this.$ = new yy.Value($$[$0-1], [].concat($$[$0])); break; case 67:this.$ = $$[$0]; break; case 68:this.$ = $$[$0]; break; case 69:this.$ = new yy.Value($$[$0]); break; case 70:this.$ = new yy.Value($$[$0]); break; case 71:this.$ = $$[$0]; break; case 72:this.$ = new yy.Value($$[$0]); break; case 73:this.$ = new yy.Value($$[$0]); break; case 74:this.$ = new yy.Value($$[$0]); break; case 75:this.$ = $$[$0]; break; case 76:this.$ = new yy.Access($$[$0]); break; case 77:this.$ = new yy.Access($$[$0], 'soak'); break; case 78:this.$ = [new yy.Access(new yy.Literal('prototype')), new yy.Access($$[$0])]; break; case 79:this.$ = new yy.Access(new yy.Literal('prototype')); break; case 80:this.$ = $$[$0]; break; case 81:this.$ = $$[$0-1]; break; case 82:this.$ = yy.extend($$[$0], { soak: true }); break; case 83:this.$ = new yy.Index($$[$0]); break; case 84:this.$ = new yy.Slice($$[$0]); break; case 85:this.$ = new yy.Obj($$[$0-2], $$[$0-3].generated); break; case 86:this.$ = []; break; case 87:this.$ = [$$[$0]]; break; case 88:this.$ = $$[$0-2].concat($$[$0]); break; case 89:this.$ = $$[$0-3].concat($$[$0]); break; case 90:this.$ = $$[$0-5].concat($$[$0-2]); break; case 91:this.$ = new yy.Class; break; case 92:this.$ = new yy.Class(null, null, $$[$0]); break; case 93:this.$ = new yy.Class(null, $$[$0]); break; case 94:this.$ = new yy.Class(null, $$[$0-1], $$[$0]); break; case 95:this.$ = new yy.Class($$[$0]); break; case 96:this.$ = new yy.Class($$[$0-1], null, $$[$0]); break; case 97:this.$ = new yy.Class($$[$0-2], $$[$0]); break; case 98:this.$ = new yy.Class($$[$0-3], $$[$0-1], $$[$0]); break; case 99:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]); break; case 100:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]); break; case 101:this.$ = new yy.Call('super', [new yy.Splat(new yy.Literal('arguments'))]); break; case 102:this.$ = new yy.Call('super', $$[$0]); break; case 103:this.$ = false; break; case 104:this.$ = true; break; case 105:this.$ = []; break; case 106:this.$ = $$[$0-2]; break; case 107:this.$ = new yy.Value(new yy.Literal('this')); break; case 108:this.$ = new yy.Value(new yy.Literal('this')); break; case 109:this.$ = new yy.Value(new yy.Literal('this'), [new yy.Access($$[$0])], 'this'); break; case 110:this.$ = new yy.Arr([]); break; case 111:this.$ = new yy.Arr($$[$0-2]); break; case 112:this.$ = 'inclusive'; break; case 113:this.$ = 'exclusive'; break; case 114:this.$ = new yy.Range($$[$0-3], $$[$0-1], $$[$0-2]); break; case 115:this.$ = new yy.Range($$[$0-2], $$[$0], $$[$0-1]); break; case 116:this.$ = new yy.Range($$[$0-1], null, $$[$0]); break; case 117:this.$ = new yy.Range(null, $$[$0], $$[$0-1]); break; case 118:this.$ = new yy.Range(null, null, $$[$0]); break; case 119:this.$ = [$$[$0]]; break; case 120:this.$ = $$[$0-2].concat($$[$0]); break; case 121:this.$ = $$[$0-3].concat($$[$0]); break; case 122:this.$ = $$[$0-2]; break; case 123:this.$ = $$[$0-5].concat($$[$0-2]); break; case 124:this.$ = $$[$0]; break; case 125:this.$ = $$[$0]; break; case 126:this.$ = $$[$0]; break; case 127:this.$ = [].concat($$[$0-2], $$[$0]); break; case 128:this.$ = new yy.Try($$[$0]); break; case 129:this.$ = new yy.Try($$[$0-1], $$[$0][0], $$[$0][1]); break; case 130:this.$ = new yy.Try($$[$0-2], null, null, $$[$0]); break; case 131:this.$ = new yy.Try($$[$0-3], $$[$0-2][0], $$[$0-2][1], $$[$0]); break; case 132:this.$ = [$$[$0-1], $$[$0]]; break; case 133:this.$ = new yy.Throw($$[$0]); break; case 134:this.$ = new yy.Parens($$[$0-1]); break; case 135:this.$ = new yy.Parens($$[$0-2]); break; case 136:this.$ = new yy.While($$[$0]); break; case 137:this.$ = new yy.While($$[$0-2], { guard: $$[$0] }); break; case 138:this.$ = new yy.While($$[$0], { invert: true }); break; case 139:this.$ = new yy.While($$[$0-2], { invert: true, guard: $$[$0] }); break; case 140:this.$ = $$[$0-1].addBody($$[$0]); break; case 141:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); break; case 142:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); break; case 143:this.$ = $$[$0]; break; case 144:this.$ = new yy.While(new yy.Literal('true')).addBody($$[$0]); break; case 145:this.$ = new yy.While(new yy.Literal('true')).addBody(yy.Block.wrap([$$[$0]])); break; case 146:this.$ = new yy.For($$[$0-1], $$[$0]); break; case 147:this.$ = new yy.For($$[$0-1], $$[$0]); break; case 148:this.$ = new yy.For($$[$0], $$[$0-1]); break; case 149:this.$ = { source: new yy.Value($$[$0]) }; break; case 150:this.$ = (function () { $$[$0].own = $$[$0-1].own; $$[$0].name = $$[$0-1][0]; $$[$0].index = $$[$0-1][1]; return $$[$0]; }()); break; case 151:this.$ = $$[$0]; break; case 152:this.$ = (function () { $$[$0].own = true; return $$[$0]; }()); break; case 153:this.$ = $$[$0]; break; case 154:this.$ = new yy.Value($$[$0]); break; case 155:this.$ = new yy.Value($$[$0]); break; case 156:this.$ = [$$[$0]]; break; case 157:this.$ = [$$[$0-2], $$[$0]]; break; case 158:this.$ = { source: $$[$0] }; break; case 159:this.$ = { source: $$[$0], object: true }; break; case 160:this.$ = { source: $$[$0-2], guard: $$[$0] }; break; case 161:this.$ = { source: $$[$0-2], guard: $$[$0], object: true }; break; case 162:this.$ = { source: $$[$0-2], step: $$[$0] }; break; case 163:this.$ = { source: $$[$0-4], guard: $$[$0-2], step: $$[$0] }; break; case 164:this.$ = { source: $$[$0-4], step: $$[$0-2], guard: $$[$0] }; break; case 165:this.$ = new yy.Switch($$[$0-3], $$[$0-1]); break; case 166:this.$ = new yy.Switch($$[$0-5], $$[$0-3], $$[$0-1]); break; case 167:this.$ = new yy.Switch(null, $$[$0-1]); break; case 168:this.$ = new yy.Switch(null, $$[$0-3], $$[$0-1]); break; case 169:this.$ = $$[$0]; break; case 170:this.$ = $$[$0-1].concat($$[$0]); break; case 171:this.$ = [[$$[$0-1], $$[$0]]]; break; case 172:this.$ = [[$$[$0-2], $$[$0-1]]]; break; case 173:this.$ = new yy.If($$[$0-1], $$[$0], { type: $$[$0-2] }); break; case 174:this.$ = $$[$0-4].addElse(new yy.If($$[$0-1], $$[$0], { type: $$[$0-2] })); break; case 175:this.$ = $$[$0]; break; case 176:this.$ = $$[$0-2].addElse($$[$0]); break; case 177:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { type: $$[$0-1], statement: true }); break; case 178:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { type: $$[$0-1], statement: true }); break; case 179:this.$ = new yy.Op($$[$0-1], $$[$0]); break; case 180:this.$ = new yy.Op('-', $$[$0]); break; case 181:this.$ = new yy.Op('+', $$[$0]); break; case 182:this.$ = new yy.Op('--', $$[$0]); break; case 183:this.$ = new yy.Op('++', $$[$0]); break; case 184:this.$ = new yy.Op('--', $$[$0-1], null, true); break; case 185:this.$ = new yy.Op('++', $$[$0-1], null, true); break; case 186:this.$ = new yy.Existence($$[$0-1]); break; case 187:this.$ = new yy.Op('+', $$[$0-2], $$[$0]); break; case 188:this.$ = new yy.Op('-', $$[$0-2], $$[$0]); break; case 189:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); break; case 190:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); break; case 191:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); break; case 192:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); break; case 193:this.$ = (function () { if ($$[$0-1].charAt(0) === '!') { return new yy.Op($$[$0-1].slice(1), $$[$0-2], $$[$0]).invert(); } else { return new yy.Op($$[$0-1], $$[$0-2], $$[$0]); } }()); break; case 194:this.$ = new yy.Assign($$[$0-2], $$[$0], $$[$0-1]); break; case 195:this.$ = new yy.Assign($$[$0-4], $$[$0-1], $$[$0-3]); break; case 196:this.$ = new yy.Extends($$[$0-2], $$[$0]); break; } }, table: [{1:[2,1],3:1,4:2,5:3,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[3]},{1:[2,2],6:[1,72]},{6:[1,73]},{1:[2,4],6:[2,4],26:[2,4],99:[2,4]},{4:75,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[1,74],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,7],6:[2,7],26:[2,7],99:[2,7],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,8],6:[2,8],26:[2,8],99:[2,8],100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,12],6:[2,12],25:[2,12],26:[2,12],47:[2,12],52:[2,12],55:[2,12],60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,12],71:[1,98],75:[2,12],78:90,81:[1,92],82:[2,103],83:[2,12],88:[2,12],90:[2,12],99:[2,12],101:[2,12],102:[2,12],103:[2,12],107:[2,12],115:[2,12],123:[2,12],125:[2,12],126:[2,12],129:[2,12],130:[2,12],131:[2,12],132:[2,12],133:[2,12],134:[2,12]},{1:[2,13],6:[2,13],25:[2,13],26:[2,13],47:[2,13],52:[2,13],55:[2,13],60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,13],71:[1,98],75:[2,13],78:99,81:[1,92],82:[2,103],83:[2,13],88:[2,13],90:[2,13],99:[2,13],101:[2,13],102:[2,13],103:[2,13],107:[2,13],115:[2,13],123:[2,13],125:[2,13],126:[2,13],129:[2,13],130:[2,13],131:[2,13],132:[2,13],133:[2,13],134:[2,13]},{1:[2,14],6:[2,14],25:[2,14],26:[2,14],47:[2,14],52:[2,14],55:[2,14],70:[2,14],75:[2,14],83:[2,14],88:[2,14],90:[2,14],99:[2,14],101:[2,14],102:[2,14],103:[2,14],107:[2,14],115:[2,14],123:[2,14],125:[2,14],126:[2,14],129:[2,14],130:[2,14],131:[2,14],132:[2,14],133:[2,14],134:[2,14]},{1:[2,15],6:[2,15],25:[2,15],26:[2,15],47:[2,15],52:[2,15],55:[2,15],70:[2,15],75:[2,15],83:[2,15],88:[2,15],90:[2,15],99:[2,15],101:[2,15],102:[2,15],103:[2,15],107:[2,15],115:[2,15],123:[2,15],125:[2,15],126:[2,15],129:[2,15],130:[2,15],131:[2,15],132:[2,15],133:[2,15],134:[2,15]},{1:[2,16],6:[2,16],25:[2,16],26:[2,16],47:[2,16],52:[2,16],55:[2,16],70:[2,16],75:[2,16],83:[2,16],88:[2,16],90:[2,16],99:[2,16],101:[2,16],102:[2,16],103:[2,16],107:[2,16],115:[2,16],123:[2,16],125:[2,16],126:[2,16],129:[2,16],130:[2,16],131:[2,16],132:[2,16],133:[2,16],134:[2,16]},{1:[2,17],6:[2,17],25:[2,17],26:[2,17],47:[2,17],52:[2,17],55:[2,17],70:[2,17],75:[2,17],83:[2,17],88:[2,17],90:[2,17],99:[2,17],101:[2,17],102:[2,17],103:[2,17],107:[2,17],115:[2,17],123:[2,17],125:[2,17],126:[2,17],129:[2,17],130:[2,17],131:[2,17],132:[2,17],133:[2,17],134:[2,17]},{1:[2,18],6:[2,18],25:[2,18],26:[2,18],47:[2,18],52:[2,18],55:[2,18],70:[2,18],75:[2,18],83:[2,18],88:[2,18],90:[2,18],99:[2,18],101:[2,18],102:[2,18],103:[2,18],107:[2,18],115:[2,18],123:[2,18],125:[2,18],126:[2,18],129:[2,18],130:[2,18],131:[2,18],132:[2,18],133:[2,18],134:[2,18]},{1:[2,19],6:[2,19],25:[2,19],26:[2,19],47:[2,19],52:[2,19],55:[2,19],70:[2,19],75:[2,19],83:[2,19],88:[2,19],90:[2,19],99:[2,19],101:[2,19],102:[2,19],103:[2,19],107:[2,19],115:[2,19],123:[2,19],125:[2,19],126:[2,19],129:[2,19],130:[2,19],131:[2,19],132:[2,19],133:[2,19],134:[2,19]},{1:[2,20],6:[2,20],25:[2,20],26:[2,20],47:[2,20],52:[2,20],55:[2,20],70:[2,20],75:[2,20],83:[2,20],88:[2,20],90:[2,20],99:[2,20],101:[2,20],102:[2,20],103:[2,20],107:[2,20],115:[2,20],123:[2,20],125:[2,20],126:[2,20],129:[2,20],130:[2,20],131:[2,20],132:[2,20],133:[2,20],134:[2,20]},{1:[2,21],6:[2,21],25:[2,21],26:[2,21],47:[2,21],52:[2,21],55:[2,21],70:[2,21],75:[2,21],83:[2,21],88:[2,21],90:[2,21],99:[2,21],101:[2,21],102:[2,21],103:[2,21],107:[2,21],115:[2,21],123:[2,21],125:[2,21],126:[2,21],129:[2,21],130:[2,21],131:[2,21],132:[2,21],133:[2,21],134:[2,21]},{1:[2,22],6:[2,22],25:[2,22],26:[2,22],47:[2,22],52:[2,22],55:[2,22],70:[2,22],75:[2,22],83:[2,22],88:[2,22],90:[2,22],99:[2,22],101:[2,22],102:[2,22],103:[2,22],107:[2,22],115:[2,22],123:[2,22],125:[2,22],126:[2,22],129:[2,22],130:[2,22],131:[2,22],132:[2,22],133:[2,22],134:[2,22]},{1:[2,23],6:[2,23],25:[2,23],26:[2,23],47:[2,23],52:[2,23],55:[2,23],70:[2,23],75:[2,23],83:[2,23],88:[2,23],90:[2,23],99:[2,23],101:[2,23],102:[2,23],103:[2,23],107:[2,23],115:[2,23],123:[2,23],125:[2,23],126:[2,23],129:[2,23],130:[2,23],131:[2,23],132:[2,23],133:[2,23],134:[2,23]},{1:[2,9],6:[2,9],26:[2,9],99:[2,9],101:[2,9],103:[2,9],107:[2,9],123:[2,9]},{1:[2,10],6:[2,10],26:[2,10],99:[2,10],101:[2,10],103:[2,10],107:[2,10],123:[2,10]},{1:[2,11],6:[2,11],26:[2,11],99:[2,11],101:[2,11],103:[2,11],107:[2,11],123:[2,11]},{1:[2,71],6:[2,71],25:[2,71],26:[2,71],38:[1,101],47:[2,71],52:[2,71],55:[2,71],64:[2,71],65:[2,71],66:[2,71],68:[2,71],70:[2,71],71:[2,71],75:[2,71],81:[2,71],82:[2,71],83:[2,71],88:[2,71],90:[2,71],99:[2,71],101:[2,71],102:[2,71],103:[2,71],107:[2,71],115:[2,71],123:[2,71],125:[2,71],126:[2,71],129:[2,71],130:[2,71],131:[2,71],132:[2,71],133:[2,71],134:[2,71]},{1:[2,72],6:[2,72],25:[2,72],26:[2,72],47:[2,72],52:[2,72],55:[2,72],64:[2,72],65:[2,72],66:[2,72],68:[2,72],70:[2,72],71:[2,72],75:[2,72],81:[2,72],82:[2,72],83:[2,72],88:[2,72],90:[2,72],99:[2,72],101:[2,72],102:[2,72],103:[2,72],107:[2,72],115:[2,72],123:[2,72],125:[2,72],126:[2,72],129:[2,72],130:[2,72],131:[2,72],132:[2,72],133:[2,72],134:[2,72]},{1:[2,73],6:[2,73],25:[2,73],26:[2,73],47:[2,73],52:[2,73],55:[2,73],64:[2,73],65:[2,73],66:[2,73],68:[2,73],70:[2,73],71:[2,73],75:[2,73],81:[2,73],82:[2,73],83:[2,73],88:[2,73],90:[2,73],99:[2,73],101:[2,73],102:[2,73],103:[2,73],107:[2,73],115:[2,73],123:[2,73],125:[2,73],126:[2,73],129:[2,73],130:[2,73],131:[2,73],132:[2,73],133:[2,73],134:[2,73]},{1:[2,74],6:[2,74],25:[2,74],26:[2,74],47:[2,74],52:[2,74],55:[2,74],64:[2,74],65:[2,74],66:[2,74],68:[2,74],70:[2,74],71:[2,74],75:[2,74],81:[2,74],82:[2,74],83:[2,74],88:[2,74],90:[2,74],99:[2,74],101:[2,74],102:[2,74],103:[2,74],107:[2,74],115:[2,74],123:[2,74],125:[2,74],126:[2,74],129:[2,74],130:[2,74],131:[2,74],132:[2,74],133:[2,74],134:[2,74]},{1:[2,75],6:[2,75],25:[2,75],26:[2,75],47:[2,75],52:[2,75],55:[2,75],64:[2,75],65:[2,75],66:[2,75],68:[2,75],70:[2,75],71:[2,75],75:[2,75],81:[2,75],82:[2,75],83:[2,75],88:[2,75],90:[2,75],99:[2,75],101:[2,75],102:[2,75],103:[2,75],107:[2,75],115:[2,75],123:[2,75],125:[2,75],126:[2,75],129:[2,75],130:[2,75],131:[2,75],132:[2,75],133:[2,75],134:[2,75]},{1:[2,101],6:[2,101],25:[2,101],26:[2,101],47:[2,101],52:[2,101],55:[2,101],64:[2,101],65:[2,101],66:[2,101],68:[2,101],70:[2,101],71:[2,101],75:[2,101],79:102,81:[2,101],82:[1,103],83:[2,101],88:[2,101],90:[2,101],99:[2,101],101:[2,101],102:[2,101],103:[2,101],107:[2,101],115:[2,101],123:[2,101],125:[2,101],126:[2,101],129:[2,101],130:[2,101],131:[2,101],132:[2,101],133:[2,101],134:[2,101]},{27:107,28:[1,71],42:108,46:104,47:[2,53],52:[2,53],53:105,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{5:113,25:[1,5]},{8:114,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:116,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:117,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:118,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:122,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{1:[2,68],6:[2,68],25:[2,68],26:[2,68],38:[2,68],47:[2,68],52:[2,68],55:[2,68],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,68],71:[2,68],75:[2,68],77:[1,126],81:[2,68],82:[2,68],83:[2,68],88:[2,68],90:[2,68],99:[2,68],101:[2,68],102:[2,68],103:[2,68],107:[2,68],115:[2,68],123:[2,68],125:[2,68],126:[2,68],127:[1,123],128:[1,124],129:[2,68],130:[2,68],131:[2,68],132:[2,68],133:[2,68],134:[2,68],135:[1,125]},{1:[2,175],6:[2,175],25:[2,175],26:[2,175],47:[2,175],52:[2,175],55:[2,175],70:[2,175],75:[2,175],83:[2,175],88:[2,175],90:[2,175],99:[2,175],101:[2,175],102:[2,175],103:[2,175],107:[2,175],115:[2,175],118:[1,127],123:[2,175],125:[2,175],126:[2,175],129:[2,175],130:[2,175],131:[2,175],132:[2,175],133:[2,175],134:[2,175]},{5:128,25:[1,5]},{5:129,25:[1,5]},{1:[2,143],6:[2,143],25:[2,143],26:[2,143],47:[2,143],52:[2,143],55:[2,143],70:[2,143],75:[2,143],83:[2,143],88:[2,143],90:[2,143],99:[2,143],101:[2,143],102:[2,143],103:[2,143],107:[2,143],115:[2,143],123:[2,143],125:[2,143],126:[2,143],129:[2,143],130:[2,143],131:[2,143],132:[2,143],133:[2,143],134:[2,143]},{5:130,25:[1,5]},{8:131,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,132],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,91],5:133,6:[2,91],13:119,14:120,25:[1,5],26:[2,91],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,47:[2,91],52:[2,91],55:[2,91],56:47,57:48,59:135,61:25,62:26,63:27,70:[2,91],73:[1,68],75:[2,91],77:[1,134],80:[1,28],83:[2,91],85:[1,56],86:[1,57],87:[1,55],88:[2,91],90:[2,91],98:[1,54],99:[2,91],101:[2,91],102:[2,91],103:[2,91],107:[2,91],115:[2,91],123:[2,91],125:[2,91],126:[2,91],129:[2,91],130:[2,91],131:[2,91],132:[2,91],133:[2,91],134:[2,91]},{8:136,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,45],6:[2,45],8:137,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,45],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,45],100:39,101:[2,45],103:[2,45],104:40,105:[1,65],106:41,107:[2,45],108:67,116:[1,42],121:37,122:[1,62],123:[2,45],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,46],6:[2,46],25:[2,46],26:[2,46],52:[2,46],75:[2,46],99:[2,46],101:[2,46],103:[2,46],107:[2,46],123:[2,46]},{1:[2,69],6:[2,69],25:[2,69],26:[2,69],38:[2,69],47:[2,69],52:[2,69],55:[2,69],64:[2,69],65:[2,69],66:[2,69],68:[2,69],70:[2,69],71:[2,69],75:[2,69],81:[2,69],82:[2,69],83:[2,69],88:[2,69],90:[2,69],99:[2,69],101:[2,69],102:[2,69],103:[2,69],107:[2,69],115:[2,69],123:[2,69],125:[2,69],126:[2,69],129:[2,69],130:[2,69],131:[2,69],132:[2,69],133:[2,69],134:[2,69]},{1:[2,70],6:[2,70],25:[2,70],26:[2,70],38:[2,70],47:[2,70],52:[2,70],55:[2,70],64:[2,70],65:[2,70],66:[2,70],68:[2,70],70:[2,70],71:[2,70],75:[2,70],81:[2,70],82:[2,70],83:[2,70],88:[2,70],90:[2,70],99:[2,70],101:[2,70],102:[2,70],103:[2,70],107:[2,70],115:[2,70],123:[2,70],125:[2,70],126:[2,70],129:[2,70],130:[2,70],131:[2,70],132:[2,70],133:[2,70],134:[2,70]},{1:[2,29],6:[2,29],25:[2,29],26:[2,29],47:[2,29],52:[2,29],55:[2,29],64:[2,29],65:[2,29],66:[2,29],68:[2,29],70:[2,29],71:[2,29],75:[2,29],81:[2,29],82:[2,29],83:[2,29],88:[2,29],90:[2,29],99:[2,29],101:[2,29],102:[2,29],103:[2,29],107:[2,29],115:[2,29],123:[2,29],125:[2,29],126:[2,29],129:[2,29],130:[2,29],131:[2,29],132:[2,29],133:[2,29],134:[2,29]},{1:[2,30],6:[2,30],25:[2,30],26:[2,30],47:[2,30],52:[2,30],55:[2,30],64:[2,30],65:[2,30],66:[2,30],68:[2,30],70:[2,30],71:[2,30],75:[2,30],81:[2,30],82:[2,30],83:[2,30],88:[2,30],90:[2,30],99:[2,30],101:[2,30],102:[2,30],103:[2,30],107:[2,30],115:[2,30],123:[2,30],125:[2,30],126:[2,30],129:[2,30],130:[2,30],131:[2,30],132:[2,30],133:[2,30],134:[2,30]},{1:[2,31],6:[2,31],25:[2,31],26:[2,31],47:[2,31],52:[2,31],55:[2,31],64:[2,31],65:[2,31],66:[2,31],68:[2,31],70:[2,31],71:[2,31],75:[2,31],81:[2,31],82:[2,31],83:[2,31],88:[2,31],90:[2,31],99:[2,31],101:[2,31],102:[2,31],103:[2,31],107:[2,31],115:[2,31],123:[2,31],125:[2,31],126:[2,31],129:[2,31],130:[2,31],131:[2,31],132:[2,31],133:[2,31],134:[2,31]},{1:[2,32],6:[2,32],25:[2,32],26:[2,32],47:[2,32],52:[2,32],55:[2,32],64:[2,32],65:[2,32],66:[2,32],68:[2,32],70:[2,32],71:[2,32],75:[2,32],81:[2,32],82:[2,32],83:[2,32],88:[2,32],90:[2,32],99:[2,32],101:[2,32],102:[2,32],103:[2,32],107:[2,32],115:[2,32],123:[2,32],125:[2,32],126:[2,32],129:[2,32],130:[2,32],131:[2,32],132:[2,32],133:[2,32],134:[2,32]},{1:[2,33],6:[2,33],25:[2,33],26:[2,33],47:[2,33],52:[2,33],55:[2,33],64:[2,33],65:[2,33],66:[2,33],68:[2,33],70:[2,33],71:[2,33],75:[2,33],81:[2,33],82:[2,33],83:[2,33],88:[2,33],90:[2,33],99:[2,33],101:[2,33],102:[2,33],103:[2,33],107:[2,33],115:[2,33],123:[2,33],125:[2,33],126:[2,33],129:[2,33],130:[2,33],131:[2,33],132:[2,33],133:[2,33],134:[2,33]},{4:138,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,139],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:140,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,107],6:[2,107],25:[2,107],26:[2,107],47:[2,107],52:[2,107],55:[2,107],64:[2,107],65:[2,107],66:[2,107],68:[2,107],70:[2,107],71:[2,107],75:[2,107],81:[2,107],82:[2,107],83:[2,107],88:[2,107],90:[2,107],99:[2,107],101:[2,107],102:[2,107],103:[2,107],107:[2,107],115:[2,107],123:[2,107],125:[2,107],126:[2,107],129:[2,107],130:[2,107],131:[2,107],132:[2,107],133:[2,107],134:[2,107]},{1:[2,108],6:[2,108],25:[2,108],26:[2,108],27:146,28:[1,71],47:[2,108],52:[2,108],55:[2,108],64:[2,108],65:[2,108],66:[2,108],68:[2,108],70:[2,108],71:[2,108],75:[2,108],81:[2,108],82:[2,108],83:[2,108],88:[2,108],90:[2,108],99:[2,108],101:[2,108],102:[2,108],103:[2,108],107:[2,108],115:[2,108],123:[2,108],125:[2,108],126:[2,108],129:[2,108],130:[2,108],131:[2,108],132:[2,108],133:[2,108],134:[2,108]},{25:[2,49]},{25:[2,50]},{1:[2,64],6:[2,64],25:[2,64],26:[2,64],38:[2,64],47:[2,64],52:[2,64],55:[2,64],64:[2,64],65:[2,64],66:[2,64],68:[2,64],70:[2,64],71:[2,64],75:[2,64],77:[2,64],81:[2,64],82:[2,64],83:[2,64],88:[2,64],90:[2,64],99:[2,64],101:[2,64],102:[2,64],103:[2,64],107:[2,64],115:[2,64],123:[2,64],125:[2,64],126:[2,64],127:[2,64],128:[2,64],129:[2,64],130:[2,64],131:[2,64],132:[2,64],133:[2,64],134:[2,64],135:[2,64]},{1:[2,67],6:[2,67],25:[2,67],26:[2,67],38:[2,67],47:[2,67],52:[2,67],55:[2,67],64:[2,67],65:[2,67],66:[2,67],68:[2,67],70:[2,67],71:[2,67],75:[2,67],77:[2,67],81:[2,67],82:[2,67],83:[2,67],88:[2,67],90:[2,67],99:[2,67],101:[2,67],102:[2,67],103:[2,67],107:[2,67],115:[2,67],123:[2,67],125:[2,67],126:[2,67],127:[2,67],128:[2,67],129:[2,67],130:[2,67],131:[2,67],132:[2,67],133:[2,67],134:[2,67],135:[2,67]},{8:147,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:148,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:149,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:150,8:151,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{27:156,28:[1,71],56:157,57:158,62:152,73:[1,68],87:[1,55],110:153,111:[1,154],112:155},{109:159,113:[1,160],114:[1,161]},{6:[2,86],11:165,25:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:162,75:[2,86],86:[1,111]},{1:[2,27],6:[2,27],25:[2,27],26:[2,27],41:[2,27],47:[2,27],52:[2,27],55:[2,27],64:[2,27],65:[2,27],66:[2,27],68:[2,27],70:[2,27],71:[2,27],75:[2,27],81:[2,27],82:[2,27],83:[2,27],88:[2,27],90:[2,27],99:[2,27],101:[2,27],102:[2,27],103:[2,27],107:[2,27],115:[2,27],123:[2,27],125:[2,27],126:[2,27],129:[2,27],130:[2,27],131:[2,27],132:[2,27],133:[2,27],134:[2,27]},{1:[2,28],6:[2,28],25:[2,28],26:[2,28],41:[2,28],47:[2,28],52:[2,28],55:[2,28],64:[2,28],65:[2,28],66:[2,28],68:[2,28],70:[2,28],71:[2,28],75:[2,28],81:[2,28],82:[2,28],83:[2,28],88:[2,28],90:[2,28],99:[2,28],101:[2,28],102:[2,28],103:[2,28],107:[2,28],115:[2,28],123:[2,28],125:[2,28],126:[2,28],129:[2,28],130:[2,28],131:[2,28],132:[2,28],133:[2,28],134:[2,28]},{1:[2,26],6:[2,26],25:[2,26],26:[2,26],38:[2,26],41:[2,26],47:[2,26],52:[2,26],55:[2,26],64:[2,26],65:[2,26],66:[2,26],68:[2,26],70:[2,26],71:[2,26],75:[2,26],77:[2,26],81:[2,26],82:[2,26],83:[2,26],88:[2,26],90:[2,26],99:[2,26],101:[2,26],102:[2,26],103:[2,26],107:[2,26],113:[2,26],114:[2,26],115:[2,26],123:[2,26],125:[2,26],126:[2,26],127:[2,26],128:[2,26],129:[2,26],130:[2,26],131:[2,26],132:[2,26],133:[2,26],134:[2,26],135:[2,26]},{1:[2,6],6:[2,6],7:169,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,6],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,6],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,3]},{1:[2,24],6:[2,24],25:[2,24],26:[2,24],47:[2,24],52:[2,24],55:[2,24],70:[2,24],75:[2,24],83:[2,24],88:[2,24],90:[2,24],95:[2,24],96:[2,24],99:[2,24],101:[2,24],102:[2,24],103:[2,24],107:[2,24],115:[2,24],118:[2,24],120:[2,24],123:[2,24],125:[2,24],126:[2,24],129:[2,24],130:[2,24],131:[2,24],132:[2,24],133:[2,24],134:[2,24]},{6:[1,72],26:[1,170]},{1:[2,186],6:[2,186],25:[2,186],26:[2,186],47:[2,186],52:[2,186],55:[2,186],70:[2,186],75:[2,186],83:[2,186],88:[2,186],90:[2,186],99:[2,186],101:[2,186],102:[2,186],103:[2,186],107:[2,186],115:[2,186],123:[2,186],125:[2,186],126:[2,186],129:[2,186],130:[2,186],131:[2,186],132:[2,186],133:[2,186],134:[2,186]},{8:171,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:172,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:173,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:174,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:175,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:176,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:177,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:178,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,142],6:[2,142],25:[2,142],26:[2,142],47:[2,142],52:[2,142],55:[2,142],70:[2,142],75:[2,142],83:[2,142],88:[2,142],90:[2,142],99:[2,142],101:[2,142],102:[2,142],103:[2,142],107:[2,142],115:[2,142],123:[2,142],125:[2,142],126:[2,142],129:[2,142],130:[2,142],131:[2,142],132:[2,142],133:[2,142],134:[2,142]},{1:[2,147],6:[2,147],25:[2,147],26:[2,147],47:[2,147],52:[2,147],55:[2,147],70:[2,147],75:[2,147],83:[2,147],88:[2,147],90:[2,147],99:[2,147],101:[2,147],102:[2,147],103:[2,147],107:[2,147],115:[2,147],123:[2,147],125:[2,147],126:[2,147],129:[2,147],130:[2,147],131:[2,147],132:[2,147],133:[2,147],134:[2,147]},{8:179,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,141],6:[2,141],25:[2,141],26:[2,141],47:[2,141],52:[2,141],55:[2,141],70:[2,141],75:[2,141],83:[2,141],88:[2,141],90:[2,141],99:[2,141],101:[2,141],102:[2,141],103:[2,141],107:[2,141],115:[2,141],123:[2,141],125:[2,141],126:[2,141],129:[2,141],130:[2,141],131:[2,141],132:[2,141],133:[2,141],134:[2,141]},{1:[2,146],6:[2,146],25:[2,146],26:[2,146],47:[2,146],52:[2,146],55:[2,146],70:[2,146],75:[2,146],83:[2,146],88:[2,146],90:[2,146],99:[2,146],101:[2,146],102:[2,146],103:[2,146],107:[2,146],115:[2,146],123:[2,146],125:[2,146],126:[2,146],129:[2,146],130:[2,146],131:[2,146],132:[2,146],133:[2,146],134:[2,146]},{79:180,82:[1,103]},{1:[2,65],6:[2,65],25:[2,65],26:[2,65],38:[2,65],47:[2,65],52:[2,65],55:[2,65],64:[2,65],65:[2,65],66:[2,65],68:[2,65],70:[2,65],71:[2,65],75:[2,65],77:[2,65],81:[2,65],82:[2,65],83:[2,65],88:[2,65],90:[2,65],99:[2,65],101:[2,65],102:[2,65],103:[2,65],107:[2,65],115:[2,65],123:[2,65],125:[2,65],126:[2,65],127:[2,65],128:[2,65],129:[2,65],130:[2,65],131:[2,65],132:[2,65],133:[2,65],134:[2,65],135:[2,65]},{82:[2,104]},{27:181,28:[1,71]},{27:182,28:[1,71]},{1:[2,79],6:[2,79],25:[2,79],26:[2,79],27:183,28:[1,71],38:[2,79],47:[2,79],52:[2,79],55:[2,79],64:[2,79],65:[2,79],66:[2,79],68:[2,79],70:[2,79],71:[2,79],75:[2,79],77:[2,79],81:[2,79],82:[2,79],83:[2,79],88:[2,79],90:[2,79],99:[2,79],101:[2,79],102:[2,79],103:[2,79],107:[2,79],115:[2,79],123:[2,79],125:[2,79],126:[2,79],127:[2,79],128:[2,79],129:[2,79],130:[2,79],131:[2,79],132:[2,79],133:[2,79],134:[2,79],135:[2,79]},{1:[2,80],6:[2,80],25:[2,80],26:[2,80],38:[2,80],47:[2,80],52:[2,80],55:[2,80],64:[2,80],65:[2,80],66:[2,80],68:[2,80],70:[2,80],71:[2,80],75:[2,80],77:[2,80],81:[2,80],82:[2,80],83:[2,80],88:[2,80],90:[2,80],99:[2,80],101:[2,80],102:[2,80],103:[2,80],107:[2,80],115:[2,80],123:[2,80],125:[2,80],126:[2,80],127:[2,80],128:[2,80],129:[2,80],130:[2,80],131:[2,80],132:[2,80],133:[2,80],134:[2,80],135:[2,80]},{8:185,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],55:[1,189],56:47,57:48,59:36,61:25,62:26,63:27,69:184,72:186,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],89:187,90:[1,188],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{67:190,68:[1,97],71:[1,98]},{79:191,82:[1,103]},{1:[2,66],6:[2,66],25:[2,66],26:[2,66],38:[2,66],47:[2,66],52:[2,66],55:[2,66],64:[2,66],65:[2,66],66:[2,66],68:[2,66],70:[2,66],71:[2,66],75:[2,66],77:[2,66],81:[2,66],82:[2,66],83:[2,66],88:[2,66],90:[2,66],99:[2,66],101:[2,66],102:[2,66],103:[2,66],107:[2,66],115:[2,66],123:[2,66],125:[2,66],126:[2,66],127:[2,66],128:[2,66],129:[2,66],130:[2,66],131:[2,66],132:[2,66],133:[2,66],134:[2,66],135:[2,66]},{6:[1,193],8:192,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,194],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,102],6:[2,102],25:[2,102],26:[2,102],47:[2,102],52:[2,102],55:[2,102],64:[2,102],65:[2,102],66:[2,102],68:[2,102],70:[2,102],71:[2,102],75:[2,102],81:[2,102],82:[2,102],83:[2,102],88:[2,102],90:[2,102],99:[2,102],101:[2,102],102:[2,102],103:[2,102],107:[2,102],115:[2,102],123:[2,102],125:[2,102],126:[2,102],129:[2,102],130:[2,102],131:[2,102],132:[2,102],133:[2,102],134:[2,102]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[1,195],84:196,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{47:[1,198],52:[1,199]},{47:[2,54],52:[2,54]},{38:[1,201],47:[2,56],52:[2,56],55:[1,200]},{38:[2,59],47:[2,59],52:[2,59],55:[2,59]},{38:[2,60],47:[2,60],52:[2,60],55:[2,60]},{38:[2,61],47:[2,61],52:[2,61],55:[2,61]},{38:[2,62],47:[2,62],52:[2,62],55:[2,62]},{27:146,28:[1,71]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,48],6:[2,48],25:[2,48],26:[2,48],47:[2,48],52:[2,48],55:[2,48],70:[2,48],75:[2,48],83:[2,48],88:[2,48],90:[2,48],99:[2,48],101:[2,48],102:[2,48],103:[2,48],107:[2,48],115:[2,48],123:[2,48],125:[2,48],126:[2,48],129:[2,48],130:[2,48],131:[2,48],132:[2,48],133:[2,48],134:[2,48]},{1:[2,179],6:[2,179],25:[2,179],26:[2,179],47:[2,179],52:[2,179],55:[2,179],70:[2,179],75:[2,179],83:[2,179],88:[2,179],90:[2,179],99:[2,179],100:85,101:[2,179],102:[2,179],103:[2,179],106:86,107:[2,179],108:67,115:[2,179],123:[2,179],125:[2,179],126:[2,179],129:[1,76],130:[2,179],131:[2,179],132:[2,179],133:[2,179],134:[2,179]},{100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,180],6:[2,180],25:[2,180],26:[2,180],47:[2,180],52:[2,180],55:[2,180],70:[2,180],75:[2,180],83:[2,180],88:[2,180],90:[2,180],99:[2,180],100:85,101:[2,180],102:[2,180],103:[2,180],106:86,107:[2,180],108:67,115:[2,180],123:[2,180],125:[2,180],126:[2,180],129:[1,76],130:[2,180],131:[2,180],132:[2,180],133:[2,180],134:[2,180]},{1:[2,181],6:[2,181],25:[2,181],26:[2,181],47:[2,181],52:[2,181],55:[2,181],70:[2,181],75:[2,181],83:[2,181],88:[2,181],90:[2,181],99:[2,181],100:85,101:[2,181],102:[2,181],103:[2,181],106:86,107:[2,181],108:67,115:[2,181],123:[2,181],125:[2,181],126:[2,181],129:[1,76],130:[2,181],131:[2,181],132:[2,181],133:[2,181],134:[2,181]},{1:[2,182],6:[2,182],25:[2,182],26:[2,182],47:[2,182],52:[2,182],55:[2,182],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,182],71:[2,68],75:[2,182],81:[2,68],82:[2,68],83:[2,182],88:[2,182],90:[2,182],99:[2,182],101:[2,182],102:[2,182],103:[2,182],107:[2,182],115:[2,182],123:[2,182],125:[2,182],126:[2,182],129:[2,182],130:[2,182],131:[2,182],132:[2,182],133:[2,182],134:[2,182]},{60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:90,81:[1,92],82:[2,103]},{60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:99,81:[1,92],82:[2,103]},{64:[2,71],65:[2,71],66:[2,71],68:[2,71],71:[2,71],81:[2,71],82:[2,71]},{1:[2,183],6:[2,183],25:[2,183],26:[2,183],47:[2,183],52:[2,183],55:[2,183],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,183],71:[2,68],75:[2,183],81:[2,68],82:[2,68],83:[2,183],88:[2,183],90:[2,183],99:[2,183],101:[2,183],102:[2,183],103:[2,183],107:[2,183],115:[2,183],123:[2,183],125:[2,183],126:[2,183],129:[2,183],130:[2,183],131:[2,183],132:[2,183],133:[2,183],134:[2,183]},{1:[2,184],6:[2,184],25:[2,184],26:[2,184],47:[2,184],52:[2,184],55:[2,184],70:[2,184],75:[2,184],83:[2,184],88:[2,184],90:[2,184],99:[2,184],101:[2,184],102:[2,184],103:[2,184],107:[2,184],115:[2,184],123:[2,184],125:[2,184],126:[2,184],129:[2,184],130:[2,184],131:[2,184],132:[2,184],133:[2,184],134:[2,184]},{1:[2,185],6:[2,185],25:[2,185],26:[2,185],47:[2,185],52:[2,185],55:[2,185],70:[2,185],75:[2,185],83:[2,185],88:[2,185],90:[2,185],99:[2,185],101:[2,185],102:[2,185],103:[2,185],107:[2,185],115:[2,185],123:[2,185],125:[2,185],126:[2,185],129:[2,185],130:[2,185],131:[2,185],132:[2,185],133:[2,185],134:[2,185]},{8:202,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,203],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:204,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:205,25:[1,5],122:[1,206]},{1:[2,128],6:[2,128],25:[2,128],26:[2,128],47:[2,128],52:[2,128],55:[2,128],70:[2,128],75:[2,128],83:[2,128],88:[2,128],90:[2,128],94:207,95:[1,208],96:[1,209],99:[2,128],101:[2,128],102:[2,128],103:[2,128],107:[2,128],115:[2,128],123:[2,128],125:[2,128],126:[2,128],129:[2,128],130:[2,128],131:[2,128],132:[2,128],133:[2,128],134:[2,128]},{1:[2,140],6:[2,140],25:[2,140],26:[2,140],47:[2,140],52:[2,140],55:[2,140],70:[2,140],75:[2,140],83:[2,140],88:[2,140],90:[2,140],99:[2,140],101:[2,140],102:[2,140],103:[2,140],107:[2,140],115:[2,140],123:[2,140],125:[2,140],126:[2,140],129:[2,140],130:[2,140],131:[2,140],132:[2,140],133:[2,140],134:[2,140]},{1:[2,148],6:[2,148],25:[2,148],26:[2,148],47:[2,148],52:[2,148],55:[2,148],70:[2,148],75:[2,148],83:[2,148],88:[2,148],90:[2,148],99:[2,148],101:[2,148],102:[2,148],103:[2,148],107:[2,148],115:[2,148],123:[2,148],125:[2,148],126:[2,148],129:[2,148],130:[2,148],131:[2,148],132:[2,148],133:[2,148],134:[2,148]},{25:[1,210],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{117:211,119:212,120:[1,213]},{1:[2,92],6:[2,92],25:[2,92],26:[2,92],47:[2,92],52:[2,92],55:[2,92],70:[2,92],75:[2,92],83:[2,92],88:[2,92],90:[2,92],99:[2,92],101:[2,92],102:[2,92],103:[2,92],107:[2,92],115:[2,92],123:[2,92],125:[2,92],126:[2,92],129:[2,92],130:[2,92],131:[2,92],132:[2,92],133:[2,92],134:[2,92]},{8:214,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,95],5:215,6:[2,95],25:[1,5],26:[2,95],47:[2,95],52:[2,95],55:[2,95],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,95],71:[2,68],75:[2,95],77:[1,216],81:[2,68],82:[2,68],83:[2,95],88:[2,95],90:[2,95],99:[2,95],101:[2,95],102:[2,95],103:[2,95],107:[2,95],115:[2,95],123:[2,95],125:[2,95],126:[2,95],129:[2,95],130:[2,95],131:[2,95],132:[2,95],133:[2,95],134:[2,95]},{1:[2,133],6:[2,133],25:[2,133],26:[2,133],47:[2,133],52:[2,133],55:[2,133],70:[2,133],75:[2,133],83:[2,133],88:[2,133],90:[2,133],99:[2,133],100:85,101:[2,133],102:[2,133],103:[2,133],106:86,107:[2,133],108:67,115:[2,133],123:[2,133],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,44],6:[2,44],26:[2,44],99:[2,44],100:85,101:[2,44],103:[2,44],106:86,107:[2,44],108:67,123:[2,44],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,72],99:[1,217]},{4:218,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,124],25:[2,124],52:[2,124],55:[1,220],88:[2,124],89:219,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,110],6:[2,110],25:[2,110],26:[2,110],38:[2,110],47:[2,110],52:[2,110],55:[2,110],64:[2,110],65:[2,110],66:[2,110],68:[2,110],70:[2,110],71:[2,110],75:[2,110],81:[2,110],82:[2,110],83:[2,110],88:[2,110],90:[2,110],99:[2,110],101:[2,110],102:[2,110],103:[2,110],107:[2,110],113:[2,110],114:[2,110],115:[2,110],123:[2,110],125:[2,110],126:[2,110],129:[2,110],130:[2,110],131:[2,110],132:[2,110],133:[2,110],134:[2,110]},{6:[2,51],25:[2,51],51:221,52:[1,222],88:[2,51]},{6:[2,119],25:[2,119],26:[2,119],52:[2,119],83:[2,119],88:[2,119]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:223,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,125],25:[2,125],26:[2,125],52:[2,125],83:[2,125],88:[2,125]},{1:[2,109],6:[2,109],25:[2,109],26:[2,109],38:[2,109],41:[2,109],47:[2,109],52:[2,109],55:[2,109],64:[2,109],65:[2,109],66:[2,109],68:[2,109],70:[2,109],71:[2,109],75:[2,109],77:[2,109],81:[2,109],82:[2,109],83:[2,109],88:[2,109],90:[2,109],99:[2,109],101:[2,109],102:[2,109],103:[2,109],107:[2,109],115:[2,109],123:[2,109],125:[2,109],126:[2,109],127:[2,109],128:[2,109],129:[2,109],130:[2,109],131:[2,109],132:[2,109],133:[2,109],134:[2,109],135:[2,109]},{5:224,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,136],6:[2,136],25:[2,136],26:[2,136],47:[2,136],52:[2,136],55:[2,136],70:[2,136],75:[2,136],83:[2,136],88:[2,136],90:[2,136],99:[2,136],100:85,101:[1,63],102:[1,225],103:[1,64],106:86,107:[1,66],108:67,115:[2,136],123:[2,136],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,138],6:[2,138],25:[2,138],26:[2,138],47:[2,138],52:[2,138],55:[2,138],70:[2,138],75:[2,138],83:[2,138],88:[2,138],90:[2,138],99:[2,138],100:85,101:[1,63],102:[1,226],103:[1,64],106:86,107:[1,66],108:67,115:[2,138],123:[2,138],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,144],6:[2,144],25:[2,144],26:[2,144],47:[2,144],52:[2,144],55:[2,144],70:[2,144],75:[2,144],83:[2,144],88:[2,144],90:[2,144],99:[2,144],101:[2,144],102:[2,144],103:[2,144],107:[2,144],115:[2,144],123:[2,144],125:[2,144],126:[2,144],129:[2,144],130:[2,144],131:[2,144],132:[2,144],133:[2,144],134:[2,144]},{1:[2,145],6:[2,145],25:[2,145],26:[2,145],47:[2,145],52:[2,145],55:[2,145],70:[2,145],75:[2,145],83:[2,145],88:[2,145],90:[2,145],99:[2,145],100:85,101:[1,63],102:[2,145],103:[1,64],106:86,107:[1,66],108:67,115:[2,145],123:[2,145],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,149],6:[2,149],25:[2,149],26:[2,149],47:[2,149],52:[2,149],55:[2,149],70:[2,149],75:[2,149],83:[2,149],88:[2,149],90:[2,149],99:[2,149],101:[2,149],102:[2,149],103:[2,149],107:[2,149],115:[2,149],123:[2,149],125:[2,149],126:[2,149],129:[2,149],130:[2,149],131:[2,149],132:[2,149],133:[2,149],134:[2,149]},{113:[2,151],114:[2,151]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],110:227,112:155},{52:[1,228],113:[2,156],114:[2,156]},{52:[2,153],113:[2,153],114:[2,153]},{52:[2,154],113:[2,154],114:[2,154]},{52:[2,155],113:[2,155],114:[2,155]},{1:[2,150],6:[2,150],25:[2,150],26:[2,150],47:[2,150],52:[2,150],55:[2,150],70:[2,150],75:[2,150],83:[2,150],88:[2,150],90:[2,150],99:[2,150],101:[2,150],102:[2,150],103:[2,150],107:[2,150],115:[2,150],123:[2,150],125:[2,150],126:[2,150],129:[2,150],130:[2,150],131:[2,150],132:[2,150],133:[2,150],134:[2,150]},{8:229,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:230,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],51:231,52:[1,232],75:[2,51]},{6:[2,87],25:[2,87],26:[2,87],52:[2,87],75:[2,87]},{6:[2,37],25:[2,37],26:[2,37],41:[1,233],52:[2,37],75:[2,37]},{6:[2,40],25:[2,40],26:[2,40],52:[2,40],75:[2,40]},{6:[2,41],25:[2,41],26:[2,41],41:[2,41],52:[2,41],75:[2,41]},{6:[2,42],25:[2,42],26:[2,42],41:[2,42],52:[2,42],75:[2,42]},{6:[2,43],25:[2,43],26:[2,43],41:[2,43],52:[2,43],75:[2,43]},{1:[2,5],6:[2,5],26:[2,5],99:[2,5]},{1:[2,25],6:[2,25],25:[2,25],26:[2,25],47:[2,25],52:[2,25],55:[2,25],70:[2,25],75:[2,25],83:[2,25],88:[2,25],90:[2,25],95:[2,25],96:[2,25],99:[2,25],101:[2,25],102:[2,25],103:[2,25],107:[2,25],115:[2,25],118:[2,25],120:[2,25],123:[2,25],125:[2,25],126:[2,25],129:[2,25],130:[2,25],131:[2,25],132:[2,25],133:[2,25],134:[2,25]},{1:[2,187],6:[2,187],25:[2,187],26:[2,187],47:[2,187],52:[2,187],55:[2,187],70:[2,187],75:[2,187],83:[2,187],88:[2,187],90:[2,187],99:[2,187],100:85,101:[2,187],102:[2,187],103:[2,187],106:86,107:[2,187],108:67,115:[2,187],123:[2,187],125:[2,187],126:[2,187],129:[1,76],130:[1,79],131:[2,187],132:[2,187],133:[2,187],134:[2,187]},{1:[2,188],6:[2,188],25:[2,188],26:[2,188],47:[2,188],52:[2,188],55:[2,188],70:[2,188],75:[2,188],83:[2,188],88:[2,188],90:[2,188],99:[2,188],100:85,101:[2,188],102:[2,188],103:[2,188],106:86,107:[2,188],108:67,115:[2,188],123:[2,188],125:[2,188],126:[2,188],129:[1,76],130:[1,79],131:[2,188],132:[2,188],133:[2,188],134:[2,188]},{1:[2,189],6:[2,189],25:[2,189],26:[2,189],47:[2,189],52:[2,189],55:[2,189],70:[2,189],75:[2,189],83:[2,189],88:[2,189],90:[2,189],99:[2,189],100:85,101:[2,189],102:[2,189],103:[2,189],106:86,107:[2,189],108:67,115:[2,189],123:[2,189],125:[2,189],126:[2,189],129:[1,76],130:[2,189],131:[2,189],132:[2,189],133:[2,189],134:[2,189]},{1:[2,190],6:[2,190],25:[2,190],26:[2,190],47:[2,190],52:[2,190],55:[2,190],70:[2,190],75:[2,190],83:[2,190],88:[2,190],90:[2,190],99:[2,190],100:85,101:[2,190],102:[2,190],103:[2,190],106:86,107:[2,190],108:67,115:[2,190],123:[2,190],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[2,190],132:[2,190],133:[2,190],134:[2,190]},{1:[2,191],6:[2,191],25:[2,191],26:[2,191],47:[2,191],52:[2,191],55:[2,191],70:[2,191],75:[2,191],83:[2,191],88:[2,191],90:[2,191],99:[2,191],100:85,101:[2,191],102:[2,191],103:[2,191],106:86,107:[2,191],108:67,115:[2,191],123:[2,191],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,191],133:[2,191],134:[1,83]},{1:[2,192],6:[2,192],25:[2,192],26:[2,192],47:[2,192],52:[2,192],55:[2,192],70:[2,192],75:[2,192],83:[2,192],88:[2,192],90:[2,192],99:[2,192],100:85,101:[2,192],102:[2,192],103:[2,192],106:86,107:[2,192],108:67,115:[2,192],123:[2,192],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[2,192],134:[1,83]},{1:[2,193],6:[2,193],25:[2,193],26:[2,193],47:[2,193],52:[2,193],55:[2,193],70:[2,193],75:[2,193],83:[2,193],88:[2,193],90:[2,193],99:[2,193],100:85,101:[2,193],102:[2,193],103:[2,193],106:86,107:[2,193],108:67,115:[2,193],123:[2,193],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,193],133:[2,193],134:[2,193]},{1:[2,178],6:[2,178],25:[2,178],26:[2,178],47:[2,178],52:[2,178],55:[2,178],70:[2,178],75:[2,178],83:[2,178],88:[2,178],90:[2,178],99:[2,178],100:85,101:[1,63],102:[2,178],103:[1,64],106:86,107:[1,66],108:67,115:[2,178],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,177],6:[2,177],25:[2,177],26:[2,177],47:[2,177],52:[2,177],55:[2,177],70:[2,177],75:[2,177],83:[2,177],88:[2,177],90:[2,177],99:[2,177],100:85,101:[1,63],102:[2,177],103:[1,64],106:86,107:[1,66],108:67,115:[2,177],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,99],6:[2,99],25:[2,99],26:[2,99],47:[2,99],52:[2,99],55:[2,99],64:[2,99],65:[2,99],66:[2,99],68:[2,99],70:[2,99],71:[2,99],75:[2,99],81:[2,99],82:[2,99],83:[2,99],88:[2,99],90:[2,99],99:[2,99],101:[2,99],102:[2,99],103:[2,99],107:[2,99],115:[2,99],123:[2,99],125:[2,99],126:[2,99],129:[2,99],130:[2,99],131:[2,99],132:[2,99],133:[2,99],134:[2,99]},{1:[2,76],6:[2,76],25:[2,76],26:[2,76],38:[2,76],47:[2,76],52:[2,76],55:[2,76],64:[2,76],65:[2,76],66:[2,76],68:[2,76],70:[2,76],71:[2,76],75:[2,76],77:[2,76],81:[2,76],82:[2,76],83:[2,76],88:[2,76],90:[2,76],99:[2,76],101:[2,76],102:[2,76],103:[2,76],107:[2,76],115:[2,76],123:[2,76],125:[2,76],126:[2,76],127:[2,76],128:[2,76],129:[2,76],130:[2,76],131:[2,76],132:[2,76],133:[2,76],134:[2,76],135:[2,76]},{1:[2,77],6:[2,77],25:[2,77],26:[2,77],38:[2,77],47:[2,77],52:[2,77],55:[2,77],64:[2,77],65:[2,77],66:[2,77],68:[2,77],70:[2,77],71:[2,77],75:[2,77],77:[2,77],81:[2,77],82:[2,77],83:[2,77],88:[2,77],90:[2,77],99:[2,77],101:[2,77],102:[2,77],103:[2,77],107:[2,77],115:[2,77],123:[2,77],125:[2,77],126:[2,77],127:[2,77],128:[2,77],129:[2,77],130:[2,77],131:[2,77],132:[2,77],133:[2,77],134:[2,77],135:[2,77]},{1:[2,78],6:[2,78],25:[2,78],26:[2,78],38:[2,78],47:[2,78],52:[2,78],55:[2,78],64:[2,78],65:[2,78],66:[2,78],68:[2,78],70:[2,78],71:[2,78],75:[2,78],77:[2,78],81:[2,78],82:[2,78],83:[2,78],88:[2,78],90:[2,78],99:[2,78],101:[2,78],102:[2,78],103:[2,78],107:[2,78],115:[2,78],123:[2,78],125:[2,78],126:[2,78],127:[2,78],128:[2,78],129:[2,78],130:[2,78],131:[2,78],132:[2,78],133:[2,78],134:[2,78],135:[2,78]},{70:[1,234]},{55:[1,189],70:[2,83],89:235,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{70:[2,84]},{8:236,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,70:[2,118],73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{12:[2,112],28:[2,112],30:[2,112],31:[2,112],33:[2,112],34:[2,112],35:[2,112],36:[2,112],43:[2,112],44:[2,112],45:[2,112],49:[2,112],50:[2,112],70:[2,112],73:[2,112],76:[2,112],80:[2,112],85:[2,112],86:[2,112],87:[2,112],93:[2,112],97:[2,112],98:[2,112],101:[2,112],103:[2,112],105:[2,112],107:[2,112],116:[2,112],122:[2,112],124:[2,112],125:[2,112],126:[2,112],127:[2,112],128:[2,112]},{12:[2,113],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],70:[2,113],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{1:[2,82],6:[2,82],25:[2,82],26:[2,82],38:[2,82],47:[2,82],52:[2,82],55:[2,82],64:[2,82],65:[2,82],66:[2,82],68:[2,82],70:[2,82],71:[2,82],75:[2,82],77:[2,82],81:[2,82],82:[2,82],83:[2,82],88:[2,82],90:[2,82],99:[2,82],101:[2,82],102:[2,82],103:[2,82],107:[2,82],115:[2,82],123:[2,82],125:[2,82],126:[2,82],127:[2,82],128:[2,82],129:[2,82],130:[2,82],131:[2,82],132:[2,82],133:[2,82],134:[2,82],135:[2,82]},{1:[2,100],6:[2,100],25:[2,100],26:[2,100],47:[2,100],52:[2,100],55:[2,100],64:[2,100],65:[2,100],66:[2,100],68:[2,100],70:[2,100],71:[2,100],75:[2,100],81:[2,100],82:[2,100],83:[2,100],88:[2,100],90:[2,100],99:[2,100],101:[2,100],102:[2,100],103:[2,100],107:[2,100],115:[2,100],123:[2,100],125:[2,100],126:[2,100],129:[2,100],130:[2,100],131:[2,100],132:[2,100],133:[2,100],134:[2,100]},{1:[2,34],6:[2,34],25:[2,34],26:[2,34],47:[2,34],52:[2,34],55:[2,34],70:[2,34],75:[2,34],83:[2,34],88:[2,34],90:[2,34],99:[2,34],100:85,101:[2,34],102:[2,34],103:[2,34],106:86,107:[2,34],108:67,115:[2,34],123:[2,34],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:237,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:238,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,105],6:[2,105],25:[2,105],26:[2,105],47:[2,105],52:[2,105],55:[2,105],64:[2,105],65:[2,105],66:[2,105],68:[2,105],70:[2,105],71:[2,105],75:[2,105],81:[2,105],82:[2,105],83:[2,105],88:[2,105],90:[2,105],99:[2,105],101:[2,105],102:[2,105],103:[2,105],107:[2,105],115:[2,105],123:[2,105],125:[2,105],126:[2,105],129:[2,105],130:[2,105],131:[2,105],132:[2,105],133:[2,105],134:[2,105]},{6:[2,51],25:[2,51],51:239,52:[1,222],83:[2,51]},{6:[2,124],25:[2,124],26:[2,124],52:[2,124],55:[1,240],83:[2,124],88:[2,124],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{48:241,49:[1,58],50:[1,59]},{27:107,28:[1,71],42:108,53:242,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{47:[2,57],52:[2,57]},{8:243,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,194],6:[2,194],25:[2,194],26:[2,194],47:[2,194],52:[2,194],55:[2,194],70:[2,194],75:[2,194],83:[2,194],88:[2,194],90:[2,194],99:[2,194],100:85,101:[2,194],102:[2,194],103:[2,194],106:86,107:[2,194],108:67,115:[2,194],123:[2,194],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:244,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,196],6:[2,196],25:[2,196],26:[2,196],47:[2,196],52:[2,196],55:[2,196],70:[2,196],75:[2,196],83:[2,196],88:[2,196],90:[2,196],99:[2,196],100:85,101:[2,196],102:[2,196],103:[2,196],106:86,107:[2,196],108:67,115:[2,196],123:[2,196],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,176],6:[2,176],25:[2,176],26:[2,176],47:[2,176],52:[2,176],55:[2,176],70:[2,176],75:[2,176],83:[2,176],88:[2,176],90:[2,176],99:[2,176],101:[2,176],102:[2,176],103:[2,176],107:[2,176],115:[2,176],123:[2,176],125:[2,176],126:[2,176],129:[2,176],130:[2,176],131:[2,176],132:[2,176],133:[2,176],134:[2,176]},{8:245,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,129],6:[2,129],25:[2,129],26:[2,129],47:[2,129],52:[2,129],55:[2,129],70:[2,129],75:[2,129],83:[2,129],88:[2,129],90:[2,129],95:[1,246],99:[2,129],101:[2,129],102:[2,129],103:[2,129],107:[2,129],115:[2,129],123:[2,129],125:[2,129],126:[2,129],129:[2,129],130:[2,129],131:[2,129],132:[2,129],133:[2,129],134:[2,129]},{5:247,25:[1,5]},{27:248,28:[1,71]},{117:249,119:212,120:[1,213]},{26:[1,250],118:[1,251],119:252,120:[1,213]},{26:[2,169],118:[2,169],120:[2,169]},{8:254,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],92:253,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,93],5:255,6:[2,93],25:[1,5],26:[2,93],47:[2,93],52:[2,93],55:[2,93],70:[2,93],75:[2,93],83:[2,93],88:[2,93],90:[2,93],99:[2,93],100:85,101:[1,63],102:[2,93],103:[1,64],106:86,107:[1,66],108:67,115:[2,93],123:[2,93],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,96],6:[2,96],25:[2,96],26:[2,96],47:[2,96],52:[2,96],55:[2,96],70:[2,96],75:[2,96],83:[2,96],88:[2,96],90:[2,96],99:[2,96],101:[2,96],102:[2,96],103:[2,96],107:[2,96],115:[2,96],123:[2,96],125:[2,96],126:[2,96],129:[2,96],130:[2,96],131:[2,96],132:[2,96],133:[2,96],134:[2,96]},{8:256,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,134],6:[2,134],25:[2,134],26:[2,134],47:[2,134],52:[2,134],55:[2,134],64:[2,134],65:[2,134],66:[2,134],68:[2,134],70:[2,134],71:[2,134],75:[2,134],81:[2,134],82:[2,134],83:[2,134],88:[2,134],90:[2,134],99:[2,134],101:[2,134],102:[2,134],103:[2,134],107:[2,134],115:[2,134],123:[2,134],125:[2,134],126:[2,134],129:[2,134],130:[2,134],131:[2,134],132:[2,134],133:[2,134],134:[2,134]},{6:[1,72],26:[1,257]},{8:258,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,63],12:[2,113],25:[2,63],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],52:[2,63],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],88:[2,63],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{6:[1,260],25:[1,261],88:[1,259]},{6:[2,52],8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[2,52],26:[2,52],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[2,52],85:[1,56],86:[1,57],87:[1,55],88:[2,52],91:262,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],26:[2,51],51:263,52:[1,222]},{1:[2,173],6:[2,173],25:[2,173],26:[2,173],47:[2,173],52:[2,173],55:[2,173],70:[2,173],75:[2,173],83:[2,173],88:[2,173],90:[2,173],99:[2,173],101:[2,173],102:[2,173],103:[2,173],107:[2,173],115:[2,173],118:[2,173],123:[2,173],125:[2,173],126:[2,173],129:[2,173],130:[2,173],131:[2,173],132:[2,173],133:[2,173],134:[2,173]},{8:264,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:265,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{113:[2,152],114:[2,152]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],112:266},{1:[2,158],6:[2,158],25:[2,158],26:[2,158],47:[2,158],52:[2,158],55:[2,158],70:[2,158],75:[2,158],83:[2,158],88:[2,158],90:[2,158],99:[2,158],100:85,101:[2,158],102:[1,267],103:[2,158],106:86,107:[2,158],108:67,115:[1,268],123:[2,158],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,159],6:[2,159],25:[2,159],26:[2,159],47:[2,159],52:[2,159],55:[2,159],70:[2,159],75:[2,159],83:[2,159],88:[2,159],90:[2,159],99:[2,159],100:85,101:[2,159],102:[1,269],103:[2,159],106:86,107:[2,159],108:67,115:[2,159],123:[2,159],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,271],25:[1,272],75:[1,270]},{6:[2,52],11:165,25:[2,52],26:[2,52],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:273,40:164,42:168,44:[1,46],75:[2,52],86:[1,111]},{8:274,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,275],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,81],6:[2,81],25:[2,81],26:[2,81],38:[2,81],47:[2,81],52:[2,81],55:[2,81],64:[2,81],65:[2,81],66:[2,81],68:[2,81],70:[2,81],71:[2,81],75:[2,81],77:[2,81],81:[2,81],82:[2,81],83:[2,81],88:[2,81],90:[2,81],99:[2,81],101:[2,81],102:[2,81],103:[2,81],107:[2,81],115:[2,81],123:[2,81],125:[2,81],126:[2,81],127:[2,81],128:[2,81],129:[2,81],130:[2,81],131:[2,81],132:[2,81],133:[2,81],134:[2,81],135:[2,81]},{8:276,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,70:[2,116],73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,117],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,35],6:[2,35],25:[2,35],26:[2,35],47:[2,35],52:[2,35],55:[2,35],70:[2,35],75:[2,35],83:[2,35],88:[2,35],90:[2,35],99:[2,35],100:85,101:[2,35],102:[2,35],103:[2,35],106:86,107:[2,35],108:67,115:[2,35],123:[2,35],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,277],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],83:[1,278]},{6:[2,63],25:[2,63],26:[2,63],52:[2,63],83:[2,63],88:[2,63]},{5:279,25:[1,5]},{47:[2,55],52:[2,55]},{47:[2,58],52:[2,58],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,280],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:281,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:282,25:[1,5]},{1:[2,130],6:[2,130],25:[2,130],26:[2,130],47:[2,130],52:[2,130],55:[2,130],70:[2,130],75:[2,130],83:[2,130],88:[2,130],90:[2,130],99:[2,130],101:[2,130],102:[2,130],103:[2,130],107:[2,130],115:[2,130],123:[2,130],125:[2,130],126:[2,130],129:[2,130],130:[2,130],131:[2,130],132:[2,130],133:[2,130],134:[2,130]},{5:283,25:[1,5]},{26:[1,284],118:[1,285],119:252,120:[1,213]},{1:[2,167],6:[2,167],25:[2,167],26:[2,167],47:[2,167],52:[2,167],55:[2,167],70:[2,167],75:[2,167],83:[2,167],88:[2,167],90:[2,167],99:[2,167],101:[2,167],102:[2,167],103:[2,167],107:[2,167],115:[2,167],123:[2,167],125:[2,167],126:[2,167],129:[2,167],130:[2,167],131:[2,167],132:[2,167],133:[2,167],134:[2,167]},{5:286,25:[1,5]},{26:[2,170],118:[2,170],120:[2,170]},{5:287,25:[1,5],52:[1,288]},{25:[2,126],52:[2,126],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,94],6:[2,94],25:[2,94],26:[2,94],47:[2,94],52:[2,94],55:[2,94],70:[2,94],75:[2,94],83:[2,94],88:[2,94],90:[2,94],99:[2,94],101:[2,94],102:[2,94],103:[2,94],107:[2,94],115:[2,94],123:[2,94],125:[2,94],126:[2,94],129:[2,94],130:[2,94],131:[2,94],132:[2,94],133:[2,94],134:[2,94]},{1:[2,97],5:289,6:[2,97],25:[1,5],26:[2,97],47:[2,97],52:[2,97],55:[2,97],70:[2,97],75:[2,97],83:[2,97],88:[2,97],90:[2,97],99:[2,97],100:85,101:[1,63],102:[2,97],103:[1,64],106:86,107:[1,66],108:67,115:[2,97],123:[2,97],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{99:[1,290]},{88:[1,291],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,111],6:[2,111],25:[2,111],26:[2,111],38:[2,111],47:[2,111],52:[2,111],55:[2,111],64:[2,111],65:[2,111],66:[2,111],68:[2,111],70:[2,111],71:[2,111],75:[2,111],81:[2,111],82:[2,111],83:[2,111],88:[2,111],90:[2,111],99:[2,111],101:[2,111],102:[2,111],103:[2,111],107:[2,111],113:[2,111],114:[2,111],115:[2,111],123:[2,111],125:[2,111],126:[2,111],129:[2,111],130:[2,111],131:[2,111],132:[2,111],133:[2,111],134:[2,111]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],91:292,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:293,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,120],25:[2,120],26:[2,120],52:[2,120],83:[2,120],88:[2,120]},{6:[1,260],25:[1,261],26:[1,294]},{1:[2,137],6:[2,137],25:[2,137],26:[2,137],47:[2,137],52:[2,137],55:[2,137],70:[2,137],75:[2,137],83:[2,137],88:[2,137],90:[2,137],99:[2,137],100:85,101:[1,63],102:[2,137],103:[1,64],106:86,107:[1,66],108:67,115:[2,137],123:[2,137],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,139],6:[2,139],25:[2,139],26:[2,139],47:[2,139],52:[2,139],55:[2,139],70:[2,139],75:[2,139],83:[2,139],88:[2,139],90:[2,139],99:[2,139],100:85,101:[1,63],102:[2,139],103:[1,64],106:86,107:[1,66],108:67,115:[2,139],123:[2,139],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{113:[2,157],114:[2,157]},{8:295,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:296,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:297,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,85],6:[2,85],25:[2,85],26:[2,85],38:[2,85],47:[2,85],52:[2,85],55:[2,85],64:[2,85],65:[2,85],66:[2,85],68:[2,85],70:[2,85],71:[2,85],75:[2,85],81:[2,85],82:[2,85],83:[2,85],88:[2,85],90:[2,85],99:[2,85],101:[2,85],102:[2,85],103:[2,85],107:[2,85],113:[2,85],114:[2,85],115:[2,85],123:[2,85],125:[2,85],126:[2,85],129:[2,85],130:[2,85],131:[2,85],132:[2,85],133:[2,85],134:[2,85]},{11:165,27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:298,40:164,42:168,44:[1,46],86:[1,111]},{6:[2,86],11:165,25:[2,86],26:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:299,86:[1,111]},{6:[2,88],25:[2,88],26:[2,88],52:[2,88],75:[2,88]},{6:[2,38],25:[2,38],26:[2,38],52:[2,38],75:[2,38],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:300,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,115],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,36],6:[2,36],25:[2,36],26:[2,36],47:[2,36],52:[2,36],55:[2,36],70:[2,36],75:[2,36],83:[2,36],88:[2,36],90:[2,36],99:[2,36],101:[2,36],102:[2,36],103:[2,36],107:[2,36],115:[2,36],123:[2,36],125:[2,36],126:[2,36],129:[2,36],130:[2,36],131:[2,36],132:[2,36],133:[2,36],134:[2,36]},{1:[2,106],6:[2,106],25:[2,106],26:[2,106],47:[2,106],52:[2,106],55:[2,106],64:[2,106],65:[2,106],66:[2,106],68:[2,106],70:[2,106],71:[2,106],75:[2,106],81:[2,106],82:[2,106],83:[2,106],88:[2,106],90:[2,106],99:[2,106],101:[2,106],102:[2,106],103:[2,106],107:[2,106],115:[2,106],123:[2,106],125:[2,106],126:[2,106],129:[2,106],130:[2,106],131:[2,106],132:[2,106],133:[2,106],134:[2,106]},{1:[2,47],6:[2,47],25:[2,47],26:[2,47],47:[2,47],52:[2,47],55:[2,47],70:[2,47],75:[2,47],83:[2,47],88:[2,47],90:[2,47],99:[2,47],101:[2,47],102:[2,47],103:[2,47],107:[2,47],115:[2,47],123:[2,47],125:[2,47],126:[2,47],129:[2,47],130:[2,47],131:[2,47],132:[2,47],133:[2,47],134:[2,47]},{1:[2,195],6:[2,195],25:[2,195],26:[2,195],47:[2,195],52:[2,195],55:[2,195],70:[2,195],75:[2,195],83:[2,195],88:[2,195],90:[2,195],99:[2,195],101:[2,195],102:[2,195],103:[2,195],107:[2,195],115:[2,195],123:[2,195],125:[2,195],126:[2,195],129:[2,195],130:[2,195],131:[2,195],132:[2,195],133:[2,195],134:[2,195]},{1:[2,174],6:[2,174],25:[2,174],26:[2,174],47:[2,174],52:[2,174],55:[2,174],70:[2,174],75:[2,174],83:[2,174],88:[2,174],90:[2,174],99:[2,174],101:[2,174],102:[2,174],103:[2,174],107:[2,174],115:[2,174],118:[2,174],123:[2,174],125:[2,174],126:[2,174],129:[2,174],130:[2,174],131:[2,174],132:[2,174],133:[2,174],134:[2,174]},{1:[2,131],6:[2,131],25:[2,131],26:[2,131],47:[2,131],52:[2,131],55:[2,131],70:[2,131],75:[2,131],83:[2,131],88:[2,131],90:[2,131],99:[2,131],101:[2,131],102:[2,131],103:[2,131],107:[2,131],115:[2,131],123:[2,131],125:[2,131],126:[2,131],129:[2,131],130:[2,131],131:[2,131],132:[2,131],133:[2,131],134:[2,131]},{1:[2,132],6:[2,132],25:[2,132],26:[2,132],47:[2,132],52:[2,132],55:[2,132],70:[2,132],75:[2,132],83:[2,132],88:[2,132],90:[2,132],95:[2,132],99:[2,132],101:[2,132],102:[2,132],103:[2,132],107:[2,132],115:[2,132],123:[2,132],125:[2,132],126:[2,132],129:[2,132],130:[2,132],131:[2,132],132:[2,132],133:[2,132],134:[2,132]},{1:[2,165],6:[2,165],25:[2,165],26:[2,165],47:[2,165],52:[2,165],55:[2,165],70:[2,165],75:[2,165],83:[2,165],88:[2,165],90:[2,165],99:[2,165],101:[2,165],102:[2,165],103:[2,165],107:[2,165],115:[2,165],123:[2,165],125:[2,165],126:[2,165],129:[2,165],130:[2,165],131:[2,165],132:[2,165],133:[2,165],134:[2,165]},{5:301,25:[1,5]},{26:[1,302]},{6:[1,303],26:[2,171],118:[2,171],120:[2,171]},{8:304,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,98],6:[2,98],25:[2,98],26:[2,98],47:[2,98],52:[2,98],55:[2,98],70:[2,98],75:[2,98],83:[2,98],88:[2,98],90:[2,98],99:[2,98],101:[2,98],102:[2,98],103:[2,98],107:[2,98],115:[2,98],123:[2,98],125:[2,98],126:[2,98],129:[2,98],130:[2,98],131:[2,98],132:[2,98],133:[2,98],134:[2,98]},{1:[2,135],6:[2,135],25:[2,135],26:[2,135],47:[2,135],52:[2,135],55:[2,135],64:[2,135],65:[2,135],66:[2,135],68:[2,135],70:[2,135],71:[2,135],75:[2,135],81:[2,135],82:[2,135],83:[2,135],88:[2,135],90:[2,135],99:[2,135],101:[2,135],102:[2,135],103:[2,135],107:[2,135],115:[2,135],123:[2,135],125:[2,135],126:[2,135],129:[2,135],130:[2,135],131:[2,135],132:[2,135],133:[2,135],134:[2,135]},{1:[2,114],6:[2,114],25:[2,114],26:[2,114],47:[2,114],52:[2,114],55:[2,114],64:[2,114],65:[2,114],66:[2,114],68:[2,114],70:[2,114],71:[2,114],75:[2,114],81:[2,114],82:[2,114],83:[2,114],88:[2,114],90:[2,114],99:[2,114],101:[2,114],102:[2,114],103:[2,114],107:[2,114],115:[2,114],123:[2,114],125:[2,114],126:[2,114],129:[2,114],130:[2,114],131:[2,114],132:[2,114],133:[2,114],134:[2,114]},{6:[2,121],25:[2,121],26:[2,121],52:[2,121],83:[2,121],88:[2,121]},{6:[2,51],25:[2,51],26:[2,51],51:305,52:[1,222]},{6:[2,122],25:[2,122],26:[2,122],52:[2,122],83:[2,122],88:[2,122]},{1:[2,160],6:[2,160],25:[2,160],26:[2,160],47:[2,160],52:[2,160],55:[2,160],70:[2,160],75:[2,160],83:[2,160],88:[2,160],90:[2,160],99:[2,160],100:85,101:[2,160],102:[2,160],103:[2,160],106:86,107:[2,160],108:67,115:[1,306],123:[2,160],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,162],6:[2,162],25:[2,162],26:[2,162],47:[2,162],52:[2,162],55:[2,162],70:[2,162],75:[2,162],83:[2,162],88:[2,162],90:[2,162],99:[2,162],100:85,101:[2,162],102:[1,307],103:[2,162],106:86,107:[2,162],108:67,115:[2,162],123:[2,162],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,161],6:[2,161],25:[2,161],26:[2,161],47:[2,161],52:[2,161],55:[2,161],70:[2,161],75:[2,161],83:[2,161],88:[2,161],90:[2,161],99:[2,161],100:85,101:[2,161],102:[2,161],103:[2,161],106:86,107:[2,161],108:67,115:[2,161],123:[2,161],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,89],25:[2,89],26:[2,89],52:[2,89],75:[2,89]},{6:[2,51],25:[2,51],26:[2,51],51:308,52:[1,232]},{26:[1,309],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,310]},{1:[2,168],6:[2,168],25:[2,168],26:[2,168],47:[2,168],52:[2,168],55:[2,168],70:[2,168],75:[2,168],83:[2,168],88:[2,168],90:[2,168],99:[2,168],101:[2,168],102:[2,168],103:[2,168],107:[2,168],115:[2,168],123:[2,168],125:[2,168],126:[2,168],129:[2,168],130:[2,168],131:[2,168],132:[2,168],133:[2,168],134:[2,168]},{26:[2,172],118:[2,172],120:[2,172]},{25:[2,127],52:[2,127],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],26:[1,311]},{8:312,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:313,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[1,271],25:[1,272],26:[1,314]},{6:[2,39],25:[2,39],26:[2,39],52:[2,39],75:[2,39]},{1:[2,166],6:[2,166],25:[2,166],26:[2,166],47:[2,166],52:[2,166],55:[2,166],70:[2,166],75:[2,166],83:[2,166],88:[2,166],90:[2,166],99:[2,166],101:[2,166],102:[2,166],103:[2,166],107:[2,166],115:[2,166],123:[2,166],125:[2,166],126:[2,166],129:[2,166],130:[2,166],131:[2,166],132:[2,166],133:[2,166],134:[2,166]},{6:[2,123],25:[2,123],26:[2,123],52:[2,123],83:[2,123],88:[2,123]},{1:[2,163],6:[2,163],25:[2,163],26:[2,163],47:[2,163],52:[2,163],55:[2,163],70:[2,163],75:[2,163],83:[2,163],88:[2,163],90:[2,163],99:[2,163],100:85,101:[2,163],102:[2,163],103:[2,163],106:86,107:[2,163],108:67,115:[2,163],123:[2,163],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,164],6:[2,164],25:[2,164],26:[2,164],47:[2,164],52:[2,164],55:[2,164],70:[2,164],75:[2,164],83:[2,164],88:[2,164],90:[2,164],99:[2,164],100:85,101:[2,164],102:[2,164],103:[2,164],106:86,107:[2,164],108:67,115:[2,164],123:[2,164],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,90],25:[2,90],26:[2,90],52:[2,90],75:[2,90]}], defaultActions: {58:[2,49],59:[2,50],73:[2,3],92:[2,104],186:[2,84]}, parseError: function parseError(str, hash) { throw new Error(str); }, parse: function parse(input) { var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; this.lexer.setInput(input); this.lexer.yy = this.yy; this.yy.lexer = this.lexer; if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; var yyloc = this.lexer.yylloc; lstack.push(yyloc); if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; function popStack(n) { stack.length = stack.length - 2 * n; vstack.length = vstack.length - n; lstack.length = lstack.length - n; } function lex() { var token; token = self.lexer.lex() || 1; if (typeof token !== "number") { token = self.symbols_[token] || token; } return token; } var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; while (true) { state = stack[stack.length - 1]; if (this.defaultActions[state]) { action = this.defaultActions[state]; } else { if (symbol == null) symbol = lex(); action = table[state] && table[state][symbol]; } if (typeof action === "undefined" || !action.length || !action[0]) { if (!recovering) { expected = []; for (p in table[state]) if (this.terminals_[p] && p > 2) { expected.push("'" + this.terminals_[p] + "'"); } var errStr = ""; if (this.lexer.showPosition) { errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + this.terminals_[symbol] + "'"; } else { errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); } this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); } } if (action[0] instanceof Array && action.length > 1) { throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); } switch (action[0]) { case 1: stack.push(symbol); vstack.push(this.lexer.yytext); lstack.push(this.lexer.yylloc); stack.push(action[1]); symbol = null; if (!preErrorSymbol) { yyleng = this.lexer.yyleng; yytext = this.lexer.yytext; yylineno = this.lexer.yylineno; yyloc = this.lexer.yylloc; if (recovering > 0) recovering--; } else { symbol = preErrorSymbol; preErrorSymbol = null; } break; case 2: len = this.productions_[action[1]][1]; yyval.$ = vstack[vstack.length - len]; yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); if (typeof r !== "undefined") { return r; } if (len) { stack = stack.slice(0, -1 * len * 2); vstack = vstack.slice(0, -1 * len); lstack = lstack.slice(0, -1 * len); } stack.push(this.productions_[action[1]][0]); vstack.push(yyval.$); lstack.push(yyval._$); newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; stack.push(newState); break; case 3: return true; } } return true; } }; module.exports = parser; }); define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coffee/scope', 'ace/mode/coffee/lexer', 'ace/mode/coffee/helpers'], function(require, exports, module) { // Generated by CoffeeScript 1.2.1-pre var Access, Arr, Assign, Base, Block, Call, Class, Closure, Code, Comment, Existence, Extends, For, IDENTIFIER, IDENTIFIER_STR, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, METHOD_DEF, NEGATE, NO, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, compact, del, ends, extend, flatten, last, merge, multident, starts, unfoldSoak, utility, _ref, _ref1, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; Scope = require('./scope').Scope; _ref = require('./lexer'), RESERVED = _ref.RESERVED, STRICT_PROSCRIBED = _ref.STRICT_PROSCRIBED; _ref1 = require('./helpers'), compact = _ref1.compact, flatten = _ref1.flatten, extend = _ref1.extend, merge = _ref1.merge, del = _ref1.del, starts = _ref1.starts, ends = _ref1.ends, last = _ref1.last; exports.extend = extend; YES = function() { return true; }; NO = function() { return false; }; THIS = function() { return this; }; NEGATE = function() { this.negated = !this.negated; return this; }; exports.Base = Base = (function() { Base.name = 'Base'; function Base() {} Base.prototype.compile = function(o, lvl) { var node; o = extend({}, o); if (lvl) o.level = lvl; node = this.unfoldSoak(o) || this; node.tab = o.indent; if (o.level === LEVEL_TOP || !node.isStatement(o)) { return node.compileNode(o); } else { return node.compileClosure(o); } }; Base.prototype.compileClosure = function(o) { if (this.jumps()) { throw SyntaxError('cannot use a pure statement in an expression.'); } o.sharedScope = true; return Closure.wrap(this).compileNode(o); }; Base.prototype.cache = function(o, level, reused) { var ref, sub; if (!this.isComplex()) { ref = level ? this.compile(o, level) : this; return [ref, ref]; } else { ref = new Literal(reused || o.scope.freeVariable('ref')); sub = new Assign(ref, this); if (level) { return [sub.compile(o, level), ref.value]; } else { return [sub, ref]; } } }; Base.prototype.compileLoopReference = function(o, name) { var src, tmp; src = tmp = this.compile(o, LEVEL_LIST); if (!((-Infinity < +src && +src < Infinity) || IDENTIFIER.test(src) && o.scope.check(src, true))) { src = "" + (tmp = o.scope.freeVariable(name)) + " = " + src; } return [src, tmp]; }; Base.prototype.makeReturn = function(res) { var me; me = this.unwrapAll(); if (res) { return new Call(new Literal("" + res + ".push"), [me]); } else { return new Return(me); } }; Base.prototype.contains = function(pred) { var contains; contains = false; this.traverseChildren(false, function(node) { if (pred(node)) { contains = true; return false; } }); return contains; }; Base.prototype.containsType = function(type) { return this instanceof type || this.contains(function(node) { return node instanceof type; }); }; Base.prototype.lastNonComment = function(list) { var i; i = list.length; while (i--) { if (!(list[i] instanceof Comment)) return list[i]; } return null; }; Base.prototype.toString = function(idt, name) { var tree; if (idt == null) idt = ''; if (name == null) name = this.constructor.name; tree = '\n' + idt + name; if (this.soak) tree += '?'; this.eachChild(function(node) { return tree += node.toString(idt + TAB); }); return tree; }; Base.prototype.eachChild = function(func) { var attr, child, _i, _j, _len, _len1, _ref2, _ref3; if (!this.children) return this; _ref2 = this.children; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { attr = _ref2[_i]; if (this[attr]) { _ref3 = flatten([this[attr]]); for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { child = _ref3[_j]; if (func(child) === false) return this; } } } return this; }; Base.prototype.traverseChildren = function(crossScope, func) { return this.eachChild(function(child) { if (func(child) === false) return false; return child.traverseChildren(crossScope, func); }); }; Base.prototype.invert = function() { return new Op('!', this); }; Base.prototype.unwrapAll = function() { var node; node = this; while (node !== (node = node.unwrap())) { continue; } return node; }; Base.prototype.children = []; Base.prototype.isStatement = NO; Base.prototype.jumps = NO; Base.prototype.isComplex = YES; Base.prototype.isChainable = NO; Base.prototype.isAssignable = NO; Base.prototype.unwrap = THIS; Base.prototype.unfoldSoak = NO; Base.prototype.assigns = NO; return Base; })(); exports.Block = Block = (function(_super) { __extends(Block, _super); Block.name = 'Block'; function Block(nodes) { this.expressions = compact(flatten(nodes || [])); } Block.prototype.children = ['expressions']; Block.prototype.push = function(node) { this.expressions.push(node); return this; }; Block.prototype.pop = function() { return this.expressions.pop(); }; Block.prototype.unshift = function(node) { this.expressions.unshift(node); return this; }; Block.prototype.unwrap = function() { if (this.expressions.length === 1) { return this.expressions[0]; } else { return this; } }; Block.prototype.isEmpty = function() { return !this.expressions.length; }; Block.prototype.isStatement = function(o) { var exp, _i, _len, _ref2; _ref2 = this.expressions; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { exp = _ref2[_i]; if (exp.isStatement(o)) return true; } return false; }; Block.prototype.jumps = function(o) { var exp, _i, _len, _ref2; _ref2 = this.expressions; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { exp = _ref2[_i]; if (exp.jumps(o)) return exp; } }; Block.prototype.makeReturn = function(res) { var expr, len; len = this.expressions.length; while (len--) { expr = this.expressions[len]; if (!(expr instanceof Comment)) { this.expressions[len] = expr.makeReturn(res); if (expr instanceof Return && !expr.expression) { this.expressions.splice(len, 1); } break; } } return this; }; Block.prototype.compile = function(o, level) { if (o == null) o = {}; if (o.scope) { return Block.__super__.compile.call(this, o, level); } else { return this.compileRoot(o); } }; Block.prototype.compileNode = function(o) { var code, codes, node, top, _i, _len, _ref2; this.tab = o.indent; top = o.level === LEVEL_TOP; codes = []; _ref2 = this.expressions; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { node = _ref2[_i]; node = node.unwrapAll(); node = node.unfoldSoak(o) || node; if (node instanceof Block) { codes.push(node.compileNode(o)); } else if (top) { node.front = true; code = node.compile(o); if (!node.isStatement(o)) { code = "" + this.tab + code + ";"; if (node instanceof Literal) code = "" + code + "\n"; } codes.push(code); } else { codes.push(node.compile(o, LEVEL_LIST)); } } if (top) { if (this.spaced) { return "\n" + (codes.join('\n\n')) + "\n"; } else { return codes.join('\n'); } } code = codes.join(', ') || 'void 0'; if (codes.length > 1 && o.level >= LEVEL_LIST) { return "(" + code + ")"; } else { return code; } }; Block.prototype.compileRoot = function(o) { var code, exp, i, prelude, preludeExps, rest; o.indent = o.bare ? '' : TAB; o.scope = new Scope(null, this, null); o.level = LEVEL_TOP; this.spaced = true; prelude = ""; if (!o.bare) { preludeExps = (function() { var _i, _len, _ref2, _results; _ref2 = this.expressions; _results = []; for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { exp = _ref2[i]; if (!(exp.unwrap() instanceof Comment)) break; _results.push(exp); } return _results; }).call(this); rest = this.expressions.slice(preludeExps.length); this.expressions = preludeExps; if (preludeExps.length) { prelude = "" + (this.compileNode(merge(o, { indent: '' }))) + "\n"; } this.expressions = rest; } code = this.compileWithDeclarations(o); if (o.bare) return code; return "" + prelude + "(function() {\n" + code + "\n}).call(this);\n"; }; Block.prototype.compileWithDeclarations = function(o) { var assigns, code, declars, exp, i, post, rest, scope, spaced, _i, _len, _ref2, _ref3, _ref4; code = post = ''; _ref2 = this.expressions; for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { exp = _ref2[i]; exp = exp.unwrap(); if (!(exp instanceof Comment || exp instanceof Literal)) break; } o = merge(o, { level: LEVEL_TOP }); if (i) { rest = this.expressions.splice(i, 9e9); _ref3 = [this.spaced, false], spaced = _ref3[0], this.spaced = _ref3[1]; _ref4 = [this.compileNode(o), spaced], code = _ref4[0], this.spaced = _ref4[1]; this.expressions = rest; } post = this.compileNode(o); scope = o.scope; if (scope.expressions === this) { declars = o.scope.hasDeclarations(); assigns = scope.hasAssignments; if (declars || assigns) { if (i) code += '\n'; code += "" + this.tab + "var "; if (declars) code += scope.declaredVariables().join(', '); if (assigns) { if (declars) code += ",\n" + (this.tab + TAB); code += scope.assignedVariables().join(",\n" + (this.tab + TAB)); } code += ';\n'; } } return code + post; }; Block.wrap = function(nodes) { if (nodes.length === 1 && nodes[0] instanceof Block) return nodes[0]; return new Block(nodes); }; return Block; })(Base); exports.Literal = Literal = (function(_super) { __extends(Literal, _super); Literal.name = 'Literal'; function Literal(value) { this.value = value; } Literal.prototype.makeReturn = function() { if (this.isStatement()) { return this; } else { return Literal.__super__.makeReturn.apply(this, arguments); } }; Literal.prototype.isAssignable = function() { return IDENTIFIER.test(this.value); }; Literal.prototype.isStatement = function() { var _ref2; return (_ref2 = this.value) === 'break' || _ref2 === 'continue' || _ref2 === 'debugger'; }; Literal.prototype.isComplex = NO; Literal.prototype.assigns = function(name) { return name === this.value; }; Literal.prototype.jumps = function(o) { if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) { return this; } if (this.value === 'continue' && !(o != null ? o.loop : void 0)) return this; }; Literal.prototype.compileNode = function(o) { var code, _ref2; code = this.isUndefined ? o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0' : this.value === 'this' ? ((_ref2 = o.scope.method) != null ? _ref2.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value; if (this.isStatement()) { return "" + this.tab + code + ";"; } else { return code; } }; Literal.prototype.toString = function() { return ' "' + this.value + '"'; }; return Literal; })(Base); exports.Return = Return = (function(_super) { __extends(Return, _super); Return.name = 'Return'; function Return(expr) { if (expr && !expr.unwrap().isUndefined) this.expression = expr; } Return.prototype.children = ['expression']; Return.prototype.isStatement = YES; Return.prototype.makeReturn = THIS; Return.prototype.jumps = THIS; Return.prototype.compile = function(o, level) { var expr, _ref2; expr = (_ref2 = this.expression) != null ? _ref2.makeReturn() : void 0; if (expr && !(expr instanceof Return)) { return expr.compile(o, level); } else { return Return.__super__.compile.call(this, o, level); } }; Return.prototype.compileNode = function(o) { return this.tab + ("return" + [this.expression ? " " + (this.expression.compile(o, LEVEL_PAREN)) : void 0] + ";"); }; return Return; })(Base); exports.Value = Value = (function(_super) { __extends(Value, _super); Value.name = 'Value'; function Value(base, props, tag) { if (!props && base instanceof Value) return base; this.base = base; this.properties = props || []; if (tag) this[tag] = true; return this; } Value.prototype.children = ['base', 'properties']; Value.prototype.add = function(props) { this.properties = this.properties.concat(props); return this; }; Value.prototype.hasProperties = function() { return !!this.properties.length; }; Value.prototype.isArray = function() { return !this.properties.length && this.base instanceof Arr; }; Value.prototype.isComplex = function() { return this.hasProperties() || this.base.isComplex(); }; Value.prototype.isAssignable = function() { return this.hasProperties() || this.base.isAssignable(); }; Value.prototype.isSimpleNumber = function() { return this.base instanceof Literal && SIMPLENUM.test(this.base.value); }; Value.prototype.isString = function() { return this.base instanceof Literal && IS_STRING.test(this.base.value); }; Value.prototype.isAtomic = function() { var node, _i, _len, _ref2; _ref2 = this.properties.concat(this.base); for (_i = 0, _len = _ref2.length; _i < _len; _i++) { node = _ref2[_i]; if (node.soak || node instanceof Call) return false; } return true; }; Value.prototype.isStatement = function(o) { return !this.properties.length && this.base.isStatement(o); }; Value.prototype.assigns = function(name) { return !this.properties.length && this.base.assigns(name); }; Value.prototype.jumps = function(o) { return !this.properties.length && this.base.jumps(o); }; Value.prototype.isObject = function(onlyGenerated) { if (this.properties.length) return false; return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated); }; Value.prototype.isSplice = function() { return last(this.properties) instanceof Slice; }; Value.prototype.unwrap = function() { if (this.properties.length) { return this; } else { return this.base; } }; Value.prototype.cacheReference = function(o) { var base, bref, name, nref; name = last(this.properties); if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) { return [this, this]; } base = new Value(this.base, this.properties.slice(0, -1)); if (base.isComplex()) { bref = new Literal(o.scope.freeVariable('base')); base = new Value(new Parens(new Assign(bref, base))); } if (!name) return [base, bref]; if (name.isComplex()) { nref = new Literal(o.scope.freeVariable('name')); name = new Index(new Assign(nref, name.index)); nref = new Index(nref); } return [base.add(name), new Value(bref || base.base, [nref || name])]; }; Value.prototype.compileNode = function(o) { var code, prop, props, _i, _len; this.base.front = this.front; props = this.properties; code = this.base.compile(o, props.length ? LEVEL_ACCESS : null); if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(code)) { code = "" + code + "."; } for (_i = 0, _len = props.length; _i < _len; _i++) { prop = props[_i]; code += prop.compile(o); } return code; }; Value.prototype.unfoldSoak = function(o) { var result, _this = this; if (this.unfoldedSoak != null) return this.unfoldedSoak; result = (function() { var fst, i, ifn, prop, ref, snd, _i, _len, _ref2; if (ifn = _this.base.unfoldSoak(o)) { Array.prototype.push.apply(ifn.body.properties, _this.properties); return ifn; } _ref2 = _this.properties; for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { prop = _ref2[i]; if (!prop.soak) continue; prop.soak = false; fst = new Value(_this.base, _this.properties.slice(0, i)); snd = new Value(_this.base, _this.properties.slice(i)); if (fst.isComplex()) { ref = new Literal(o.scope.freeVariable('ref')); fst = new Parens(new Assign(ref, fst)); snd.base = ref; } return new If(new Existence(fst), snd, { soak: true }); } return null; })(); return this.unfoldedSoak = result || false; }; return Value; })(Base); exports.Comment = Comment = (function(_super) { __extends(Comment, _super); Comment.name = 'Comment'; function Comment(comment) { this.comment = comment; } Comment.prototype.isStatement = YES; Comment.prototype.makeReturn = THIS; Comment.prototype.compileNode = function(o, level) { var code; code = '/*' + multident(this.comment, this.tab) + ("\n" + this.tab + "*/\n"); if ((level || o.level) === LEVEL_TOP) code = o.indent + code; return code; }; return Comment; })(Base); exports.Call = Call = (function(_super) { __extends(Call, _super); Call.name = 'Call'; function Call(variable, args, soak) { this.args = args != null ? args : []; this.soak = soak; this.isNew = false; this.isSuper = variable === 'super'; this.variable = this.isSuper ? null : variable; } Call.prototype.children = ['variable', 'args']; Call.prototype.newInstance = function() { var base, _ref2; base = ((_ref2 = this.variable) != null ? _ref2.base : void 0) || this.variable; if (base instanceof Call && !base.isNew) { base.newInstance(); } else { this.isNew = true; } return this; }; Call.prototype.superReference = function(o) { var accesses, method, name; method = o.scope.method; if (!method) throw SyntaxError('cannot call super outside of a function.'); name = method.name; if (name == null) { throw SyntaxError('cannot call super on an anonymous function.'); } if (method.klass) { accesses = [new Access(new Literal('__super__'))]; if (method["static"]) { accesses.push(new Access(new Literal('constructor'))); } accesses.push(new Access(new Literal(name))); return (new Value(new Literal(method.klass), accesses)).compile(o); } else { return "" + name + ".__super__.constructor"; } }; Call.prototype.unfoldSoak = function(o) { var call, ifn, left, list, rite, _i, _len, _ref2, _ref3; if (this.soak) { if (this.variable) { if (ifn = unfoldSoak(o, this, 'variable')) return ifn; _ref2 = new Value(this.variable).cacheReference(o), left = _ref2[0], rite = _ref2[1]; } else { left = new Literal(this.superReference(o)); rite = new Value(left); } rite = new Call(rite, this.args); rite.isNew = this.isNew; left = new Literal("typeof " + (left.compile(o)) + " === \"function\""); return new If(left, new Value(rite), { soak: true }); } call = this; list = []; while (true) { if (call.variable instanceof Call) { list.push(call); call = call.variable; continue; } if (!(call.variable instanceof Value)) break; list.push(call); if (!((call = call.variable.base) instanceof Call)) break; } _ref3 = list.reverse(); for (_i = 0, _len = _ref3.length; _i < _len; _i++) { call = _ref3[_i]; if (ifn) { if (call.variable instanceof Call) { call.variable = ifn; } else { call.variable.base = ifn; } } ifn = unfoldSoak(o, call, 'variable'); } return ifn; }; Call.prototype.filterImplicitObjects = function(list) { var node, nodes, obj, prop, properties, _i, _j, _len, _len1, _ref2; nodes = []; for (_i = 0, _len = list.length; _i < _len; _i++) { node = list[_i]; if (!((typeof node.isObject === "function" ? node.isObject() : void 0) && node.base.generated)) { nodes.push(node); continue; } obj = null; _ref2 = node.base.properties; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { prop = _ref2[_j]; if (prop instanceof Assign || prop instanceof Comment) { if (!obj) nodes.push(obj = new Obj(properties = [], true)); properties.push(prop); } else { nodes.push(prop); obj = null; } } } return nodes; }; Call.prototype.compileNode = function(o) { var arg, args, code, _ref2; if ((_ref2 = this.variable) != null) _ref2.front = this.front; if (code = Splat.compileSplattedArray(o, this.args, true)) { return this.compileSplat(o, code); } args = this.filterImplicitObjects(this.args); args = ((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = args.length; _i < _len; _i++) { arg = args[_i]; _results.push(arg.compile(o, LEVEL_LIST)); } return _results; })()).join(', '); if (this.isSuper) { return this.superReference(o) + (".call(this" + (args && ', ' + args) + ")"); } else { return (this.isNew ? 'new ' : '') + this.variable.compile(o, LEVEL_ACCESS) + ("(" + args + ")"); } }; Call.prototype.compileSuper = function(args, o) { return "" + (this.superReference(o)) + ".call(this" + (args.length ? ', ' : '') + args + ")"; }; Call.prototype.compileSplat = function(o, splatArgs) { var base, fun, idt, name, ref; if (this.isSuper) { return "" + (this.superReference(o)) + ".apply(this, " + splatArgs + ")"; } if (this.isNew) { idt = this.tab + TAB; return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args), t = typeof result;\n" + idt + "return t == \"object\" || t == \"function\" ? result || child : child;\n" + this.tab + "})(" + (this.variable.compile(o, LEVEL_LIST)) + ", " + splatArgs + ", function(){})"; } base = new Value(this.variable); if ((name = base.properties.pop()) && base.isComplex()) { ref = o.scope.freeVariable('ref'); fun = "(" + ref + " = " + (base.compile(o, LEVEL_LIST)) + ")" + (name.compile(o)); } else { fun = base.compile(o, LEVEL_ACCESS); if (SIMPLENUM.test(fun)) fun = "(" + fun + ")"; if (name) { ref = fun; fun += name.compile(o); } else { ref = 'null'; } } return "" + fun + ".apply(" + ref + ", " + splatArgs + ")"; }; return Call; })(Base); exports.Extends = Extends = (function(_super) { __extends(Extends, _super); Extends.name = 'Extends'; function Extends(child, parent) { this.child = child; this.parent = parent; } Extends.prototype.children = ['child', 'parent']; Extends.prototype.compile = function(o) { return new Call(new Value(new Literal(utility('extends'))), [this.child, this.parent]).compile(o); }; return Extends; })(Base); exports.Access = Access = (function(_super) { __extends(Access, _super); Access.name = 'Access'; function Access(name, tag) { this.name = name; this.name.asKey = true; this.soak = tag === 'soak'; } Access.prototype.children = ['name']; Access.prototype.compile = function(o) { var name; name = this.name.compile(o); if (IDENTIFIER.test(name)) { return "." + name; } else { return "[" + name + "]"; } }; Access.prototype.isComplex = NO; return Access; })(Base); exports.Index = Index = (function(_super) { __extends(Index, _super); Index.name = 'Index'; function Index(index) { this.index = index; } Index.prototype.children = ['index']; Index.prototype.compile = function(o) { return "[" + (this.index.compile(o, LEVEL_PAREN)) + "]"; }; Index.prototype.isComplex = function() { return this.index.isComplex(); }; return Index; })(Base); exports.Range = Range = (function(_super) { __extends(Range, _super); Range.name = 'Range'; Range.prototype.children = ['from', 'to']; function Range(from, to, tag) { this.from = from; this.to = to; this.exclusive = tag === 'exclusive'; this.equals = this.exclusive ? '' : '='; } Range.prototype.compileVariables = function(o) { var step, _ref2, _ref3, _ref4, _ref5; o = merge(o, { top: true }); _ref2 = this.from.cache(o, LEVEL_LIST), this.fromC = _ref2[0], this.fromVar = _ref2[1]; _ref3 = this.to.cache(o, LEVEL_LIST), this.toC = _ref3[0], this.toVar = _ref3[1]; if (step = del(o, 'step')) { _ref4 = step.cache(o, LEVEL_LIST), this.step = _ref4[0], this.stepVar = _ref4[1]; } _ref5 = [this.fromVar.match(SIMPLENUM), this.toVar.match(SIMPLENUM)], this.fromNum = _ref5[0], this.toNum = _ref5[1]; if (this.stepVar) return this.stepNum = this.stepVar.match(SIMPLENUM); }; Range.prototype.compileNode = function(o) { var cond, condPart, from, gt, idx, idxName, known, lt, namedIndex, stepPart, to, varPart, _ref2, _ref3; if (!this.fromVar) this.compileVariables(o); if (!o.index) return this.compileArray(o); known = this.fromNum && this.toNum; idx = del(o, 'index'); idxName = del(o, 'name'); namedIndex = idxName && idxName !== idx; varPart = "" + idx + " = " + this.fromC; if (this.toC !== this.toVar) varPart += ", " + this.toC; if (this.step !== this.stepVar) varPart += ", " + this.step; _ref2 = ["" + idx + " <" + this.equals, "" + idx + " >" + this.equals], lt = _ref2[0], gt = _ref2[1]; condPart = this.stepNum ? +this.stepNum > 0 ? "" + lt + " " + this.toVar : "" + gt + " " + this.toVar : known ? ((_ref3 = [+this.fromNum, +this.toNum], from = _ref3[0], to = _ref3[1], _ref3), from <= to ? "" + lt + " " + to : "" + gt + " " + to) : (cond = "" + this.fromVar + " <= " + this.toVar, "" + cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar); stepPart = this.stepVar ? "" + idx + " += " + this.stepVar : known ? namedIndex ? from <= to ? "++" + idx : "--" + idx : from <= to ? "" + idx + "++" : "" + idx + "--" : namedIndex ? "" + cond + " ? ++" + idx + " : --" + idx : "" + cond + " ? " + idx + "++ : " + idx + "--"; if (namedIndex) varPart = "" + idxName + " = " + varPart; if (namedIndex) stepPart = "" + idxName + " = " + stepPart; return "" + varPart + "; " + condPart + "; " + stepPart; }; Range.prototype.compileArray = function(o) { var args, body, cond, hasArgs, i, idt, post, pre, range, result, vars, _i, _ref2, _ref3, _results; if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) { range = (function() { _results = []; for (var _i = _ref2 = +this.fromNum, _ref3 = +this.toNum; _ref2 <= _ref3 ? _i <= _ref3 : _i >= _ref3; _ref2 <= _ref3 ? _i++ : _i--){ _results.push(_i); } return _results; }).apply(this); if (this.exclusive) range.pop(); return "[" + (range.join(', ')) + "]"; } idt = this.tab + TAB; i = o.scope.freeVariable('i'); result = o.scope.freeVariable('results'); pre = "\n" + idt + result + " = [];"; if (this.fromNum && this.toNum) { o.index = i; body = this.compileNode(o); } else { vars = ("" + i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : ''); cond = "" + this.fromVar + " <= " + this.toVar; body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--"; } post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent; hasArgs = function(node) { return node != null ? node.contains(function(n) { return n instanceof Literal && n.value === 'arguments' && !n.asKey; }) : void 0; }; if (hasArgs(this.from) || hasArgs(this.to)) args = ', arguments'; return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")"; }; return Range; })(Base); exports.Slice = Slice = (function(_super) { __extends(Slice, _super); Slice.name = 'Slice'; Slice.prototype.children = ['range']; function Slice(range) { this.range = range; Slice.__super__.constructor.call(this); } Slice.prototype.compileNode = function(o) { var compiled, from, fromStr, to, toStr, _ref2; _ref2 = this.range, to = _ref2.to, from = _ref2.from; fromStr = from && from.compile(o, LEVEL_PAREN) || '0'; compiled = to && to.compile(o, LEVEL_PAREN); if (to && !(!this.range.exclusive && +compiled === -1)) { toStr = ', ' + (this.range.exclusive ? compiled : SIMPLENUM.test(compiled) ? "" + (+compiled + 1) : (compiled = to.compile(o, LEVEL_ACCESS), "" + compiled + " + 1 || 9e9")); } return ".slice(" + fromStr + (toStr || '') + ")"; }; return Slice; })(Base); exports.Obj = Obj = (function(_super) { __extends(Obj, _super); Obj.name = 'Obj'; function Obj(props, generated) { this.generated = generated != null ? generated : false; this.objects = this.properties = props || []; } Obj.prototype.children = ['properties']; Obj.prototype.compileNode = function(o) { var i, idt, indent, join, lastNoncom, node, obj, prop, propName, propNames, props, _i, _j, _len, _len1, _ref2; props = this.properties; propNames = []; _ref2 = this.properties; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { prop = _ref2[_i]; if (prop.isComplex()) prop = prop.variable; if (prop != null) { propName = prop.unwrapAll().value.toString(); if (__indexOf.call(propNames, propName) >= 0) { throw SyntaxError("multiple object literal properties named \"" + propName + "\""); } propNames.push(propName); } } if (!props.length) return (this.front ? '({})' : '{}'); if (this.generated) { for (_j = 0, _len1 = props.length; _j < _len1; _j++) { node = props[_j]; if (node instanceof Value) { throw new Error('cannot have an implicit value in an implicit object'); } } } idt = o.indent += TAB; lastNoncom = this.lastNonComment(this.properties); props = (function() { var _k, _len2, _results; _results = []; for (i = _k = 0, _len2 = props.length; _k < _len2; i = ++_k) { prop = props[i]; join = i === props.length - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n'; indent = prop instanceof Comment ? '' : idt; if (prop instanceof Value && prop["this"]) { prop = new Assign(prop.properties[0].name, prop, 'object'); } if (!(prop instanceof Comment)) { if (!(prop instanceof Assign)) prop = new Assign(prop, prop, 'object'); (prop.variable.base || prop.variable).asKey = true; } _results.push(indent + prop.compile(o, LEVEL_TOP) + join); } return _results; })(); props = props.join(''); obj = "{" + (props && '\n' + props + '\n' + this.tab) + "}"; if (this.front) { return "(" + obj + ")"; } else { return obj; } }; Obj.prototype.assigns = function(name) { var prop, _i, _len, _ref2; _ref2 = this.properties; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { prop = _ref2[_i]; if (prop.assigns(name)) return true; } return false; }; return Obj; })(Base); exports.Arr = Arr = (function(_super) { __extends(Arr, _super); Arr.name = 'Arr'; function Arr(objs) { this.objects = objs || []; } Arr.prototype.children = ['objects']; Arr.prototype.filterImplicitObjects = Call.prototype.filterImplicitObjects; Arr.prototype.compileNode = function(o) { var code, obj, objs; if (!this.objects.length) return '[]'; o.indent += TAB; objs = this.filterImplicitObjects(this.objects); if (code = Splat.compileSplattedArray(o, objs)) return code; code = ((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = objs.length; _i < _len; _i++) { obj = objs[_i]; _results.push(obj.compile(o, LEVEL_LIST)); } return _results; })()).join(', '); if (code.indexOf('\n') >= 0) { return "[\n" + o.indent + code + "\n" + this.tab + "]"; } else { return "[" + code + "]"; } }; Arr.prototype.assigns = function(name) { var obj, _i, _len, _ref2; _ref2 = this.objects; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { obj = _ref2[_i]; if (obj.assigns(name)) return true; } return false; }; return Arr; })(Base); exports.Class = Class = (function(_super) { __extends(Class, _super); Class.name = 'Class'; function Class(variable, parent, body) { this.variable = variable; this.parent = parent; this.body = body != null ? body : new Block; this.boundFuncs = []; this.body.classBody = true; } Class.prototype.children = ['variable', 'parent', 'body']; Class.prototype.determineName = function() { var decl, tail; if (!this.variable) return null; decl = (tail = last(this.variable.properties)) ? tail instanceof Access && tail.name.value : this.variable.base.value; if (__indexOf.call(STRICT_PROSCRIBED, decl) >= 0) { throw SyntaxError("variable name may not be " + decl); } return decl && (decl = IDENTIFIER.test(decl) && decl); }; Class.prototype.setContext = function(name) { return this.body.traverseChildren(false, function(node) { if (node.classBody) return false; if (node instanceof Literal && node.value === 'this') { return node.value = name; } else if (node instanceof Code) { node.klass = name; if (node.bound) return node.context = name; } }); }; Class.prototype.addBoundFunctions = function(o) { var bvar, lhs, _i, _len, _ref2, _results; if (this.boundFuncs.length) { _ref2 = this.boundFuncs; _results = []; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { bvar = _ref2[_i]; lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o); _results.push(this.ctor.body.unshift(new Literal("" + lhs + " = " + (utility('bind')) + "(" + lhs + ", this)"))); } return _results; } }; Class.prototype.addProperties = function(node, name, o) { var assign, base, exprs, func, props; props = node.base.properties.slice(0); exprs = (function() { var _results; _results = []; while (assign = props.shift()) { if (assign instanceof Assign) { base = assign.variable.base; delete assign.context; func = assign.value; if (base.value === 'constructor') { if (this.ctor) { throw new Error('cannot define more than one constructor in a class'); } if (func.bound) { throw new Error('cannot define a constructor as a bound function'); } if (func instanceof Code) { assign = this.ctor = func; } else { this.externalCtor = o.scope.freeVariable('class'); assign = new Assign(new Literal(this.externalCtor), func); } } else { if (assign.variable["this"]) { func["static"] = true; if (func.bound) func.context = name; } else { assign.variable = new Value(new Literal(name), [new Access(new Literal('prototype')), new Access(base)]); if (func instanceof Code && func.bound) { this.boundFuncs.push(base); func.bound = false; } } } } _results.push(assign); } return _results; }).call(this); return compact(exprs); }; Class.prototype.walkBody = function(name, o) { var _this = this; return this.traverseChildren(false, function(child) { var exps, i, node, _i, _len, _ref2; if (child instanceof Class) return false; if (child instanceof Block) { _ref2 = exps = child.expressions; for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { node = _ref2[i]; if (node instanceof Value && node.isObject(true)) { exps[i] = _this.addProperties(node, name, o); } } return child.expressions = exps = flatten(exps); } }); }; Class.prototype.hoistDirectivePrologue = function() { var expressions, index, node; index = 0; expressions = this.body.expressions; while ((node = expressions[index]) && node instanceof Comment || node instanceof Value && node.isString()) { ++index; } return this.directives = expressions.splice(0, index); }; Class.prototype.ensureConstructor = function(name) { if (!this.ctor) { this.ctor = new Code; if (this.parent) { this.ctor.body.push(new Literal("" + name + ".__super__.constructor.apply(this, arguments)")); } if (this.externalCtor) { this.ctor.body.push(new Literal("" + this.externalCtor + ".apply(this, arguments)")); } this.ctor.body.makeReturn(); this.body.expressions.unshift(this.ctor); } this.ctor.ctor = this.ctor.name = name; this.ctor.klass = null; return this.ctor.noReturn = true; }; Class.prototype.compileNode = function(o) { var call, decl, klass, lname, name, params, _ref2; decl = this.determineName(); name = decl || '_Class'; if (name.reserved) name = "_" + name; lname = new Literal(name); this.hoistDirectivePrologue(); this.setContext(name); this.walkBody(name, o); this.ensureConstructor(name); this.body.spaced = true; if (!(this.ctor instanceof Code)) this.body.expressions.unshift(this.ctor); if (decl) { this.body.expressions.unshift(new Assign(new Value(new Literal(name), [new Access(new Literal('name'))]), new Literal("'" + name + "'"))); } this.body.expressions.push(lname); (_ref2 = this.body.expressions).unshift.apply(_ref2, this.directives); this.addBoundFunctions(o); call = Closure.wrap(this.body); if (this.parent) { this.superClass = new Literal(o.scope.freeVariable('super', false)); this.body.expressions.unshift(new Extends(lname, this.superClass)); call.args.push(this.parent); params = call.variable.params || call.variable.base.params; params.push(new Param(this.superClass)); } klass = new Parens(call, true); if (this.variable) klass = new Assign(this.variable, klass); return klass.compile(o); }; return Class; })(Base); exports.Assign = Assign = (function(_super) { __extends(Assign, _super); Assign.name = 'Assign'; function Assign(variable, value, context, options) { var forbidden, name, _ref2; this.variable = variable; this.value = value; this.context = context; this.param = options && options.param; this.subpattern = options && options.subpattern; forbidden = (_ref2 = (name = this.variable.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0); if (forbidden && this.context !== 'object') { throw SyntaxError("variable name may not be \"" + name + "\""); } } Assign.prototype.children = ['variable', 'value']; Assign.prototype.isStatement = function(o) { return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && __indexOf.call(this.context, "?") >= 0; }; Assign.prototype.assigns = function(name) { return this[this.context === 'object' ? 'value' : 'variable'].assigns(name); }; Assign.prototype.unfoldSoak = function(o) { return unfoldSoak(o, this, 'variable'); }; Assign.prototype.compileNode = function(o) { var isValue, match, name, val, varBase, _ref2, _ref3, _ref4, _ref5; if (isValue = this.variable instanceof Value) { if (this.variable.isArray() || this.variable.isObject()) { return this.compilePatternMatch(o); } if (this.variable.isSplice()) return this.compileSplice(o); if ((_ref2 = this.context) === '||=' || _ref2 === '&&=' || _ref2 === '?=') { return this.compileConditional(o); } } name = this.variable.compile(o, LEVEL_LIST); if (!this.context) { if (!(varBase = this.variable.unwrapAll()).isAssignable()) { throw SyntaxError("\"" + (this.variable.compile(o)) + "\" cannot be assigned."); } if (!(typeof varBase.hasProperties === "function" ? varBase.hasProperties() : void 0)) { if (this.param) { o.scope.add(name, 'var'); } else { o.scope.find(name); } } } if (this.value instanceof Code && (match = METHOD_DEF.exec(name))) { if (match[1]) this.value.klass = match[1]; this.value.name = (_ref3 = (_ref4 = (_ref5 = match[2]) != null ? _ref5 : match[3]) != null ? _ref4 : match[4]) != null ? _ref3 : match[5]; } val = this.value.compile(o, LEVEL_LIST); if (this.context === 'object') return "" + name + ": " + val; val = name + (" " + (this.context || '=') + " ") + val; if (o.level <= LEVEL_LIST) { return val; } else { return "(" + val + ")"; } }; Assign.prototype.compilePatternMatch = function(o) { var acc, assigns, code, i, idx, isObject, ivar, name, obj, objects, olen, ref, rest, splat, top, val, value, vvar, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; top = o.level === LEVEL_TOP; value = this.value; objects = this.variable.base.objects; if (!(olen = objects.length)) { code = value.compile(o); if (o.level >= LEVEL_OP) { return "(" + code + ")"; } else { return code; } } isObject = this.variable.isObject(); if (top && olen === 1 && !((obj = objects[0]) instanceof Splat)) { if (obj instanceof Assign) { _ref2 = obj, (_ref3 = _ref2.variable, idx = _ref3.base), obj = _ref2.value; } else { if (obj.base instanceof Parens) { _ref4 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref4[0], idx = _ref4[1]; } else { idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0); } } acc = IDENTIFIER.test(idx.unwrap().value || 0); value = new Value(value); value.properties.push(new (acc ? Access : Index)(idx)); if (_ref5 = obj.unwrap().value, __indexOf.call(RESERVED, _ref5) >= 0) { throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (value.compile(o))); } return new Assign(obj, value, null, { param: this.param }).compile(o, LEVEL_TOP); } vvar = value.compile(o, LEVEL_LIST); assigns = []; splat = false; if (!IDENTIFIER.test(vvar) || this.variable.assigns(vvar)) { assigns.push("" + (ref = o.scope.freeVariable('ref')) + " = " + vvar); vvar = ref; } for (i = _i = 0, _len = objects.length; _i < _len; i = ++_i) { obj = objects[i]; idx = i; if (isObject) { if (obj instanceof Assign) { _ref6 = obj, (_ref7 = _ref6.variable, idx = _ref7.base), obj = _ref6.value; } else { if (obj.base instanceof Parens) { _ref8 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref8[0], idx = _ref8[1]; } else { idx = obj["this"] ? obj.properties[0].name : obj; } } } if (!splat && obj instanceof Splat) { name = obj.name.unwrap().value; obj = obj.unwrap(); val = "" + olen + " <= " + vvar + ".length ? " + (utility('slice')) + ".call(" + vvar + ", " + i; if (rest = olen - i - 1) { ivar = o.scope.freeVariable('i'); val += ", " + ivar + " = " + vvar + ".length - " + rest + ") : (" + ivar + " = " + i + ", [])"; } else { val += ") : []"; } val = new Literal(val); splat = "" + ivar + "++"; } else { name = obj.unwrap().value; if (obj instanceof Splat) { obj = obj.name.compile(o); throw new SyntaxError("multiple splats are disallowed in an assignment: " + obj + "..."); } if (typeof idx === 'number') { idx = new Literal(splat || idx); acc = false; } else { acc = isObject && IDENTIFIER.test(idx.unwrap().value || 0); } val = new Value(new Literal(vvar), [new (acc ? Access : Index)(idx)]); } if ((name != null) && __indexOf.call(RESERVED, name) >= 0) { throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (val.compile(o))); } assigns.push(new Assign(obj, val, null, { param: this.param, subpattern: true }).compile(o, LEVEL_LIST)); } if (!(top || this.subpattern)) assigns.push(vvar); code = assigns.join(', '); if (o.level < LEVEL_LIST) { return code; } else { return "(" + code + ")"; } }; Assign.prototype.compileConditional = function(o) { var left, right, _ref2; _ref2 = this.variable.cacheReference(o), left = _ref2[0], right = _ref2[1]; if (left.base instanceof Literal && left.base.value !== "this" && !o.scope.check(left.base.value)) { throw new Error("the variable \"" + left.base.value + "\" can't be assigned with " + this.context + " because it has not been defined."); } if (__indexOf.call(this.context, "?") >= 0) o.isExistentialEquals = true; return new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compile(o); }; Assign.prototype.compileSplice = function(o) { var code, exclusive, from, fromDecl, fromRef, name, to, valDef, valRef, _ref2, _ref3, _ref4; _ref2 = this.variable.properties.pop().range, from = _ref2.from, to = _ref2.to, exclusive = _ref2.exclusive; name = this.variable.compile(o); _ref3 = (from != null ? from.cache(o, LEVEL_OP) : void 0) || ['0', '0'], fromDecl = _ref3[0], fromRef = _ref3[1]; if (to) { if ((from != null ? from.isSimpleNumber() : void 0) && to.isSimpleNumber()) { to = +to.compile(o) - +fromRef; if (!exclusive) to += 1; } else { to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef; if (!exclusive) to += ' + 1'; } } else { to = "9e9"; } _ref4 = this.value.cache(o, LEVEL_LIST), valDef = _ref4[0], valRef = _ref4[1]; code = "[].splice.apply(" + name + ", [" + fromDecl + ", " + to + "].concat(" + valDef + ")), " + valRef; if (o.level > LEVEL_TOP) { return "(" + code + ")"; } else { return code; } }; return Assign; })(Base); exports.Code = Code = (function(_super) { __extends(Code, _super); Code.name = 'Code'; function Code(params, body, tag) { this.params = params || []; this.body = body || new Block; this.bound = tag === 'boundfunc'; if (this.bound) this.context = '_this'; } Code.prototype.children = ['params', 'body']; Code.prototype.isStatement = function() { return !!this.ctor; }; Code.prototype.jumps = NO; Code.prototype.compileNode = function(o) { var code, exprs, i, idt, lit, name, p, param, params, ref, splats, uniqs, val, wasEmpty, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; o.scope = new Scope(o.scope, this.body, this); o.scope.shared = del(o, 'sharedScope'); o.indent += TAB; delete o.bare; delete o.isExistentialEquals; params = []; exprs = []; _ref2 = this.paramNames(); for (_i = 0, _len = _ref2.length; _i < _len; _i++) { name = _ref2[_i]; if (!o.scope.check(name)) o.scope.parameter(name); } _ref3 = this.params; for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { param = _ref3[_j]; if (!param.splat) continue; _ref4 = this.params; for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) { p = _ref4[_k]; if (p.name.value) o.scope.add(p.name.value, 'var', true); } splats = new Assign(new Value(new Arr((function() { var _l, _len3, _ref5, _results; _ref5 = this.params; _results = []; for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { p = _ref5[_l]; _results.push(p.asReference(o)); } return _results; }).call(this))), new Value(new Literal('arguments'))); break; } _ref5 = this.params; for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { param = _ref5[_l]; if (param.isComplex()) { val = ref = param.asReference(o); if (param.value) val = new Op('?', ref, param.value); exprs.push(new Assign(new Value(param.name), val, '=', { param: true })); } else { ref = param; if (param.value) { lit = new Literal(ref.name.value + ' == null'); val = new Assign(new Value(param.name), param.value, '='); exprs.push(new If(lit, val)); } } if (!splats) params.push(ref); } wasEmpty = this.body.isEmpty(); if (splats) exprs.unshift(splats); if (exprs.length) { (_ref6 = this.body.expressions).unshift.apply(_ref6, exprs); } for (i = _m = 0, _len4 = params.length; _m < _len4; i = ++_m) { p = params[i]; o.scope.parameter(params[i] = p.compile(o)); } uniqs = []; _ref7 = this.paramNames(); for (_n = 0, _len5 = _ref7.length; _n < _len5; _n++) { name = _ref7[_n]; if (__indexOf.call(uniqs, name) >= 0) { throw SyntaxError("multiple parameters named '" + name + "'"); } uniqs.push(name); } if (!(wasEmpty || this.noReturn)) this.body.makeReturn(); if (this.bound) { if ((_ref8 = o.scope.parent.method) != null ? _ref8.bound : void 0) { this.bound = this.context = o.scope.parent.method.context; } else if (!this["static"]) { o.scope.parent.assign('_this', 'this'); } } idt = o.indent; code = 'function'; if (this.ctor) code += ' ' + this.name; code += '(' + params.join(', ') + ') {'; if (!this.body.isEmpty()) { code += "\n" + (this.body.compileWithDeclarations(o)) + "\n" + this.tab; } code += '}'; if (this.ctor) return this.tab + code; if (this.front || (o.level >= LEVEL_ACCESS)) { return "(" + code + ")"; } else { return code; } }; Code.prototype.paramNames = function() { var names, param, _i, _len, _ref2; names = []; _ref2 = this.params; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { param = _ref2[_i]; names.push.apply(names, param.names()); } return names; }; Code.prototype.traverseChildren = function(crossScope, func) { if (crossScope) { return Code.__super__.traverseChildren.call(this, crossScope, func); } }; return Code; })(Base); exports.Param = Param = (function(_super) { __extends(Param, _super); Param.name = 'Param'; function Param(name, value, splat) { var _ref2; this.name = name; this.value = value; this.splat = splat; if (_ref2 = (name = this.name.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { throw SyntaxError("parameter name \"" + name + "\" is not allowed"); } } Param.prototype.children = ['name', 'value']; Param.prototype.compile = function(o) { return this.name.compile(o, LEVEL_LIST); }; Param.prototype.asReference = function(o) { var node; if (this.reference) return this.reference; node = this.name; if (node["this"]) { node = node.properties[0].name; if (node.value.reserved) { node = new Literal(o.scope.freeVariable(node.value)); } } else if (node.isComplex()) { node = new Literal(o.scope.freeVariable('arg')); } node = new Value(node); if (this.splat) node = new Splat(node); return this.reference = node; }; Param.prototype.isComplex = function() { return this.name.isComplex(); }; Param.prototype.names = function(name) { var atParam, names, obj, _i, _len, _ref2; if (name == null) name = this.name; atParam = function(obj) { var value; value = obj.properties[0].name.value; if (value.reserved) { return []; } else { return [value]; } }; if (name instanceof Literal) return [name.value]; if (name instanceof Value) return atParam(name); names = []; _ref2 = name.objects; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { obj = _ref2[_i]; if (obj instanceof Assign) { names.push(obj.variable.base.value); } else if (obj.isArray() || obj.isObject()) { names.push.apply(names, this.names(obj.base)); } else if (obj["this"]) { names.push.apply(names, atParam(obj)); } else { names.push(obj.base.value); } } return names; }; return Param; })(Base); exports.Splat = Splat = (function(_super) { __extends(Splat, _super); Splat.name = 'Splat'; Splat.prototype.children = ['name']; Splat.prototype.isAssignable = YES; function Splat(name) { this.name = name.compile ? name : new Literal(name); } Splat.prototype.assigns = function(name) { return this.name.assigns(name); }; Splat.prototype.compile = function(o) { if (this.index != null) { return this.compileParam(o); } else { return this.name.compile(o); } }; Splat.prototype.unwrap = function() { return this.name; }; Splat.compileSplattedArray = function(o, list, apply) { var args, base, code, i, index, node, _i, _len; index = -1; while ((node = list[++index]) && !(node instanceof Splat)) { continue; } if (index >= list.length) return ''; if (list.length === 1) { code = list[0].compile(o, LEVEL_LIST); if (apply) return code; return "" + (utility('slice')) + ".call(" + code + ")"; } args = list.slice(index); for (i = _i = 0, _len = args.length; _i < _len; i = ++_i) { node = args[i]; code = node.compile(o, LEVEL_LIST); args[i] = node instanceof Splat ? "" + (utility('slice')) + ".call(" + code + ")" : "[" + code + "]"; } if (index === 0) { return args[0] + (".concat(" + (args.slice(1).join(', ')) + ")"); } base = (function() { var _j, _len1, _ref2, _results; _ref2 = list.slice(0, index); _results = []; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { node = _ref2[_j]; _results.push(node.compile(o, LEVEL_LIST)); } return _results; })(); return "[" + (base.join(', ')) + "].concat(" + (args.join(', ')) + ")"; }; return Splat; })(Base); exports.While = While = (function(_super) { __extends(While, _super); While.name = 'While'; function While(condition, options) { this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition; this.guard = options != null ? options.guard : void 0; } While.prototype.children = ['condition', 'guard', 'body']; While.prototype.isStatement = YES; While.prototype.makeReturn = function(res) { if (res) { return While.__super__.makeReturn.apply(this, arguments); } else { this.returns = !this.jumps({ loop: true }); return this; } }; While.prototype.addBody = function(body) { this.body = body; return this; }; While.prototype.jumps = function() { var expressions, node, _i, _len; expressions = this.body.expressions; if (!expressions.length) return false; for (_i = 0, _len = expressions.length; _i < _len; _i++) { node = expressions[_i]; if (node.jumps({ loop: true })) return node; } return false; }; While.prototype.compileNode = function(o) { var body, code, rvar, set; o.indent += TAB; set = ''; body = this.body; if (body.isEmpty()) { body = ''; } else { if (this.returns) { body.makeReturn(rvar = o.scope.freeVariable('results')); set = "" + this.tab + rvar + " = [];\n"; } if (this.guard) { if (body.expressions.length > 1) { body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); } else { if (this.guard) body = Block.wrap([new If(this.guard, body)]); } } body = "\n" + (body.compile(o, LEVEL_TOP)) + "\n" + this.tab; } code = set + this.tab + ("while (" + (this.condition.compile(o, LEVEL_PAREN)) + ") {" + body + "}"); if (this.returns) code += "\n" + this.tab + "return " + rvar + ";"; return code; }; return While; })(Base); exports.Op = Op = (function(_super) { var CONVERSIONS, INVERSIONS; __extends(Op, _super); Op.name = 'Op'; function Op(op, first, second, flip) { if (op === 'in') return new In(first, second); if (op === 'do') return this.generateDo(first); if (op === 'new') { if (first instanceof Call && !first["do"] && !first.isNew) { return first.newInstance(); } if (first instanceof Code && first.bound || first["do"]) { first = new Parens(first); } } this.operator = CONVERSIONS[op] || op; this.first = first; this.second = second; this.flip = !!flip; return this; } CONVERSIONS = { '==': '===', '!=': '!==', 'of': 'in' }; INVERSIONS = { '!==': '===', '===': '!==' }; Op.prototype.children = ['first', 'second']; Op.prototype.isSimpleNumber = NO; Op.prototype.isUnary = function() { return !this.second; }; Op.prototype.isComplex = function() { var _ref2; return !(this.isUnary() && ((_ref2 = this.operator) === '+' || _ref2 === '-')) || this.first.isComplex(); }; Op.prototype.isChainable = function() { var _ref2; return (_ref2 = this.operator) === '<' || _ref2 === '>' || _ref2 === '>=' || _ref2 === '<=' || _ref2 === '===' || _ref2 === '!=='; }; Op.prototype.invert = function() { var allInvertable, curr, fst, op, _ref2; if (this.isChainable() && this.first.isChainable()) { allInvertable = true; curr = this; while (curr && curr.operator) { allInvertable && (allInvertable = curr.operator in INVERSIONS); curr = curr.first; } if (!allInvertable) return new Parens(this).invert(); curr = this; while (curr && curr.operator) { curr.invert = !curr.invert; curr.operator = INVERSIONS[curr.operator]; curr = curr.first; } return this; } else if (op = INVERSIONS[this.operator]) { this.operator = op; if (this.first.unwrap() instanceof Op) this.first.invert(); return this; } else if (this.second) { return new Parens(this).invert(); } else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((_ref2 = fst.operator) === '!' || _ref2 === 'in' || _ref2 === 'instanceof')) { return fst; } else { return new Op('!', this); } }; Op.prototype.unfoldSoak = function(o) { var _ref2; return ((_ref2 = this.operator) === '++' || _ref2 === '--' || _ref2 === 'delete') && unfoldSoak(o, this, 'first'); }; Op.prototype.generateDo = function(exp) { var call, func, param, passedParams, ref, _i, _len, _ref2; passedParams = []; func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp; _ref2 = func.params || []; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { param = _ref2[_i]; if (param.value) { passedParams.push(param.value); delete param.value; } else { passedParams.push(param); } } call = new Call(exp, passedParams); call["do"] = true; return call; }; Op.prototype.compileNode = function(o) { var code, isChain, _ref2, _ref3; isChain = this.isChainable() && this.first.isChainable(); if (!isChain) this.first.front = this.front; if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) { throw SyntaxError('delete operand may not be argument or var'); } if (((_ref2 = this.operator) === '--' || _ref2 === '++') && (_ref3 = this.first.unwrapAll().value, __indexOf.call(STRICT_PROSCRIBED, _ref3) >= 0)) { throw SyntaxError('prefix increment/decrement may not have eval or arguments operand'); } if (this.isUnary()) return this.compileUnary(o); if (isChain) return this.compileChain(o); if (this.operator === '?') return this.compileExistence(o); code = this.first.compile(o, LEVEL_OP) + ' ' + this.operator + ' ' + this.second.compile(o, LEVEL_OP); if (o.level <= LEVEL_OP) { return code; } else { return "(" + code + ")"; } }; Op.prototype.compileChain = function(o) { var code, fst, shared, _ref2; _ref2 = this.first.second.cache(o), this.first.second = _ref2[0], shared = _ref2[1]; fst = this.first.compile(o, LEVEL_OP); code = "" + fst + " " + (this.invert ? '&&' : '||') + " " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o, LEVEL_OP)); return "(" + code + ")"; }; Op.prototype.compileExistence = function(o) { var fst, ref; if (this.first.isComplex() && o.level > LEVEL_TOP) { ref = new Literal(o.scope.freeVariable('ref')); fst = new Parens(new Assign(ref, this.first)); } else { fst = this.first; ref = fst; } return new If(new Existence(fst), ref, { type: 'if' }).addElse(this.second).compile(o); }; Op.prototype.compileUnary = function(o) { var op, parts, plusMinus; if (o.level >= LEVEL_ACCESS) return (new Parens(this)).compile(o); parts = [op = this.operator]; plusMinus = op === '+' || op === '-'; if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) { parts.push(' '); } if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) { this.first = new Parens(this.first); } parts.push(this.first.compile(o, LEVEL_OP)); if (this.flip) parts.reverse(); return parts.join(''); }; Op.prototype.toString = function(idt) { return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator); }; return Op; })(Base); exports.In = In = (function(_super) { __extends(In, _super); In.name = 'In'; function In(object, array) { this.object = object; this.array = array; } In.prototype.children = ['object', 'array']; In.prototype.invert = NEGATE; In.prototype.compileNode = function(o) { var hasSplat, obj, _i, _len, _ref2; if (this.array instanceof Value && this.array.isArray()) { _ref2 = this.array.base.objects; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { obj = _ref2[_i]; if (!(obj instanceof Splat)) continue; hasSplat = true; break; } if (!hasSplat) return this.compileOrTest(o); } return this.compileLoopTest(o); }; In.prototype.compileOrTest = function(o) { var cmp, cnj, i, item, ref, sub, tests, _ref2, _ref3; if (this.array.base.objects.length === 0) return "" + (!!this.negated); _ref2 = this.object.cache(o, LEVEL_OP), sub = _ref2[0], ref = _ref2[1]; _ref3 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = _ref3[0], cnj = _ref3[1]; tests = (function() { var _i, _len, _ref4, _results; _ref4 = this.array.base.objects; _results = []; for (i = _i = 0, _len = _ref4.length; _i < _len; i = ++_i) { item = _ref4[i]; _results.push((i ? ref : sub) + cmp + item.compile(o, LEVEL_ACCESS)); } return _results; }).call(this); tests = tests.join(cnj); if (o.level < LEVEL_OP) { return tests; } else { return "(" + tests + ")"; } }; In.prototype.compileLoopTest = function(o) { var code, ref, sub, _ref2; _ref2 = this.object.cache(o, LEVEL_LIST), sub = _ref2[0], ref = _ref2[1]; code = utility('indexOf') + (".call(" + (this.array.compile(o, LEVEL_LIST)) + ", " + ref + ") ") + (this.negated ? '< 0' : '>= 0'); if (sub === ref) return code; code = sub + ', ' + code; if (o.level < LEVEL_LIST) { return code; } else { return "(" + code + ")"; } }; In.prototype.toString = function(idt) { return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : '')); }; return In; })(Base); exports.Try = Try = (function(_super) { __extends(Try, _super); Try.name = 'Try'; function Try(attempt, error, recovery, ensure) { this.attempt = attempt; this.error = error; this.recovery = recovery; this.ensure = ensure; } Try.prototype.children = ['attempt', 'recovery', 'ensure']; Try.prototype.isStatement = YES; Try.prototype.jumps = function(o) { var _ref2; return this.attempt.jumps(o) || ((_ref2 = this.recovery) != null ? _ref2.jumps(o) : void 0); }; Try.prototype.makeReturn = function(res) { if (this.attempt) this.attempt = this.attempt.makeReturn(res); if (this.recovery) this.recovery = this.recovery.makeReturn(res); return this; }; Try.prototype.compileNode = function(o) { var catchPart, ensurePart, errorPart, tryPart; o.indent += TAB; errorPart = this.error ? " (" + (this.error.compile(o)) + ") " : ' '; tryPart = this.attempt.compile(o, LEVEL_TOP); catchPart = (function() { var _ref2; if (this.recovery) { if (_ref2 = this.error.value, __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { throw SyntaxError("catch variable may not be \"" + this.error.value + "\""); } if (!o.scope.check(this.error.value)) { o.scope.add(this.error.value, 'param'); } return " catch" + errorPart + "{\n" + (this.recovery.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"; } else if (!(this.ensure || this.recovery)) { return ' catch (_error) {}'; } }).call(this); ensurePart = this.ensure ? " finally {\n" + (this.ensure.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : ''; return "" + this.tab + "try {\n" + tryPart + "\n" + this.tab + "}" + (catchPart || '') + ensurePart; }; return Try; })(Base); exports.Throw = Throw = (function(_super) { __extends(Throw, _super); Throw.name = 'Throw'; function Throw(expression) { this.expression = expression; } Throw.prototype.children = ['expression']; Throw.prototype.isStatement = YES; Throw.prototype.jumps = NO; Throw.prototype.makeReturn = THIS; Throw.prototype.compileNode = function(o) { return this.tab + ("throw " + (this.expression.compile(o)) + ";"); }; return Throw; })(Base); exports.Existence = Existence = (function(_super) { __extends(Existence, _super); Existence.name = 'Existence'; function Existence(expression) { this.expression = expression; } Existence.prototype.children = ['expression']; Existence.prototype.invert = NEGATE; Existence.prototype.compileNode = function(o) { var cmp, cnj, code, _ref2; this.expression.front = this.front; code = this.expression.compile(o, LEVEL_OP); if (IDENTIFIER.test(code) && !o.scope.check(code)) { _ref2 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = _ref2[0], cnj = _ref2[1]; code = "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null"; } else { code = "" + code + " " + (this.negated ? '==' : '!=') + " null"; } if (o.level <= LEVEL_COND) { return code; } else { return "(" + code + ")"; } }; return Existence; })(Base); exports.Parens = Parens = (function(_super) { __extends(Parens, _super); Parens.name = 'Parens'; function Parens(body) { this.body = body; } Parens.prototype.children = ['body']; Parens.prototype.unwrap = function() { return this.body; }; Parens.prototype.isComplex = function() { return this.body.isComplex(); }; Parens.prototype.compileNode = function(o) { var bare, code, expr; expr = this.body.unwrap(); if (expr instanceof Value && expr.isAtomic()) { expr.front = this.front; return expr.compile(o); } code = expr.compile(o, LEVEL_PAREN); bare = o.level < LEVEL_OP && (expr instanceof Op || expr instanceof Call || (expr instanceof For && expr.returns)); if (bare) { return code; } else { return "(" + code + ")"; } }; return Parens; })(Base); exports.For = For = (function(_super) { __extends(For, _super); For.name = 'For'; function For(body, source) { var _ref2; this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index; this.body = Block.wrap([body]); this.own = !!source.own; this.object = !!source.object; if (this.object) { _ref2 = [this.index, this.name], this.name = _ref2[0], this.index = _ref2[1]; } if (this.index instanceof Value) { throw SyntaxError('index cannot be a pattern matching expression'); } this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length; this.pattern = this.name instanceof Value; if (this.range && this.index) { throw SyntaxError('indexes do not apply to range loops'); } if (this.range && this.pattern) { throw SyntaxError('cannot pattern match over range loops'); } this.returns = false; } For.prototype.children = ['body', 'source', 'guard', 'step']; For.prototype.compileNode = function(o) { var body, defPart, forPart, forVarPart, guardPart, idt1, index, ivar, kvar, kvarAssign, lastJumps, lvar, name, namePart, ref, resultPart, returnResult, rvar, scope, source, stepPart, stepvar, svar, varPart, _ref2; body = Block.wrap([this.body]); lastJumps = (_ref2 = last(body.expressions)) != null ? _ref2.jumps() : void 0; if (lastJumps && lastJumps instanceof Return) this.returns = false; source = this.range ? this.source.base : this.source; scope = o.scope; name = this.name && this.name.compile(o, LEVEL_LIST); index = this.index && this.index.compile(o, LEVEL_LIST); if (name && !this.pattern) { scope.find(name, { immediate: true }); } if (index) { scope.find(index, { immediate: true }); } if (this.returns) rvar = scope.freeVariable('results'); ivar = (this.object && index) || scope.freeVariable('i'); kvar = (this.range && name) || index || ivar; kvarAssign = kvar !== ivar ? "" + kvar + " = " : ""; if (this.step && !this.range) stepvar = scope.freeVariable("step"); if (this.pattern) name = ivar; varPart = ''; guardPart = ''; defPart = ''; idt1 = this.tab + TAB; if (this.range) { forPart = source.compile(merge(o, { index: ivar, name: name, step: this.step })); } else { svar = this.source.compile(o, LEVEL_LIST); if ((name || this.own) && !IDENTIFIER.test(svar)) { defPart = "" + this.tab + (ref = scope.freeVariable('ref')) + " = " + svar + ";\n"; svar = ref; } if (name && !this.pattern) { namePart = "" + name + " = " + svar + "[" + kvar + "]"; } if (!this.object) { lvar = scope.freeVariable('len'); forVarPart = "" + kvarAssign + ivar + " = 0, " + lvar + " = " + svar + ".length"; if (this.step) { forVarPart += ", " + stepvar + " = " + (this.step.compile(o, LEVEL_OP)); } stepPart = "" + kvarAssign + (this.step ? "" + ivar + " += " + stepvar : (kvar !== ivar ? "++" + ivar : "" + ivar + "++")); forPart = "" + forVarPart + "; " + ivar + " < " + lvar + "; " + stepPart; } } if (this.returns) { resultPart = "" + this.tab + rvar + " = [];\n"; returnResult = "\n" + this.tab + "return " + rvar + ";"; body.makeReturn(rvar); } if (this.guard) { if (body.expressions.length > 1) { body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); } else { if (this.guard) body = Block.wrap([new If(this.guard, body)]); } } if (this.pattern) { body.expressions.unshift(new Assign(this.name, new Literal("" + svar + "[" + kvar + "]"))); } defPart += this.pluckDirectCall(o, body); if (namePart) varPart = "\n" + idt1 + namePart + ";"; if (this.object) { forPart = "" + kvar + " in " + svar; if (this.own) { guardPart = "\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + kvar + ")) continue;"; } } body = body.compile(merge(o, { indent: idt1 }), LEVEL_TOP); if (body) body = '\n' + body + '\n'; return "" + defPart + (resultPart || '') + this.tab + "for (" + forPart + ") {" + guardPart + varPart + body + this.tab + "}" + (returnResult || ''); }; For.prototype.pluckDirectCall = function(o, body) { var base, defs, expr, fn, idx, ref, val, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; defs = ''; _ref2 = body.expressions; for (idx = _i = 0, _len = _ref2.length; _i < _len; idx = ++_i) { expr = _ref2[idx]; expr = expr.unwrapAll(); if (!(expr instanceof Call)) continue; val = expr.variable.unwrapAll(); if (!((val instanceof Code) || (val instanceof Value && ((_ref3 = val.base) != null ? _ref3.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((_ref4 = (_ref5 = val.properties[0].name) != null ? _ref5.value : void 0) === 'call' || _ref4 === 'apply')))) { continue; } fn = ((_ref6 = val.base) != null ? _ref6.unwrapAll() : void 0) || val; ref = new Literal(o.scope.freeVariable('fn')); base = new Value(ref); if (val.base) _ref7 = [base, val], val.base = _ref7[0], base = _ref7[1]; body.expressions[idx] = new Call(base, expr.args); defs += this.tab + new Assign(ref, fn).compile(o, LEVEL_TOP) + ';\n'; } return defs; }; return For; })(While); exports.Switch = Switch = (function(_super) { __extends(Switch, _super); Switch.name = 'Switch'; function Switch(subject, cases, otherwise) { this.subject = subject; this.cases = cases; this.otherwise = otherwise; } Switch.prototype.children = ['subject', 'cases', 'otherwise']; Switch.prototype.isStatement = YES; Switch.prototype.jumps = function(o) { var block, conds, _i, _len, _ref2, _ref3, _ref4; if (o == null) { o = { block: true }; } _ref2 = this.cases; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { _ref3 = _ref2[_i], conds = _ref3[0], block = _ref3[1]; if (block.jumps(o)) return block; } return (_ref4 = this.otherwise) != null ? _ref4.jumps(o) : void 0; }; Switch.prototype.makeReturn = function(res) { var pair, _i, _len, _ref2, _ref3; _ref2 = this.cases; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { pair = _ref2[_i]; pair[1].makeReturn(res); } if (res) { this.otherwise || (this.otherwise = new Block([new Literal('void 0')])); } if ((_ref3 = this.otherwise) != null) _ref3.makeReturn(res); return this; }; Switch.prototype.compileNode = function(o) { var block, body, code, cond, conditions, expr, i, idt1, idt2, _i, _j, _len, _len1, _ref2, _ref3, _ref4, _ref5; idt1 = o.indent + TAB; idt2 = o.indent = idt1 + TAB; code = this.tab + ("switch (" + (((_ref2 = this.subject) != null ? _ref2.compile(o, LEVEL_PAREN) : void 0) || false) + ") {\n"); _ref3 = this.cases; for (i = _i = 0, _len = _ref3.length; _i < _len; i = ++_i) { _ref4 = _ref3[i], conditions = _ref4[0], block = _ref4[1]; _ref5 = flatten([conditions]); for (_j = 0, _len1 = _ref5.length; _j < _len1; _j++) { cond = _ref5[_j]; if (!this.subject) cond = cond.invert(); code += idt1 + ("case " + (cond.compile(o, LEVEL_PAREN)) + ":\n"); } if (body = block.compile(o, LEVEL_TOP)) code += body + '\n'; if (i === this.cases.length - 1 && !this.otherwise) break; expr = this.lastNonComment(block.expressions); if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) { continue; } code += idt2 + 'break;\n'; } if (this.otherwise && this.otherwise.expressions.length) { code += idt1 + ("default:\n" + (this.otherwise.compile(o, LEVEL_TOP)) + "\n"); } return code + this.tab + '}'; }; return Switch; })(Base); exports.If = If = (function(_super) { __extends(If, _super); If.name = 'If'; function If(condition, body, options) { this.body = body; if (options == null) options = {}; this.condition = options.type === 'unless' ? condition.invert() : condition; this.elseBody = null; this.isChain = false; this.soak = options.soak; } If.prototype.children = ['condition', 'body', 'elseBody']; If.prototype.bodyNode = function() { var _ref2; return (_ref2 = this.body) != null ? _ref2.unwrap() : void 0; }; If.prototype.elseBodyNode = function() { var _ref2; return (_ref2 = this.elseBody) != null ? _ref2.unwrap() : void 0; }; If.prototype.addElse = function(elseBody) { if (this.isChain) { this.elseBodyNode().addElse(elseBody); } else { this.isChain = elseBody instanceof If; this.elseBody = this.ensureBlock(elseBody); } return this; }; If.prototype.isStatement = function(o) { var _ref2; return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((_ref2 = this.elseBodyNode()) != null ? _ref2.isStatement(o) : void 0); }; If.prototype.jumps = function(o) { var _ref2; return this.body.jumps(o) || ((_ref2 = this.elseBody) != null ? _ref2.jumps(o) : void 0); }; If.prototype.compileNode = function(o) { if (this.isStatement(o)) { return this.compileStatement(o); } else { return this.compileExpression(o); } }; If.prototype.makeReturn = function(res) { if (res) { this.elseBody || (this.elseBody = new Block([new Literal('void 0')])); } this.body && (this.body = new Block([this.body.makeReturn(res)])); this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)])); return this; }; If.prototype.ensureBlock = function(node) { if (node instanceof Block) { return node; } else { return new Block([node]); } }; If.prototype.compileStatement = function(o) { var body, bodyc, child, cond, exeq, ifPart, _ref2; child = del(o, 'chainChild'); exeq = del(o, 'isExistentialEquals'); if (exeq) { return new If(this.condition.invert(), this.elseBodyNode(), { type: 'if' }).compile(o); } cond = this.condition.compile(o, LEVEL_PAREN); o.indent += TAB; body = this.ensureBlock(this.body); bodyc = body.compile(o); if (1 === ((_ref2 = body.expressions) != null ? _ref2.length : void 0) && !this.elseBody && !child && bodyc && cond && -1 === (bodyc.indexOf('\n')) && 80 > cond.length + bodyc.length) { return "" + this.tab + "if (" + cond + ") " + (bodyc.replace(/^\s+/, '')); } if (bodyc) bodyc = "\n" + bodyc + "\n" + this.tab; ifPart = "if (" + cond + ") {" + bodyc + "}"; if (!child) ifPart = this.tab + ifPart; if (!this.elseBody) return ifPart; return ifPart + ' else ' + (this.isChain ? (o.indent = this.tab, o.chainChild = true, this.elseBody.unwrap().compile(o, LEVEL_TOP)) : "{\n" + (this.elseBody.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"); }; If.prototype.compileExpression = function(o) { var alt, body, code, cond; cond = this.condition.compile(o, LEVEL_COND); body = this.bodyNode().compile(o, LEVEL_LIST); alt = this.elseBodyNode() ? this.elseBodyNode().compile(o, LEVEL_LIST) : 'void 0'; code = "" + cond + " ? " + body + " : " + alt; if (o.level >= LEVEL_COND) { return "(" + code + ")"; } else { return code; } }; If.prototype.unfoldSoak = function() { return this.soak && this; }; return If; })(Base); Closure = { wrap: function(expressions, statement, noReturn) { var args, call, func, mentionsArgs, meth; if (expressions.jumps()) return expressions; func = new Code([], Block.wrap([expressions])); args = []; if ((mentionsArgs = expressions.contains(this.literalArgs)) || expressions.contains(this.literalThis)) { meth = new Literal(mentionsArgs ? 'apply' : 'call'); args = [new Literal('this')]; if (mentionsArgs) args.push(new Literal('arguments')); func = new Value(func, [new Access(meth)]); } func.noReturn = noReturn; call = new Call(func, args); if (statement) { return Block.wrap([call]); } else { return call; } }, literalArgs: function(node) { return node instanceof Literal && node.value === 'arguments' && !node.asKey; }, literalThis: function(node) { return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound); } }; unfoldSoak = function(o, parent, name) { var ifn; if (!(ifn = parent[name].unfoldSoak(o))) return; parent[name] = ifn.body; ifn.body = new Value(parent); return ifn; }; UTILITIES = { "extends": function() { return "function(child, parent) { for (var key in parent) { if (" + (utility('hasProp')) + ".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }"; }, 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; }"; }, hasProp: function() { return '{}.hasOwnProperty'; }, slice: function() { return '[].slice'; } }; LEVEL_TOP = 1; LEVEL_PAREN = 2; LEVEL_LIST = 3; LEVEL_COND = 4; LEVEL_OP = 5; LEVEL_ACCESS = 6; TAB = ' '; IDENTIFIER_STR = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*"; IDENTIFIER = RegExp("^" + IDENTIFIER_STR + "$"); SIMPLENUM = /^[+-]?\d+$/; METHOD_DEF = RegExp("^(?:(" + IDENTIFIER_STR + ")\\.prototype(?:\\.(" + IDENTIFIER_STR + ")|\\[(\"(?:[^\\\\\"\\r\\n]|\\\\.)*\"|'(?:[^\\\\'\\r\\n]|\\\\.)*')\\]|\\[(0x[\\da-fA-F]+|\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\]))|(" + IDENTIFIER_STR + ")$"); IS_STRING = /^['"]/; utility = function(name) { var ref; ref = "__" + name; Scope.root.assign(ref, UTILITIES[name]()); return ref; }; multident = function(code, tab) { code = code.replace(/\n/g, '$&' + tab); return code.replace(/\s+$/, ''); }; }); define('ace/mode/coffee/scope', ['require', 'exports', 'module' , 'ace/mode/coffee/helpers'], function(require, exports, module) { // Generated by CoffeeScript 1.2.1-pre var Scope, extend, last, _ref; _ref = require('./helpers'), extend = _ref.extend, last = _ref.last; exports.Scope = Scope = (function() { Scope.name = 'Scope'; Scope.root = null; function Scope(parent, expressions, method) { this.parent = parent; this.expressions = expressions; this.method = method; this.variables = [ { name: 'arguments', type: 'arguments' } ]; this.positions = {}; if (!this.parent) Scope.root = this; } Scope.prototype.add = function(name, type, immediate) { if (this.shared && !immediate) return this.parent.add(name, type, immediate); if (Object.prototype.hasOwnProperty.call(this.positions, name)) { return this.variables[this.positions[name]].type = type; } else { return this.positions[name] = this.variables.push({ name: name, type: type }) - 1; } }; Scope.prototype.find = function(name, options) { if (this.check(name, options)) return true; this.add(name, 'var'); return false; }; Scope.prototype.parameter = function(name) { if (this.shared && this.parent.check(name, true)) return; return this.add(name, 'param'); }; Scope.prototype.check = function(name, immediate) { var found, _ref1; found = !!this.type(name); if (found || immediate) return found; return !!((_ref1 = this.parent) != null ? _ref1.check(name) : void 0); }; Scope.prototype.temporary = function(name, index) { if (name.length > 1) { return '_' + name + (index > 1 ? index - 1 : ''); } else { return '_' + (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a'); } }; Scope.prototype.type = function(name) { var v, _i, _len, _ref1; _ref1 = this.variables; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { v = _ref1[_i]; if (v.name === name) return v.type; } return null; }; Scope.prototype.freeVariable = function(name, reserve) { var index, temp; if (reserve == null) reserve = true; index = 0; while (this.check((temp = this.temporary(name, index)))) { index++; } if (reserve) this.add(temp, 'var', true); return temp; }; Scope.prototype.assign = function(name, value) { this.add(name, { value: value, assigned: true }, true); return this.hasAssignments = true; }; Scope.prototype.hasDeclarations = function() { return !!this.declaredVariables().length; }; Scope.prototype.declaredVariables = function() { var realVars, tempVars, v, _i, _len, _ref1; realVars = []; tempVars = []; _ref1 = this.variables; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { v = _ref1[_i]; if (v.type === 'var') { (v.name.charAt(0) === '_' ? tempVars : realVars).push(v.name); } } return realVars.sort().concat(tempVars.sort()); }; Scope.prototype.assignedVariables = function() { var v, _i, _len, _ref1, _results; _ref1 = this.variables; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { v = _ref1[_i]; if (v.type.assigned) _results.push("" + v.name + " = " + v.type.value); } return _results; }; return Scope; })(); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/worker-coffee.js
JavaScript
asf20
323,787
/* vim:ts=4:sts=4:sw=4: * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Mihai Sucan <mihai DOT sucan AT gmail DOT com> * Chris Spencer <chris.ag.spencer AT googlemail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/markdown', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/mode/javascript', 'ace/mode/xml', 'ace/mode/html', 'ace/tokenizer', 'ace/mode/markdown_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var XmlMode = require("./xml").Mode; var HtmlMode = require("./html").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var MarkdownHighlightRules = require("./markdown_highlight_rules").MarkdownHighlightRules; var Mode = function() { var highlighter = new MarkdownHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); this.$embeds = highlighter.getEmbeds(); this.createModeDelegates({ "js-": JavaScriptMode, "xml-": XmlMode, "html-": HtmlMode }); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { if (state == "listblock") { var match = /^((?:.+)?)([-+*][ ]+)/.exec(line); if (match) { return new Array(match[1].length + 1).join(" ") + match[2]; } else { return ""; } } else { return this.$getIndent(line); } }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules()); this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" }], cdata : [{ token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "(?:[^\\]]|\\](?!\\]>))+" }], comment : [{ token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); }; oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); }); define('ace/mode/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/mode/javascript', 'ace/mode/css', 'ace/tokenizer', 'ace/mode/html_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/html'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var Mode = function() { var highlighter = new HtmlHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); this.$behaviour = new XmlBehaviour(); this.$embeds = highlighter.getEmbeds(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { return 0; }; this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("csslint", function(e) { var errors = []; e.data.forEach(function(message) { errors.push({ row: message.line - 1, column: message.col - 1, text: message.message, type: message.type, lint: message }); }); session.setAnnotations(errors); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/html_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var HtmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", merge : true, regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", regex : "<(?=\s*script\\b)", next : "script" }, { token : "meta.tag", regex : "<(?=\s*style\\b)", next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" } ], cdata : [ { token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", merge : true, regex : "\\s+" }, { token : "text", merge : true, regex : ".+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" } ] }; xmlUtil.tag(this.$rules, "tag", "start"); xmlUtil.tag(this.$rules, "style", "css-start"); xmlUtil.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); this.embedRules(CssHighlightRules, "css-", [{ token: "meta.tag", regex: "<\\/(?=style)", next: "tag" }]); }; oop.inherits(HtmlHighlightRules, TextHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); define('ace/mode/folding/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/mixed', 'ace/mode/folding/xml', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function() { MixedFoldMode.call(this, new XmlFoldMode({ // void elements "area": 1, "base": 1, "br": 1, "col": 1, "command": 1, "embed": 1, "hr": 1, "img": 1, "input": 1, "keygen": 1, "link": 1, "meta": 1, "param": 1, "source": 1, "track": 1, "wbr": 1, // optional tags "li": 1, "dt": 1, "dd": 1, "p": 1, "rt": 1, "rp": 1, "optgroup": 1, "option": 1, "colgroup": 1, "td": 1, "th": 1 }), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); define('ace/mode/folding/mixed', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); define('ace/mode/markdown_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/xml_highlight_rules', 'ace/mode/html_highlight_rules', 'ace/mode/css_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; function github_embed(tag, prefix) { return { // Github style block token : "support.function", regex : "^```" + tag + "\\s*$", next : prefix + "start" }; } var MarkdownHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "empty_line", regex : '^$' }, { // code span ` token : ["support.function", "support.function", "support.function"], regex : "(`+)([^\\r]*?[^`])(\\1)" }, { // code block token : "support.function", regex : "^[ ]{4}.+" }, { // h1 token: "markup.heading.1", regex: "^=+(?=\\s*$)" }, { // h2 token: "markup.heading.1", regex: "^\\-+(?=\\s*$)" }, { // header token : function(value) { return "markup.heading." + value.length; }, regex : "^#{1,6}" }, github_embed("javascript", "js-"), github_embed("xml", "xml-"), github_embed("html", "html-"), github_embed("css", "css-"), { // Github style block token : "support.function", regex : "^```[a-zA-Z]+\\s*$", next : "githubblock" }, { // block quote token : "string", regex : "^>[ ].+$", next : "blockquote" }, { // reference token : ["text", "constant", "text", "url", "string", "text"], regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$" }, { // link by reference token : ["text", "string", "text", "constant", "text"], regex : "(\\[)((?:[[^\\]]*\\]|[^\\[\\]])*)(\\][ ]?(?:\\n[ ]*)?\\[)(.*?)(\\])" }, { // link by url token : ["text", "string", "text", "markup.underline", "string", "text"], regex : "(\\[)"+ "(\\[[^\\]]*\\]|[^\\[\\]]*)"+ "(\\]\\([ \\t]*)"+ "(<?(?:(?:[^\\(]*?\\([^\\)]*?\\)\\S*?)|(?:.*?))>?)"+ "((?:[ \t]*\"(?:.*?)\"[ \\t]*)?)"+ "(\\))" }, { // HR * token : "constant", regex : "^[ ]{0,2}(?:[ ]?\\*[ ]?){3,}\\s*$" }, { // HR - token : "constant", regex : "^[ ]{0,2}(?:[ ]?\\-[ ]?){3,}\\s*$" }, { // HR _ token : "constant", regex : "^[ ]{0,2}(?:[ ]?\\_[ ]?){3,}\\s*$" }, { // list token : "markup.list", regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+", next : "listblock" }, { // strong ** __ token : ["string", "string", "string"], regex : "([*]{2}|[_]{2}(?=\\S))([^\\r]*?\\S[*_]*)(\\1)" }, { // emphasis * _ token : ["string", "string", "string"], regex : "([*]|[_](?=\\S))([^\\r]*?\\S[*_]*)(\\1)" }, { // token : ["text", "url", "text"], regex : "(<)("+ "(?:https?|ftp|dict):[^'\">\\s]+"+ "|"+ "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+ ")(>)" }, { token : "text", regex : "[^\\*_%$`\\[#<>]+" } ], "listblock" : [ { // Lists only escape on completely blank lines. token : "empty_line", regex : "^$", next : "start" }, { token : "markup.list", regex : ".+" } ], "blockquote" : [ { // BLockquotes only escape on blank lines. token : "empty_line", regex : "^\\s*$", next : "start" }, { token : "string", regex : ".+" } ], "githubblock" : [ { token : "support.function", regex : "^```", next : "start" }, { token : "support.function", regex : ".+" } ] }; this.embedRules(JavaScriptHighlightRules, "js-", [{ token : "support.function", regex : "^```", next : "start" }]); this.embedRules(HtmlHighlightRules, "html-", [{ token : "support.function", regex : "^```", next : "start" }]); this.embedRules(CssHighlightRules, "css-", [{ token : "support.function", regex : "^```", next : "start" }]); this.embedRules(XmlHighlightRules, "xml-", [{ token : "support.function", regex : "^```", next : "start" }]); }; oop.inherits(MarkdownHighlightRules, TextHighlightRules); exports.MarkdownHighlightRules = MarkdownHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-markdown.js
JavaScript
asf20
83,322
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Gastón Kleiman <gaston.kleiman AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/scad', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/scad_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var scadHighlightRules = require("./scad_highlight_rules").scadHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new scadHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/scad_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var scadHighlightRules = function() { var keywords = lang.arrayToMap( ("module|if|else|for").split("|") ); var buildinConstants = lang.arrayToMap( ("NULL").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant", // <CONSTANT> regex : "<[a-zA-Z0-9.]+>" }, { token : "keyword", // pre-compiler directivs regex : "(?:use|include)" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(scadHighlightRules, TextHighlightRules); exports.scadHighlightRules = scadHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-scad.js
JavaScript
asf20
23,155
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/tomorrow_night', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-tomorrow-night"; exports.cssText = "\ .ace-tomorrow-night .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tomorrow-night .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tomorrow-night .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-tomorrow-night .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tomorrow-night .ace_scroller {\ background-color: #1D1F21;\ }\ \ .ace-tomorrow-night .ace_text-layer {\ cursor: text;\ color: #C5C8C6;\ }\ \ .ace-tomorrow-night .ace_cursor {\ border-left: 2px solid #AEAFAD;\ }\ \ .ace-tomorrow-night .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #AEAFAD;\ }\ \ .ace-tomorrow-night .ace_marker-layer .ace_selection {\ background: #373B41;\ }\ \ .ace-tomorrow-night.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #1D1F21;\ border-radius: 2px;\ }\ \ .ace-tomorrow-night .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-tomorrow-night .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #4B4E55;\ }\ \ .ace-tomorrow-night .ace_marker-layer .ace_active_line {\ background: #282A2E;\ }\ \ .ace-tomorrow-night .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-tomorrow-night .ace_marker-layer .ace_selected_word {\ border: 1px solid #373B41;\ }\ \ .ace-tomorrow-night .ace_invisible {\ color: #4B4E55;\ }\ \ .ace-tomorrow-night .ace_keyword, .ace-tomorrow-night .ace_meta {\ color:#B294BB;\ }\ \ .ace-tomorrow-night .ace_keyword.ace_operator {\ color:#8ABEB7;\ }\ \ .ace-tomorrow-night .ace_constant.ace_language {\ color:#DE935F;\ }\ \ .ace-tomorrow-night .ace_constant.ace_numeric {\ color:#DE935F;\ }\ \ .ace-tomorrow-night .ace_constant.ace_other {\ color:#CED1CF;\ }\ \ .ace-tomorrow-night .ace_invalid {\ color:#CED2CF;\ background-color:#DF5F5F;\ }\ \ .ace-tomorrow-night .ace_invalid.ace_deprecated {\ color:#CED2CF;\ background-color:#B798BF;\ }\ \ .ace-tomorrow-night .ace_support.ace_constant {\ color:#DE935F;\ }\ \ .ace-tomorrow-night .ace_fold {\ background-color: #81A2BE;\ border-color: #C5C8C6;\ }\ \ .ace-tomorrow-night .ace_support.ace_function {\ color:#81A2BE;\ }\ \ .ace-tomorrow-night .ace_storage {\ color:#B294BB;\ }\ \ .ace-tomorrow-night .ace_storage.ace_type, .ace-tomorrow-night .ace_support.ace_type{\ color:#B294BB;\ }\ \ .ace-tomorrow-night .ace_variable {\ color:#81A2BE;\ }\ \ .ace-tomorrow-night .ace_variable.ace_parameter {\ color:#DE935F;\ }\ \ .ace-tomorrow-night .ace_string {\ color:#B5BD68;\ }\ \ .ace-tomorrow-night .ace_string.ace_regexp {\ color:#CC6666;\ }\ \ .ace-tomorrow-night .ace_comment {\ color:#969896;\ }\ \ .ace-tomorrow-night .ace_variable {\ color:#CC6666;\ }\ \ .ace-tomorrow-night .ace_meta.ace_tag {\ color:#CC6666;\ }\ \ .ace-tomorrow-night .ace_entity.ace_other.ace_attribute-name {\ color:#CC6666;\ }\ \ .ace-tomorrow-night .ace_entity.ace_name.ace_function {\ color:#81A2BE;\ }\ \ .ace-tomorrow-night .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-tomorrow-night .ace_markup.ace_heading {\ color:#B5BD68;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-tomorrow_night.js
JavaScript
asf20
5,185
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Rich Healey <richo AT psych0tik DOT net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/sh', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/sh_highlight_rules', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ShHighlightRules = require("./sh_highlight_rules").ShHighlightRules; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new ShHighlightRules().getRules()); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; var outdents = { "pass": 1, "return": 1, "raise": 1, "break": 1, "continue": 1 }; this.checkOutdent = function(state, line, input) { if (input !== "\r\n" && input !== "\r" && input !== "\n") return false; var tokens = this.$tokenizer.getLineTokens(line.trim(), state).tokens; if (!tokens) return false; // ignore trailing comments do { var last = tokens.pop(); } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); if (!last) return false; return (last.type == "keyword" && outdents[last.value]); }; this.autoOutdent = function(state, doc, row) { // outdenting in sh is slightly different because it always applies // to the next line and only of a new line is inserted row += 1; var indent = this.$getIndent(doc.getLine(row)); var tab = doc.getTabString(); if (indent.slice(-tab.length) == tab) doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/sh_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ShHighlightRules = function() { var reservedKeywords = lang.arrayToMap( ('!|{|}|case|do|done|elif|else|'+ 'esac|fi|for|if|in|then|until|while|'+ '&|;|export|local|read|typeset|unset|'+ 'elif|select|set' ).split('|') ); var languageConstructs = lang.arrayToMap( ('[|]|alias|bg|bind|break|builtin|'+ 'cd|command|compgen|complete|continue|'+ 'dirs|disown|echo|enable|eval|exec|'+ 'exit|fc|fg|getopts|hash|help|history|'+ 'jobs|kill|let|logout|popd|printf|pushd|'+ 'pwd|return|set|shift|shopt|source|'+ 'suspend|test|times|trap|type|ulimit|'+ 'umask|unalias|wait' ).split('|') ); var integer = "(?:(?:[1-9]\\d*)|(?:0))"; // var integer = "(?:" + decimalInteger + ")"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; var fileDescriptor = "(?:&" + intPart + ")"; var variableName = "[a-zA-Z][a-zA-Z0-9_]*"; var variable = "(?:(?:\\$" + variableName + ")|(?:" + variableName + "=))"; var builtinVariable = "(?:\\$(?:SHLVL|\\$|\\!|\\?))"; var func = "(?:" + variableName + "\\s*\\(\\))"; this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string", // " string regex : '"(?:[^\\\\]|\\\\.)*?"' }, { token : "variable.language", regex : builtinVariable }, { token : "variable", regex : variable }, { token : "support.function", regex : func, }, { token : "support.function", regex : fileDescriptor }, { token : "string", // ' string regex : "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (reservedKeywords.hasOwnProperty(value)) return "keyword"; else if (languageConstructs.hasOwnProperty(value)) return "constant.language"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, 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+" } ] }; }; oop.inherits(ShHighlightRules, TextHighlightRules); exports.ShHighlightRules = ShHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-sh.js
JavaScript
asf20
8,374
/* ***** BEGIN LICENSE BLOCK ***** * The Original Code is Ajax.org Code Editor (ACE). * * Contributor(s): * Jonathan Camile <jonathan.camile AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/pgsql', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/pgsql_highlight_rules', 'ace/range'], function(require, exports, module) { var oop = require("ace/lib/oop"); var TextMode = require("ace/mode/text").Mode; var Tokenizer = require("ace/tokenizer").Tokenizer; var PgsqlHighlightRules = require("ace/mode/pgsql_highlight_rules").PgsqlHighlightRules; var Range = require("ace/range").Range; // var EditSession = require("ace/edit_session").EditSession; var Mode = function() { this.$tokenizer = new Tokenizer(new PgsqlHighlightRules().getRules()); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; // var outentedRows = []; var re = /^(\s*)--/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "--"); } }; this.getNextLineIndent = function(state, line, tab) { if (state == "start" || state == "keyword.statementEnd") { return ""; } else { return this.$getIndent(line); // Keep whatever indent the previous line has } } }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/pgsql_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules', 'ace/mode/perl_highlight_rules', 'ace/mode/python_highlight_rules'], function(require, exports, module) { var oop = require("ace/lib/oop"); var lang = require("ace/lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; // Supporting perl and python for now -- both in pg core and ace var PerlHighlightRules = require("./perl_highlight_rules").PerlHighlightRules; var PythonHighlightRules = require("./python_highlight_rules").PythonHighlightRules; var PgsqlHighlightRules = function() { // Keywords, functions, operators last updated for pg 9.1. var keywords = lang.arrayToMap( ("abort|absolute|abstime|access|aclitem|action|add|admin|after|aggregate|all|also|alter|always|" + "analyse|analyze|and|any|anyarray|anyelement|anyenum|anynonarray|array|as|asc|assertion|" + "assignment|asymmetric|at|attribute|authorization|backward|before|begin|between|bigint|" + "binary|bit|bool|boolean|both|box|bpchar|by|bytea|cache|called|cascade|cascaded|case|cast|" + "catalog|chain|char|character|characteristics|check|checkpoint|cid|cidr|circle|class|close|" + "cluster|coalesce|collate|collation|column|comment|comments|commit|committed|concurrently|" + "configuration|connection|constraint|constraints|content|continue|conversion|copy|cost|" + "create|cross|cstring|csv|current|current_catalog|current_date|current_role|" + "current_schema|current_time|current_timestamp|current_user|cursor|cycle|data|database|" + "date|day|deallocate|dec|decimal|declare|default|defaults|deferrable|deferred|definer|delete|" + "delimiter|delimiters|desc|dictionary|disable|discard|distinct|do|document|domain|double|" + "drop|each|else|enable|encoding|encrypted|end|enum|escape|except|exclude|excluding|exclusive|" + "execute|exists|explain|extension|external|extract|false|family|fdw_handler|fetch|first|" + "float|float4|float8|following|for|force|foreign|forward|freeze|from|full|function|functions|" + "global|grant|granted|greatest|group|gtsvector|handler|having|header|hold|hour|identity|if|" + "ilike|immediate|immutable|implicit|in|including|increment|index|indexes|inet|inherit|" + "inherits|initially|inline|inner|inout|input|insensitive|insert|instead|int|int2|int2vector|" + "int4|int8|integer|internal|intersect|interval|into|invoker|is|isnull|isolation|join|key|label|" + "language|language_handler|large|last|lc_collate|lc_ctype|leading|least|left|level|like|" + "limit|line|listen|load|local|localtime|localtimestamp|location|lock|lseg|macaddr|mapping|" + "match|maxvalue|minute|minvalue|mode|money|month|move|name|names|national|natural|nchar|next|no|" + "none|not|nothing|notify|notnull|nowait|null|nullif|nulls|numeric|object|of|off|offset|oid|oids|" + "oidvector|on|only|opaque|operator|option|options|or|order|out|outer|over|overlaps|overlay|" + "owned|owner|parser|partial|partition|passing|password|path|pg_attribute|pg_auth_members|" + "pg_authid|pg_class|pg_database|pg_node_tree|pg_proc|pg_type|placing|plans|point|polygon|" + "position|preceding|precision|prepare|prepared|preserve|primary|prior|privileges|" + "procedural|procedure|quote|range|read|real|reassign|recheck|record|recursive|ref|refcursor|" + "references|regclass|regconfig|regdictionary|regoper|regoperator|regproc|regprocedure|" + "regtype|reindex|relative|release|reltime|rename|repeatable|replace|replica|reset|restart|" + "restrict|returning|returns|revoke|right|role|rollback|row|rows|rule|savepoint|schema|scroll|" + "search|second|security|select|sequence|sequences|serializable|server|session|session_user|" + "set|setof|share|show|similar|simple|smallint|smgr|some|stable|standalone|start|statement|" + "statistics|stdin|stdout|storage|strict|strip|substring|symmetric|sysid|system|table|tables|" + "tablespace|temp|template|temporary|text|then|tid|time|timestamp|timestamptz|timetz|" + "tinterval|to|trailing|transaction|treat|trigger|trim|true|truncate|trusted|tsquery|tsvector|" + "txid_snapshot|type|unbounded|uncommitted|unencrypted|union|unique|unknown|unlisten|" + "unlogged|until|update|user|using|uuid|vacuum|valid|validate|validator|value|values|varbit|" + "varchar|variadic|varying|verbose|version|view|void|volatile|when|where|whitespace|window|" + "with|without|work|wrapper|write|xid|xml|xmlattributes|xmlconcat|xmlelement|xmlexists|" + "xmlforest|xmlparse|xmlpi|xmlroot|xmlserialize|year|yes|zone").split("|") ); var builtinFunctions = lang.arrayToMap( ("RI_FKey_cascade_del|RI_FKey_cascade_upd|RI_FKey_check_ins|RI_FKey_check_upd|" + "RI_FKey_noaction_del|RI_FKey_noaction_upd|RI_FKey_restrict_del|RI_FKey_restrict_upd|" + "RI_FKey_setdefault_del|RI_FKey_setdefault_upd|RI_FKey_setnull_del|" + "RI_FKey_setnull_upd|abbrev|abs|abstime|abstimeeq|abstimege|abstimegt|abstimein|abstimele|" + "abstimelt|abstimene|abstimeout|abstimerecv|abstimesend|aclcontains|aclexplode|aclinsert|" + "aclitemeq|aclitemin|aclitemout|aclremove|acos|age|any_in|any_out|anyarray_in|anyarray_out|" + "anyarray_recv|anyarray_send|anyelement_in|anyelement_out|anyenum_in|anyenum_out|" + "anynonarray_in|anynonarray_out|anytextcat|area|areajoinsel|areasel|array_agg|" + "array_agg_finalfn|array_agg_transfn|array_append|array_cat|array_dims|array_eq|" + "array_fill|array_ge|array_gt|array_in|array_larger|array_le|array_length|array_lower|" + "array_lt|array_ndims|array_ne|array_out|array_prepend|array_recv|array_send|" + "array_smaller|array_to_string|array_upper|arraycontained|arraycontains|arrayoverlap|" + "ascii|ascii_to_mic|ascii_to_utf8|asin|atan|atan2|avg|big5_to_euc_tw|big5_to_mic|" + "big5_to_utf8|bit_and|bit_in|bit_length|bit_or|bit_out|bit_recv|bit_send|bitand|bitcat|" + "bitcmp|biteq|bitge|bitgt|bitle|bitlt|bitne|bitnot|bitor|bitshiftleft|bitshiftright|" + "bittypmodin|bittypmodout|bitxor|bool|bool_and|bool_or|booland_statefunc|booleq|boolge|" + "boolgt|boolin|boolle|boollt|boolne|boolor_statefunc|boolout|boolrecv|boolsend|box|" + "box_above|box_above_eq|box_add|box_below|box_below_eq|box_center|box_contain|" + "box_contain_pt|box_contained|box_distance|box_div|box_eq|box_ge|box_gt|box_in|" + "box_intersect|box_le|box_left|box_lt|box_mul|box_out|box_overabove|box_overbelow|" + "box_overlap|box_overleft|box_overright|box_recv|box_right|box_same|box_send|box_sub|" + "bpchar_larger|bpchar_pattern_ge|bpchar_pattern_gt|bpchar_pattern_le|" + "bpchar_pattern_lt|bpchar_smaller|bpcharcmp|bpchareq|bpcharge|bpchargt|bpchariclike|" + "bpcharicnlike|bpcharicregexeq|bpcharicregexne|bpcharin|bpcharle|bpcharlike|bpcharlt|" + "bpcharne|bpcharnlike|bpcharout|bpcharrecv|bpcharregexeq|bpcharregexne|bpcharsend|" + "bpchartypmodin|bpchartypmodout|broadcast|btabstimecmp|btarraycmp|btbeginscan|btboolcmp|" + "btbpchar_pattern_cmp|btbuild|btbuildempty|btbulkdelete|btcharcmp|btcostestimate|" + "btendscan|btfloat48cmp|btfloat4cmp|btfloat84cmp|btfloat8cmp|btgetbitmap|btgettuple|" + "btinsert|btint24cmp|btint28cmp|btint2cmp|btint42cmp|btint48cmp|btint4cmp|btint82cmp|" + "btint84cmp|btint8cmp|btmarkpos|btnamecmp|btoidcmp|btoidvectorcmp|btoptions|btrecordcmp|" + "btreltimecmp|btrescan|btrestrpos|btrim|bttext_pattern_cmp|bttextcmp|bttidcmp|" + "bttintervalcmp|btvacuumcleanup|byteacat|byteacmp|byteaeq|byteage|byteagt|byteain|byteale|" + "bytealike|bytealt|byteane|byteanlike|byteaout|bytearecv|byteasend|cash_cmp|cash_div_cash|" + "cash_div_flt4|cash_div_flt8|cash_div_int2|cash_div_int4|cash_eq|cash_ge|cash_gt|cash_in|" + "cash_le|cash_lt|cash_mi|cash_mul_flt4|cash_mul_flt8|cash_mul_int2|cash_mul_int4|cash_ne|" + "cash_out|cash_pl|cash_recv|cash_send|cash_words|cashlarger|cashsmaller|cbrt|ceil|ceiling|" + "center|char|char_length|character_length|chareq|charge|chargt|charin|charle|charlt|charne|" + "charout|charrecv|charsend|chr|cideq|cidin|cidout|cidr|cidr_in|cidr_out|cidr_recv|cidr_send|" + "cidrecv|cidsend|circle|circle_above|circle_add_pt|circle_below|circle_center|" + "circle_contain|circle_contain_pt|circle_contained|circle_distance|circle_div_pt|" + "circle_eq|circle_ge|circle_gt|circle_in|circle_le|circle_left|circle_lt|circle_mul_pt|" + "circle_ne|circle_out|circle_overabove|circle_overbelow|circle_overlap|circle_overleft|" + "circle_overright|circle_recv|circle_right|circle_same|circle_send|circle_sub_pt|" + "clock_timestamp|close_lb|close_ls|close_lseg|close_pb|close_pl|close_ps|close_sb|" + "close_sl|col_description|concat|concat_ws|contjoinsel|contsel|convert|convert_from|" + "convert_to|corr|cos|cot|count|covar_pop|covar_samp|cstring_in|cstring_out|cstring_recv|" + "cstring_send|cume_dist|current_database|current_query|current_schema|current_schemas|" + "current_setting|current_user|currtid|currtid2|currval|cursor_to_xml|" + "cursor_to_xmlschema|database_to_xml|database_to_xml_and_xmlschema|" + "database_to_xmlschema|date|date_cmp|date_cmp_timestamp|date_cmp_timestamptz|date_eq|" + "date_eq_timestamp|date_eq_timestamptz|date_ge|date_ge_timestamp|date_ge_timestamptz|" + "date_gt|date_gt_timestamp|date_gt_timestamptz|date_in|date_larger|date_le|" + "date_le_timestamp|date_le_timestamptz|date_lt|date_lt_timestamp|date_lt_timestamptz|" + "date_mi|date_mi_interval|date_mii|date_ne|date_ne_timestamp|date_ne_timestamptz|" + "date_out|date_part|date_pl_interval|date_pli|date_recv|date_send|date_smaller|" + "date_trunc|datetime_pl|datetimetz_pl|dcbrt|decode|degrees|dense_rank|dexp|diagonal|" + "diameter|dispell_init|dispell_lexize|dist_cpoly|dist_lb|dist_pb|dist_pc|dist_pl|" + "dist_ppath|dist_ps|dist_sb|dist_sl|div|dlog1|dlog10|domain_in|domain_recv|dpow|dround|" + "dsimple_init|dsimple_lexize|dsnowball_init|dsnowball_lexize|dsqrt|dsynonym_init|" + "dsynonym_lexize|dtrunc|encode|enum_cmp|enum_eq|enum_first|enum_ge|enum_gt|enum_in|" + "enum_larger|enum_last|enum_le|enum_lt|enum_ne|enum_out|enum_range|enum_recv|enum_send|" + "enum_smaller|eqjoinsel|eqsel|euc_cn_to_mic|euc_cn_to_utf8|" + "euc_jis_2004_to_shift_jis_2004|euc_jis_2004_to_utf8|euc_jp_to_mic|euc_jp_to_sjis|" + "euc_jp_to_utf8|euc_kr_to_mic|euc_kr_to_utf8|euc_tw_to_big5|euc_tw_to_mic|" + "euc_tw_to_utf8|every|exp|factorial|family|fdw_handler_in|fdw_handler_out|first_value|" + "float4|float48div|float48eq|float48ge|float48gt|float48le|float48lt|float48mi|float48mul|" + "float48ne|float48pl|float4_accum|float4abs|float4div|float4eq|float4ge|float4gt|float4in|" + "float4larger|float4le|float4lt|float4mi|float4mul|float4ne|float4out|float4pl|float4recv|" + "float4send|float4smaller|float4um|float4up|float8|float84div|float84eq|float84ge|" + "float84gt|float84le|float84lt|float84mi|float84mul|float84ne|float84pl|float8_accum|" + "float8_avg|float8_corr|float8_covar_pop|float8_covar_samp|float8_regr_accum|" + "float8_regr_avgx|float8_regr_avgy|float8_regr_intercept|float8_regr_r2|" + "float8_regr_slope|float8_regr_sxx|float8_regr_sxy|float8_regr_syy|float8_stddev_pop|" + "float8_stddev_samp|float8_var_pop|float8_var_samp|float8abs|float8div|float8eq|" + "float8ge|float8gt|float8in|float8larger|float8le|float8lt|float8mi|float8mul|float8ne|" + "float8out|float8pl|float8recv|float8send|float8smaller|float8um|float8up|floor|" + "flt4_mul_cash|flt8_mul_cash|fmgr_c_validator|fmgr_internal_validator|" + "fmgr_sql_validator|format|format_type|gb18030_to_utf8|gbk_to_utf8|generate_series|" + "generate_subscripts|get_bit|get_byte|get_current_ts_config|getdatabaseencoding|" + "getpgusername|gin_cmp_prefix|gin_cmp_tslexeme|gin_extract_tsquery|" + "gin_extract_tsvector|gin_tsquery_consistent|ginarrayconsistent|ginarrayextract|" + "ginbeginscan|ginbuild|ginbuildempty|ginbulkdelete|gincostestimate|ginendscan|" + "gingetbitmap|gininsert|ginmarkpos|ginoptions|ginqueryarrayextract|ginrescan|" + "ginrestrpos|ginvacuumcleanup|gist_box_compress|gist_box_consistent|" + "gist_box_decompress|gist_box_penalty|gist_box_picksplit|gist_box_same|gist_box_union|" + "gist_circle_compress|gist_circle_consistent|gist_point_compress|" + "gist_point_consistent|gist_point_distance|gist_poly_compress|gist_poly_consistent|" + "gistbeginscan|gistbuild|gistbuildempty|gistbulkdelete|gistcostestimate|gistendscan|" + "gistgetbitmap|gistgettuple|gistinsert|gistmarkpos|gistoptions|gistrescan|gistrestrpos|" + "gistvacuumcleanup|gtsquery_compress|gtsquery_consistent|gtsquery_decompress|" + "gtsquery_penalty|gtsquery_picksplit|gtsquery_same|gtsquery_union|gtsvector_compress|" + "gtsvector_consistent|gtsvector_decompress|gtsvector_penalty|gtsvector_picksplit|" + "gtsvector_same|gtsvector_union|gtsvectorin|gtsvectorout|has_any_column_privilege|" + "has_column_privilege|has_database_privilege|has_foreign_data_wrapper_privilege|" + "has_function_privilege|has_language_privilege|has_schema_privilege|" + "has_sequence_privilege|has_server_privilege|has_table_privilege|" + "has_tablespace_privilege|hash_aclitem|hash_array|hash_numeric|hashbeginscan|" + "hashbpchar|hashbuild|hashbuildempty|hashbulkdelete|hashchar|hashcostestimate|" + "hashendscan|hashenum|hashfloat4|hashfloat8|hashgetbitmap|hashgettuple|hashinet|" + "hashinsert|hashint2|hashint2vector|hashint4|hashint8|hashmacaddr|hashmarkpos|hashname|" + "hashoid|hashoidvector|hashoptions|hashrescan|hashrestrpos|hashtext|hashvacuumcleanup|" + "hashvarlena|height|host|hostmask|iclikejoinsel|iclikesel|icnlikejoinsel|icnlikesel|" + "icregexeqjoinsel|icregexeqsel|icregexnejoinsel|icregexnesel|inet_client_addr|" + "inet_client_port|inet_in|inet_out|inet_recv|inet_send|inet_server_addr|" + "inet_server_port|inetand|inetmi|inetmi_int8|inetnot|inetor|inetpl|initcap|int2|int24div|" + "int24eq|int24ge|int24gt|int24le|int24lt|int24mi|int24mul|int24ne|int24pl|int28div|int28eq|" + "int28ge|int28gt|int28le|int28lt|int28mi|int28mul|int28ne|int28pl|int2_accum|" + "int2_avg_accum|int2_mul_cash|int2_sum|int2abs|int2and|int2div|int2eq|int2ge|int2gt|int2in|" + "int2larger|int2le|int2lt|int2mi|int2mod|int2mul|int2ne|int2not|int2or|int2out|int2pl|" + "int2recv|int2send|int2shl|int2shr|int2smaller|int2um|int2up|int2vectoreq|int2vectorin|" + "int2vectorout|int2vectorrecv|int2vectorsend|int2xor|int4|int42div|int42eq|int42ge|" + "int42gt|int42le|int42lt|int42mi|int42mul|int42ne|int42pl|int48div|int48eq|int48ge|int48gt|" + "int48le|int48lt|int48mi|int48mul|int48ne|int48pl|int4_accum|int4_avg_accum|int4_mul_cash|" + "int4_sum|int4abs|int4and|int4div|int4eq|int4ge|int4gt|int4in|int4inc|int4larger|int4le|" + "int4lt|int4mi|int4mod|int4mul|int4ne|int4not|int4or|int4out|int4pl|int4recv|int4send|" + "int4shl|int4shr|int4smaller|int4um|int4up|int4xor|int8|int82div|int82eq|int82ge|int82gt|" + "int82le|int82lt|int82mi|int82mul|int82ne|int82pl|int84div|int84eq|int84ge|int84gt|int84le|" + "int84lt|int84mi|int84mul|int84ne|int84pl|int8_accum|int8_avg|int8_avg_accum|int8_sum|" + "int8abs|int8and|int8div|int8eq|int8ge|int8gt|int8in|int8inc|int8inc_any|" + "int8inc_float8_float8|int8larger|int8le|int8lt|int8mi|int8mod|int8mul|int8ne|int8not|" + "int8or|int8out|int8pl|int8pl_inet|int8recv|int8send|int8shl|int8shr|int8smaller|int8um|" + "int8up|int8xor|integer_pl_date|inter_lb|inter_sb|inter_sl|internal_in|internal_out|" + "interval_accum|interval_avg|interval_cmp|interval_div|interval_eq|interval_ge|" + "interval_gt|interval_hash|interval_in|interval_larger|interval_le|interval_lt|" + "interval_mi|interval_mul|interval_ne|interval_out|interval_pl|interval_pl_date|" + "interval_pl_time|interval_pl_timestamp|interval_pl_timestamptz|interval_pl_timetz|" + "interval_recv|interval_send|interval_smaller|interval_um|intervaltypmodin|" + "intervaltypmodout|intinterval|isclosed|isfinite|ishorizontal|iso8859_1_to_utf8|" + "iso8859_to_utf8|iso_to_koi8r|iso_to_mic|iso_to_win1251|iso_to_win866|isopen|isparallel|" + "isperp|isvertical|johab_to_utf8|justify_days|justify_hours|justify_interval|" + "koi8r_to_iso|koi8r_to_mic|koi8r_to_utf8|koi8r_to_win1251|koi8r_to_win866|" + "koi8u_to_utf8|lag|language_handler_in|language_handler_out|last_value|lastval|" + "latin1_to_mic|latin2_to_mic|latin2_to_win1250|latin3_to_mic|latin4_to_mic|lead|left|" + "length|like|like_escape|likejoinsel|likesel|line|line_distance|line_eq|line_horizontal|" + "line_in|line_interpt|line_intersect|line_out|line_parallel|line_perp|line_recv|" + "line_send|line_vertical|ln|lo_close|lo_creat|lo_create|lo_export|lo_import|lo_lseek|" + "lo_open|lo_tell|lo_truncate|lo_unlink|log|loread|lower|lowrite|lpad|lseg|lseg_center|" + "lseg_distance|lseg_eq|lseg_ge|lseg_gt|lseg_horizontal|lseg_in|lseg_interpt|" + "lseg_intersect|lseg_le|lseg_length|lseg_lt|lseg_ne|lseg_out|lseg_parallel|lseg_perp|" + "lseg_recv|lseg_send|lseg_vertical|ltrim|macaddr_cmp|macaddr_eq|macaddr_ge|macaddr_gt|" + "macaddr_in|macaddr_le|macaddr_lt|macaddr_ne|macaddr_out|macaddr_recv|macaddr_send|" + "makeaclitem|masklen|max|md5|mic_to_ascii|mic_to_big5|mic_to_euc_cn|mic_to_euc_jp|" + "mic_to_euc_kr|mic_to_euc_tw|mic_to_iso|mic_to_koi8r|mic_to_latin1|mic_to_latin2|" + "mic_to_latin3|mic_to_latin4|mic_to_sjis|mic_to_win1250|mic_to_win1251|mic_to_win866|" + "min|mktinterval|mod|money|mul_d_interval|name|nameeq|namege|namegt|nameiclike|nameicnlike|" + "nameicregexeq|nameicregexne|namein|namele|namelike|namelt|namene|namenlike|nameout|" + "namerecv|nameregexeq|nameregexne|namesend|neqjoinsel|neqsel|netmask|network|network_cmp|" + "network_eq|network_ge|network_gt|network_le|network_lt|network_ne|network_sub|" + "network_subeq|network_sup|network_supeq|nextval|nlikejoinsel|nlikesel|notlike|now|" + "npoints|nth_value|ntile|numeric_abs|numeric_accum|numeric_add|numeric_avg|" + "numeric_avg_accum|numeric_cmp|numeric_div|numeric_div_trunc|numeric_eq|numeric_exp|" + "numeric_fac|numeric_ge|numeric_gt|numeric_in|numeric_inc|numeric_larger|numeric_le|" + "numeric_ln|numeric_log|numeric_lt|numeric_mod|numeric_mul|numeric_ne|numeric_out|" + "numeric_power|numeric_recv|numeric_send|numeric_smaller|numeric_sqrt|" + "numeric_stddev_pop|numeric_stddev_samp|numeric_sub|numeric_uminus|numeric_uplus|" + "numeric_var_pop|numeric_var_samp|numerictypmodin|numerictypmodout|numnode|" + "obj_description|octet_length|oid|oideq|oidge|oidgt|oidin|oidlarger|oidle|oidlt|oidne|oidout|" + "oidrecv|oidsend|oidsmaller|oidvectoreq|oidvectorge|oidvectorgt|oidvectorin|oidvectorle|" + "oidvectorlt|oidvectorne|oidvectorout|oidvectorrecv|oidvectorsend|oidvectortypes|on_pb|" + "on_pl|on_ppath|on_ps|on_sb|on_sl|opaque_in|opaque_out|overlaps|overlay|path|path_add|" + "path_add_pt|path_center|path_contain_pt|path_distance|path_div_pt|path_in|path_inter|" + "path_length|path_mul_pt|path_n_eq|path_n_ge|path_n_gt|path_n_le|path_n_lt|path_npoints|" + "path_out|path_recv|path_send|path_sub_pt|pclose|percent_rank|pg_advisory_lock|" + "pg_advisory_lock_shared|pg_advisory_unlock|pg_advisory_unlock_all|" + "pg_advisory_unlock_shared|pg_advisory_xact_lock|pg_advisory_xact_lock_shared|" + "pg_available_extension_versions|pg_available_extensions|pg_backend_pid|" + "pg_cancel_backend|pg_char_to_encoding|pg_client_encoding|pg_collation_is_visible|" + "pg_column_size|pg_conf_load_time|pg_conversion_is_visible|pg_create_restore_point|" + "pg_current_xlog_insert_location|pg_current_xlog_location|pg_cursor|pg_database_size|" + "pg_describe_object|pg_encoding_max_length|pg_encoding_to_char|" + "pg_extension_config_dump|pg_extension_update_paths|pg_function_is_visible|" + "pg_get_constraintdef|pg_get_expr|pg_get_function_arguments|" + "pg_get_function_identity_arguments|pg_get_function_result|pg_get_functiondef|" + "pg_get_indexdef|pg_get_keywords|pg_get_ruledef|pg_get_serial_sequence|" + "pg_get_triggerdef|pg_get_userbyid|pg_get_viewdef|pg_has_role|pg_indexes_size|" + "pg_is_in_recovery|pg_is_other_temp_schema|pg_is_xlog_replay_paused|" + "pg_last_xact_replay_timestamp|pg_last_xlog_receive_location|" + "pg_last_xlog_replay_location|pg_listening_channels|pg_lock_status|pg_ls_dir|" + "pg_my_temp_schema|pg_node_tree_in|pg_node_tree_out|pg_node_tree_recv|" + "pg_node_tree_send|pg_notify|pg_opclass_is_visible|pg_operator_is_visible|" + "pg_options_to_table|pg_postmaster_start_time|pg_prepared_statement|pg_prepared_xact|" + "pg_read_binary_file|pg_read_file|pg_relation_filenode|pg_relation_filepath|" + "pg_relation_size|pg_reload_conf|pg_rotate_logfile|pg_sequence_parameters|" + "pg_show_all_settings|pg_size_pretty|pg_sleep|pg_start_backup|pg_stat_clear_snapshot|" + "pg_stat_file|pg_stat_get_activity|pg_stat_get_analyze_count|" + "pg_stat_get_autoanalyze_count|pg_stat_get_autovacuum_count|" + "pg_stat_get_backend_activity|pg_stat_get_backend_activity_start|" + "pg_stat_get_backend_client_addr|pg_stat_get_backend_client_port|" + "pg_stat_get_backend_dbid|pg_stat_get_backend_idset|pg_stat_get_backend_pid|" + "pg_stat_get_backend_start|pg_stat_get_backend_userid|pg_stat_get_backend_waiting|" + "pg_stat_get_backend_xact_start|pg_stat_get_bgwriter_buf_written_checkpoints|" + "pg_stat_get_bgwriter_buf_written_clean|pg_stat_get_bgwriter_maxwritten_clean|" + "pg_stat_get_bgwriter_requested_checkpoints|pg_stat_get_bgwriter_stat_reset_time|" + "pg_stat_get_bgwriter_timed_checkpoints|pg_stat_get_blocks_fetched|" + "pg_stat_get_blocks_hit|pg_stat_get_buf_alloc|pg_stat_get_buf_fsync_backend|" + "pg_stat_get_buf_written_backend|pg_stat_get_db_blocks_fetched|" + "pg_stat_get_db_blocks_hit|pg_stat_get_db_conflict_all|" + "pg_stat_get_db_conflict_bufferpin|pg_stat_get_db_conflict_lock|" + "pg_stat_get_db_conflict_snapshot|pg_stat_get_db_conflict_startup_deadlock|" + "pg_stat_get_db_conflict_tablespace|pg_stat_get_db_numbackends|" + "pg_stat_get_db_stat_reset_time|pg_stat_get_db_tuples_deleted|" + "pg_stat_get_db_tuples_fetched|pg_stat_get_db_tuples_inserted|" + "pg_stat_get_db_tuples_returned|pg_stat_get_db_tuples_updated|" + "pg_stat_get_db_xact_commit|pg_stat_get_db_xact_rollback|pg_stat_get_dead_tuples|" + "pg_stat_get_function_calls|pg_stat_get_function_self_time|" + "pg_stat_get_function_time|pg_stat_get_last_analyze_time|" + "pg_stat_get_last_autoanalyze_time|pg_stat_get_last_autovacuum_time|" + "pg_stat_get_last_vacuum_time|pg_stat_get_live_tuples|pg_stat_get_numscans|" + "pg_stat_get_tuples_deleted|pg_stat_get_tuples_fetched|" + "pg_stat_get_tuples_hot_updated|pg_stat_get_tuples_inserted|" + "pg_stat_get_tuples_returned|pg_stat_get_tuples_updated|pg_stat_get_vacuum_count|" + "pg_stat_get_wal_senders|pg_stat_get_xact_blocks_fetched|" + "pg_stat_get_xact_blocks_hit|pg_stat_get_xact_function_calls|" + "pg_stat_get_xact_function_self_time|pg_stat_get_xact_function_time|" + "pg_stat_get_xact_numscans|pg_stat_get_xact_tuples_deleted|" + "pg_stat_get_xact_tuples_fetched|pg_stat_get_xact_tuples_hot_updated|" + "pg_stat_get_xact_tuples_inserted|pg_stat_get_xact_tuples_returned|" + "pg_stat_get_xact_tuples_updated|pg_stat_reset|pg_stat_reset_shared|" + "pg_stat_reset_single_function_counters|pg_stat_reset_single_table_counters|" + "pg_stop_backup|pg_switch_xlog|pg_table_is_visible|pg_table_size|" + "pg_tablespace_databases|pg_tablespace_size|pg_terminate_backend|pg_timezone_abbrevs|" + "pg_timezone_names|pg_total_relation_size|pg_try_advisory_lock|" + "pg_try_advisory_lock_shared|pg_try_advisory_xact_lock|" + "pg_try_advisory_xact_lock_shared|pg_ts_config_is_visible|pg_ts_dict_is_visible|" + "pg_ts_parser_is_visible|pg_ts_template_is_visible|pg_type_is_visible|pg_typeof|" + "pg_xlog_replay_pause|pg_xlog_replay_resume|pg_xlogfile_name|pg_xlogfile_name_offset|" + "pi|plainto_tsquery|plpgsql_call_handler|plpgsql_inline_handler|plpgsql_validator|" + "point|point_above|point_add|point_below|point_distance|point_div|point_eq|point_horiz|" + "point_in|point_left|point_mul|point_ne|point_out|point_recv|point_right|point_send|" + "point_sub|point_vert|poly_above|poly_below|poly_center|poly_contain|poly_contain_pt|" + "poly_contained|poly_distance|poly_in|poly_left|poly_npoints|poly_out|poly_overabove|" + "poly_overbelow|poly_overlap|poly_overleft|poly_overright|poly_recv|poly_right|" + "poly_same|poly_send|polygon|popen|position|positionjoinsel|positionsel|" + "postgresql_fdw_validator|pow|power|prsd_end|prsd_headline|prsd_lextype|prsd_nexttoken|" + "prsd_start|pt_contained_circle|pt_contained_poly|query_to_xml|" + "query_to_xml_and_xmlschema|query_to_xmlschema|querytree|quote_ident|quote_literal|" + "quote_nullable|radians|radius|random|rank|record_eq|record_ge|record_gt|record_in|" + "record_le|record_lt|record_ne|record_out|record_recv|record_send|regclass|regclassin|" + "regclassout|regclassrecv|regclasssend|regconfigin|regconfigout|regconfigrecv|" + "regconfigsend|regdictionaryin|regdictionaryout|regdictionaryrecv|regdictionarysend|" + "regexeqjoinsel|regexeqsel|regexnejoinsel|regexnesel|regexp_matches|regexp_replace|" + "regexp_split_to_array|regexp_split_to_table|regoperatorin|regoperatorout|" + "regoperatorrecv|regoperatorsend|regoperin|regoperout|regoperrecv|regopersend|" + "regprocedurein|regprocedureout|regprocedurerecv|regproceduresend|regprocin|regprocout|" + "regprocrecv|regprocsend|regr_avgx|regr_avgy|regr_count|regr_intercept|regr_r2|" + "regr_slope|regr_sxx|regr_sxy|regr_syy|regtypein|regtypeout|regtyperecv|regtypesend|" + "reltime|reltimeeq|reltimege|reltimegt|reltimein|reltimele|reltimelt|reltimene|reltimeout|" + "reltimerecv|reltimesend|repeat|replace|reverse|right|round|row_number|rpad|rtrim|" + "scalargtjoinsel|scalargtsel|scalarltjoinsel|scalarltsel|schema_to_xml|" + "schema_to_xml_and_xmlschema|schema_to_xmlschema|session_user|set_bit|set_byte|" + "set_config|set_masklen|setseed|setval|setweight|shell_in|shell_out|" + "shift_jis_2004_to_euc_jis_2004|shift_jis_2004_to_utf8|shobj_description|sign|" + "similar_escape|sin|sjis_to_euc_jp|sjis_to_mic|sjis_to_utf8|slope|smgreq|smgrin|smgrne|" + "smgrout|split_part|sqrt|statement_timestamp|stddev|stddev_pop|stddev_samp|string_agg|" + "string_agg_finalfn|string_agg_transfn|string_to_array|strip|strpos|substr|substring|sum|" + "suppress_redundant_updates_trigger|table_to_xml|table_to_xml_and_xmlschema|" + "table_to_xmlschema|tan|text|text_ge|text_gt|text_larger|text_le|text_lt|text_pattern_ge|" + "text_pattern_gt|text_pattern_le|text_pattern_lt|text_smaller|textanycat|textcat|texteq|" + "texticlike|texticnlike|texticregexeq|texticregexne|textin|textlen|textlike|textne|" + "textnlike|textout|textrecv|textregexeq|textregexne|textsend|thesaurus_init|" + "thesaurus_lexize|tideq|tidge|tidgt|tidin|tidlarger|tidle|tidlt|tidne|tidout|tidrecv|tidsend|" + "tidsmaller|time_cmp|time_eq|time_ge|time_gt|time_hash|time_in|time_larger|time_le|time_lt|" + "time_mi_interval|time_mi_time|time_ne|time_out|time_pl_interval|time_recv|time_send|" + "time_smaller|timedate_pl|timemi|timenow|timeofday|timepl|timestamp_cmp|" + "timestamp_cmp_date|timestamp_cmp_timestamptz|timestamp_eq|timestamp_eq_date|" + "timestamp_eq_timestamptz|timestamp_ge|timestamp_ge_date|timestamp_ge_timestamptz|" + "timestamp_gt|timestamp_gt_date|timestamp_gt_timestamptz|timestamp_hash|timestamp_in|" + "timestamp_larger|timestamp_le|timestamp_le_date|timestamp_le_timestamptz|" + "timestamp_lt|timestamp_lt_date|timestamp_lt_timestamptz|timestamp_mi|" + "timestamp_mi_interval|timestamp_ne|timestamp_ne_date|timestamp_ne_timestamptz|" + "timestamp_out|timestamp_pl_interval|timestamp_recv|timestamp_send|timestamp_smaller|" + "timestamptypmodin|timestamptypmodout|timestamptz_cmp|timestamptz_cmp_date|" + "timestamptz_cmp_timestamp|timestamptz_eq|timestamptz_eq_date|" + "timestamptz_eq_timestamp|timestamptz_ge|timestamptz_ge_date|" + "timestamptz_ge_timestamp|timestamptz_gt|timestamptz_gt_date|" + "timestamptz_gt_timestamp|timestamptz_in|timestamptz_larger|timestamptz_le|" + "timestamptz_le_date|timestamptz_le_timestamp|timestamptz_lt|timestamptz_lt_date|" + "timestamptz_lt_timestamp|timestamptz_mi|timestamptz_mi_interval|timestamptz_ne|" + "timestamptz_ne_date|timestamptz_ne_timestamp|timestamptz_out|" + "timestamptz_pl_interval|timestamptz_recv|timestamptz_send|timestamptz_smaller|" + "timestamptztypmodin|timestamptztypmodout|timetypmodin|timetypmodout|timetz_cmp|" + "timetz_eq|timetz_ge|timetz_gt|timetz_hash|timetz_in|timetz_larger|timetz_le|timetz_lt|" + "timetz_mi_interval|timetz_ne|timetz_out|timetz_pl_interval|timetz_recv|timetz_send|" + "timetz_smaller|timetzdate_pl|timetztypmodin|timetztypmodout|timezone|tinterval|" + "tintervalct|tintervalend|tintervaleq|tintervalge|tintervalgt|tintervalin|tintervalle|" + "tintervalleneq|tintervallenge|tintervallengt|tintervallenle|tintervallenlt|" + "tintervallenne|tintervallt|tintervalne|tintervalout|tintervalov|tintervalrecv|" + "tintervalrel|tintervalsame|tintervalsend|tintervalstart|to_ascii|to_char|to_date|to_hex|" + "to_number|to_timestamp|to_tsquery|to_tsvector|transaction_timestamp|translate|" + "trigger_in|trigger_out|trunc|ts_debug|ts_headline|ts_lexize|ts_match_qv|ts_match_tq|" + "ts_match_tt|ts_match_vq|ts_parse|ts_rank|ts_rank_cd|ts_rewrite|ts_stat|ts_token_type|" + "ts_typanalyze|tsmatchjoinsel|tsmatchsel|tsq_mcontained|tsq_mcontains|tsquery_and|" + "tsquery_cmp|tsquery_eq|tsquery_ge|tsquery_gt|tsquery_le|tsquery_lt|tsquery_ne|" + "tsquery_not|tsquery_or|tsqueryin|tsqueryout|tsqueryrecv|tsquerysend|tsvector_cmp|" + "tsvector_concat|tsvector_eq|tsvector_ge|tsvector_gt|tsvector_le|tsvector_lt|" + "tsvector_ne|tsvector_update_trigger|tsvector_update_trigger_column|tsvectorin|" + "tsvectorout|tsvectorrecv|tsvectorsend|txid_current|txid_current_snapshot|" + "txid_snapshot_in|txid_snapshot_out|txid_snapshot_recv|txid_snapshot_send|" + "txid_snapshot_xip|txid_snapshot_xmax|txid_snapshot_xmin|txid_visible_in_snapshot|" + "uhc_to_utf8|unique_key_recheck|unknownin|unknownout|unknownrecv|unknownsend|unnest|" + "upper|utf8_to_ascii|utf8_to_big5|utf8_to_euc_cn|utf8_to_euc_jis_2004|utf8_to_euc_jp|" + "utf8_to_euc_kr|utf8_to_euc_tw|utf8_to_gb18030|utf8_to_gbk|utf8_to_iso8859|" + "utf8_to_iso8859_1|utf8_to_johab|utf8_to_koi8r|utf8_to_koi8u|utf8_to_shift_jis_2004|" + "utf8_to_sjis|utf8_to_uhc|utf8_to_win|uuid_cmp|uuid_eq|uuid_ge|uuid_gt|uuid_hash|uuid_in|" + "uuid_le|uuid_lt|uuid_ne|uuid_out|uuid_recv|uuid_send|var_pop|var_samp|varbit_in|" + "varbit_out|varbit_recv|varbit_send|varbitcmp|varbiteq|varbitge|varbitgt|varbitle|" + "varbitlt|varbitne|varbittypmodin|varbittypmodout|varcharin|varcharout|varcharrecv|" + "varcharsend|varchartypmodin|varchartypmodout|variance|version|void_in|void_out|" + "void_recv|void_send|width|width_bucket|win1250_to_latin2|win1250_to_mic|win1251_to_iso|" + "win1251_to_koi8r|win1251_to_mic|win1251_to_win866|win866_to_iso|win866_to_koi8r|" + "win866_to_mic|win866_to_win1251|win_to_utf8|xideq|xideqint4|xidin|xidout|xidrecv|xidsend|" + "xml|xml_in|xml_is_well_formed|xml_is_well_formed_content|xml_is_well_formed_document|" + "xml_out|xml_recv|xml_send|xmlagg|xmlcomment|xmlconcat2|xmlexists|xmlvalidate|xpath|" + "xpath_exists").split("|") ); var sqlRules = [ { token : "string", // single line string -- assume dollar strings if multi-line for now regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "variable.language", // pg identifier regex : '".*?"' }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : function(value) { value = value.toLowerCase(); if (keywords.hasOwnProperty(value)) { return "keyword"; } else if (builtinFunctions.hasOwnProperty(value)) { return "support.function"; } else { return "identifier"; } }, regex : "[a-zA-Z_][a-zA-Z0-9_$]*\\b" // TODO - Unicode in identifiers }, { token : "keyword.operator", regex : "!|!!|!~|!~\\*|!~~|!~~\\*|#|##|#<|#<=|#<>|#=|#>|#>=|%|\\&|\\&\\&|\\&<|\\&<\\||\\&>|\\*|\\+|" + "\\-|/|<|<#>|<\\->|<<|<<=|<<\\||<=|<>|<\\?>|<@|<\\^|=|>|>=|>>|>>=|>\\^|\\?#|\\?\\-|\\?\\-\\||" + "\\?\\||\\?\\|\\||@|@\\-@|@>|@@|@@@|\\^|\\||\\|\\&>|\\|/|\\|>>|\\|\\||\\|\\|/|~|~\\*|~<=~|~<~|" + "~=|~>=~|~>~|~~|~~\\*" }, { token : "paren.lparen", regex : "[\\(]" }, { token : "paren.rparen", regex : "[\\)]" }, { token : "text", regex : "\\s+" } ]; this.$rules = { "start" : [ { token : "comment", regex : "--.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi-line comment merge : true, regex : "\\/\\*", next : "comment" },{ token : "keyword.statementBegin", regex : "^[a-zA-Z]+", // Could enumerate starting keywords but this allows things to work when new statements are added. next : "statement" },{ token : "support.buildin", // psql directive regex : "^\\\\[\\S]+.*$" } ], "statement" : [ { token : "comment", regex : "--.*$" }, { token : "comment", // multi-line comment merge : true, regex : "\\/\\*", next : "commentStatement" }, { token : "statementEnd", regex : ";", next : "start" }, { token : "string", // perl, python, tcl are in the pg default dist (no tcl highlighter) regex : "\\$perl\\$", next : "perl-start" }, { token : "string", regex : "\\$python\\$", next : "python-start" },{ token : "string", regex : "\\$[\\w_0-9]*\\$$", // dollar quote at the end of a line next : "dollarSql" }, { token : "string", regex : "\\$[\\w_0-9]*\\$", next : "dollarStatementString" } ].concat(sqlRules), "dollarSql" : [ { token : "comment", regex : "--.*$" }, { token : "comment", // multi-line comment merge : true, regex : "\\/\\*", next : "commentDollarSql" }, { token : "string", // end quoting with dollar at the start of a line regex : "^\\$[\\w_0-9]*\\$", next : "statement" }, { token : "string", regex : "\\$[\\w_0-9]*\\$", next : "dollarSqlString" } ].concat(sqlRules), "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "commentStatement" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "statement" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "commentDollarSql" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "dollarSql" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "dollarStatementString" : [ { token : "string", // closing dollarstring regex : ".*?\\$[\\w_0-9]*\\$", next : "statement" }, { token : "string", // dollarstring spanning whole line merge : true, regex : ".+" } ], "dollarSqlString" : [ { token : "string", // closing dollarstring regex : ".*?\\$[\\w_0-9]*\\$", next : "dollarSql" }, { token : "string", // dollarstring spanning whole line merge : true, regex : ".+" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); this.embedRules(PerlHighlightRules, "perl-", [{token : "string", regex : "\\$perl\\$", next : "statement"}]); this.embedRules(PythonHighlightRules, "python-", [{token : "string", regex : "\\$python\\$", next : "statement"}]); }; oop.inherits(PgsqlHighlightRules, TextHighlightRules); exports.PgsqlHighlightRules = PgsqlHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/perl_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PerlHighlightRules = function() { var keywords = lang.arrayToMap( ("base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|" + "no|package|parent|redo|require|scalar|sub|unless|until|while|use|vars").split("|") ); var buildinConstants = lang.arrayToMap( ("ARGV|ENV|INC|SIG").split("|") ); var builtinFunctions = lang.arrayToMap( ("getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|" + "gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|" + "getpeername|setpriority|getprotoent|setprotoent|getpriority|" + "endprotoent|getservent|setservent|endservent|sethostent|socketpair|" + "getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|" + "localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|" + "closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|" + "shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|" + "dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|" + "setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|" + "lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|" + "waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|" + "chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|" + "unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|" + "length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|" + "undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|" + "sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|" + "BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|" + "join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|" + "keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|" + "eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|" + "map|die|uc|lc|do").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0x[0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(PerlHighlightRules, TextHighlightRules); exports.PerlHighlightRules = PerlHighlightRules; }); define('ace/mode/python_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PythonHighlightRules = function() { var keywords = lang.arrayToMap( ("and|as|assert|break|class|continue|def|del|elif|else|except|exec|" + "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" + "raise|return|try|while|with|yield").split("|") ); var builtinConstants = lang.arrayToMap( ("True|False|None|NotImplemented|Ellipsis|__debug__").split("|") ); var builtinFunctions = lang.arrayToMap( ("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" + "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" + "binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" + "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" + "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" + "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" + "__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" + "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern").split("|") ); var futureReserved = lang.arrayToMap( ("").split("|") ); var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?"; var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var octInteger = "(?:0[oO]?[0-7]+)"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var binInteger = "(?:0[bB][01]+)"; var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; var exponent = "(?:[eE][+-]?\\d+)"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string", // """ string regex : strPre + '"{3}(?:[^\\\\]|\\\\.)*?"{3}' }, { token : "string", // multi line """ string start merge : true, regex : strPre + '"{3}.*$', next : "qqstring" }, { token : "string", // " string regex : strPre + '"(?:[^\\\\]|\\\\.)*?"' }, { token : "string", // ''' string regex : strPre + "'{3}(?:[^\\\\]|\\\\.)*?'{3}" }, { token : "string", // multi line ''' string start merge : true, regex : strPre + "'{3}.*$", next : "qstring" }, { token : "string", // ' string regex : strPre + "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // imaginary regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // long integer regex : integer + "[lL]\\b" }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, 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+" } ], "qqstring" : [ { token : "string", // multi line """ string end regex : '(?:[^\\\\]|\\\\.)*?"{3}', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", // multi line ''' string end regex : "(?:[^\\\\]|\\\\.)*?'{3}", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(PythonHighlightRules, TextHighlightRules); exports.PythonHighlightRules = PythonHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-pgsql.js
JavaScript
asf20
55,509
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * André Fiedler <fiedler dot andre a t gmail dot com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/php', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/php_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var PhpHighlightRules = require("./php_highlight_rules").PhpHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new PhpHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/php_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PhpHighlightRules = function() { var docComment = DocCommentHighlightRules; // http://php.net/quickref.php var builtinFunctions = lang.arrayToMap( ('abs|acos|acosh|addcslashes|addslashes|aggregate|aggregate_info|aggregate_methods|aggregate_methods_by_list|aggregate_methods_by_regexp|' + 'aggregate_properties|aggregate_properties_by_list|aggregate_properties_by_regexp|aggregation_info|amqpconnection|amqpexchange|amqpqueue|' + 'apache_child_terminate|apache_get_modules|apache_get_version|apache_getenv|apache_lookup_uri|apache_note|apache_request_headers|' + 'apache_reset_timeout|apache_response_headers|apache_setenv|apc_add|apc_bin_dump|apc_bin_dumpfile|apc_bin_load|apc_bin_loadfile|' + 'apc_cache_info|apc_cas|apc_clear_cache|apc_compile_file|apc_dec|apc_define_constants|apc_delete|apc_delete_file|apc_exists|apc_fetch|' + 'apc_inc|apc_load_constants|apc_sma_info|apc_store|apciterator|apd_breakpoint|apd_callstack|apd_clunk|apd_continue|apd_croak|' + 'apd_dump_function_table|apd_dump_persistent_resources|apd_dump_regular_resources|apd_echo|apd_get_active_symbols|apd_set_pprof_trace|' + 'apd_set_session|apd_set_session_trace|apd_set_session_trace_socket|appenditerator|array|array_change_key_case|array_chunk|array_combine|' + 'array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_fill_keys|array_filter|' + 'array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|' + 'array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|' + 'array_reduce|array_replace|array_replace_recursive|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|' + 'array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|' + 'array_values|array_walk|array_walk_recursive|arrayaccess|arrayiterator|arrayobject|arsort|asin|asinh|asort|assert|assert_options|atan|' + 'atan2|atanh|audioproperties|badfunctioncallexception|badmethodcallexception|base64_decode|base64_encode|base_convert|basename|' + 'bbcode_add_element|bbcode_add_smiley|bbcode_create|bbcode_destroy|bbcode_parse|bbcode_set_arg_parser|bbcode_set_flags|bcadd|bccomp|bcdiv|' + 'bcmod|bcmul|bcompiler_load|bcompiler_load_exe|bcompiler_parse_class|bcompiler_read|bcompiler_write_class|bcompiler_write_constant|' + 'bcompiler_write_exe_footer|bcompiler_write_file|bcompiler_write_footer|bcompiler_write_function|bcompiler_write_functions_from_file|' + 'bcompiler_write_header|bcompiler_write_included_filename|bcpow|bcpowmod|bcscale|bcsqrt|bcsub|bin2hex|bind_textdomain_codeset|bindec|' + 'bindtextdomain|bson_decode|bson_encode|bumpValue|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|' + 'cachingiterator|cairo|cairo_create|cairo_font_face_get_type|cairo_font_face_status|cairo_font_options_create|cairo_font_options_equal|' + 'cairo_font_options_get_antialias|cairo_font_options_get_hint_metrics|cairo_font_options_get_hint_style|' + 'cairo_font_options_get_subpixel_order|cairo_font_options_hash|cairo_font_options_merge|cairo_font_options_set_antialias|' + 'cairo_font_options_set_hint_metrics|cairo_font_options_set_hint_style|cairo_font_options_set_subpixel_order|cairo_font_options_status|' + 'cairo_format_stride_for_width|cairo_image_surface_create|cairo_image_surface_create_for_data|cairo_image_surface_create_from_png|' + 'cairo_image_surface_get_data|cairo_image_surface_get_format|cairo_image_surface_get_height|cairo_image_surface_get_stride|' + 'cairo_image_surface_get_width|cairo_matrix_create_scale|cairo_matrix_create_translate|cairo_matrix_invert|cairo_matrix_multiply|' + 'cairo_matrix_rotate|cairo_matrix_transform_distance|cairo_matrix_transform_point|cairo_matrix_translate|cairo_pattern_add_color_stop_rgb|' + 'cairo_pattern_add_color_stop_rgba|cairo_pattern_create_for_surface|cairo_pattern_create_linear|cairo_pattern_create_radial|' + 'cairo_pattern_create_rgb|cairo_pattern_create_rgba|cairo_pattern_get_color_stop_count|cairo_pattern_get_color_stop_rgba|' + 'cairo_pattern_get_extend|cairo_pattern_get_filter|cairo_pattern_get_linear_points|cairo_pattern_get_matrix|' + 'cairo_pattern_get_radial_circles|cairo_pattern_get_rgba|cairo_pattern_get_surface|cairo_pattern_get_type|cairo_pattern_set_extend|' + 'cairo_pattern_set_filter|cairo_pattern_set_matrix|cairo_pattern_status|cairo_pdf_surface_create|cairo_pdf_surface_set_size|' + 'cairo_ps_get_levels|cairo_ps_level_to_string|cairo_ps_surface_create|cairo_ps_surface_dsc_begin_page_setup|' + 'cairo_ps_surface_dsc_begin_setup|cairo_ps_surface_dsc_comment|cairo_ps_surface_get_eps|cairo_ps_surface_restrict_to_level|' + 'cairo_ps_surface_set_eps|cairo_ps_surface_set_size|cairo_scaled_font_create|cairo_scaled_font_extents|cairo_scaled_font_get_ctm|' + 'cairo_scaled_font_get_font_face|cairo_scaled_font_get_font_matrix|cairo_scaled_font_get_font_options|cairo_scaled_font_get_scale_matrix|' + 'cairo_scaled_font_get_type|cairo_scaled_font_glyph_extents|cairo_scaled_font_status|cairo_scaled_font_text_extents|' + 'cairo_surface_copy_page|cairo_surface_create_similar|cairo_surface_finish|cairo_surface_flush|cairo_surface_get_content|' + 'cairo_surface_get_device_offset|cairo_surface_get_font_options|cairo_surface_get_type|cairo_surface_mark_dirty|' + 'cairo_surface_mark_dirty_rectangle|cairo_surface_set_device_offset|cairo_surface_set_fallback_resolution|cairo_surface_show_page|' + 'cairo_surface_status|cairo_surface_write_to_png|cairo_svg_surface_create|cairo_svg_surface_restrict_to_version|' + 'cairo_svg_version_to_string|cairoantialias|cairocontent|cairocontext|cairoexception|cairoextend|cairofillrule|cairofilter|cairofontface|' + 'cairofontoptions|cairofontslant|cairofonttype|cairofontweight|cairoformat|cairogradientpattern|cairohintmetrics|cairohintstyle|' + 'cairoimagesurface|cairolineargradient|cairolinecap|cairolinejoin|cairomatrix|cairooperator|cairopath|cairopattern|cairopatterntype|' + 'cairopdfsurface|cairopslevel|cairopssurface|cairoradialgradient|cairoscaledfont|cairosolidpattern|cairostatus|cairosubpixelorder|' + 'cairosurface|cairosurfacepattern|cairosurfacetype|cairosvgsurface|cairosvgversion|cairotoyfontface|cal_days_in_month|cal_from_jd|cal_info|' + 'cal_to_jd|calcul_hmac|calculhmac|call_user_func|call_user_func_array|call_user_method|call_user_method_array|callbackfilteriterator|ceil|' + 'chdb|chdb_create|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_alias|class_exists|class_implements|' + 'class_parents|classkit_import|classkit_method_add|classkit_method_copy|classkit_method_redefine|classkit_method_remove|' + 'classkit_method_rename|clearstatcache|clone|closedir|closelog|collator|com|com_addref|com_create_guid|com_event_sink|com_get|' + 'com_get_active_object|com_invoke|com_isenum|com_load|com_load_typelib|com_message_pump|com_print_typeinfo|com_propget|com_propput|' + 'com_propset|com_release|com_set|compact|connection_aborted|connection_status|connection_timeout|constant|construct|construct|construct|' + 'convert_cyr_string|convert_uudecode|convert_uuencode|copy|cos|cosh|count|count_chars|countable|counter_bump|counter_bump_value|' + 'counter_create|counter_get|counter_get_meta|counter_get_named|counter_get_value|counter_reset|counter_reset_value|crack_check|' + 'crack_closedict|crack_getlastmessage|crack_opendict|crc32|create_function|crypt|ctype_alnum|ctype_alpha|ctype_cntrl|ctype_digit|' + 'ctype_graph|ctype_lower|ctype_print|ctype_punct|ctype_space|ctype_upper|ctype_xdigit|cubrid_affected_rows|cubrid_bind|' + 'cubrid_client_encoding|cubrid_close|cubrid_close_prepare|cubrid_close_request|cubrid_col_get|cubrid_col_size|cubrid_column_names|' + 'cubrid_column_types|cubrid_commit|cubrid_connect|cubrid_connect_with_url|cubrid_current_oid|cubrid_data_seek|cubrid_db_name|' + 'cubrid_disconnect|cubrid_drop|cubrid_errno|cubrid_error|cubrid_error_code|cubrid_error_code_facility|cubrid_error_msg|cubrid_execute|' + 'cubrid_fetch|cubrid_fetch_array|cubrid_fetch_assoc|cubrid_fetch_field|cubrid_fetch_lengths|cubrid_fetch_object|cubrid_fetch_row|' + 'cubrid_field_flags|cubrid_field_len|cubrid_field_name|cubrid_field_seek|cubrid_field_table|cubrid_field_type|cubrid_free_result|' + 'cubrid_get|cubrid_get_autocommit|cubrid_get_charset|cubrid_get_class_name|cubrid_get_client_info|cubrid_get_db_parameter|' + 'cubrid_get_server_info|cubrid_insert_id|cubrid_is_instance|cubrid_list_dbs|cubrid_load_from_glo|cubrid_lob_close|cubrid_lob_export|' + 'cubrid_lob_get|cubrid_lob_send|cubrid_lob_size|cubrid_lock_read|cubrid_lock_write|cubrid_move_cursor|cubrid_new_glo|cubrid_next_result|' + 'cubrid_num_cols|cubrid_num_fields|cubrid_num_rows|cubrid_ping|cubrid_prepare|cubrid_put|cubrid_query|cubrid_real_escape_string|' + 'cubrid_result|cubrid_rollback|cubrid_save_to_glo|cubrid_schema|cubrid_send_glo|cubrid_seq_drop|cubrid_seq_insert|cubrid_seq_put|' + 'cubrid_set_add|cubrid_set_autocommit|cubrid_set_db_parameter|cubrid_set_drop|cubrid_unbuffered_query|cubrid_version|curl_close|' + 'curl_copy_handle|curl_errno|curl_error|curl_exec|curl_getinfo|curl_init|curl_multi_add_handle|curl_multi_close|curl_multi_exec|' + 'curl_multi_getcontent|curl_multi_info_read|curl_multi_init|curl_multi_remove_handle|curl_multi_select|curl_setopt|curl_setopt_array|' + 'curl_version|current|cyrus_authenticate|cyrus_bind|cyrus_close|cyrus_connect|cyrus_query|cyrus_unbind|date|date_add|date_create|' + 'date_create_from_format|date_date_set|date_default_timezone_get|date_default_timezone_set|date_diff|date_format|date_get_last_errors|' + 'date_interval_create_from_date_string|date_interval_format|date_isodate_set|date_modify|date_offset_get|date_parse|date_parse_from_format|' + 'date_sub|date_sun_info|date_sunrise|date_sunset|date_time_set|date_timestamp_get|date_timestamp_set|date_timezone_get|date_timezone_set|' + 'dateinterval|dateperiod|datetime|datetimezone|db2_autocommit|db2_bind_param|db2_client_info|db2_close|db2_column_privileges|db2_columns|' + 'db2_commit|db2_conn_error|db2_conn_errormsg|db2_connect|db2_cursor_type|db2_escape_string|db2_exec|db2_execute|db2_fetch_array|' + 'db2_fetch_assoc|db2_fetch_both|db2_fetch_object|db2_fetch_row|db2_field_display_size|db2_field_name|db2_field_num|db2_field_precision|' + 'db2_field_scale|db2_field_type|db2_field_width|db2_foreign_keys|db2_free_result|db2_free_stmt|db2_get_option|db2_last_insert_id|' + 'db2_lob_read|db2_next_result|db2_num_fields|db2_num_rows|db2_pclose|db2_pconnect|db2_prepare|db2_primary_keys|db2_procedure_columns|' + 'db2_procedures|db2_result|db2_rollback|db2_server_info|db2_set_option|db2_special_columns|db2_statistics|db2_stmt_error|db2_stmt_errormsg|' + 'db2_table_privileges|db2_tables|dba_close|dba_delete|dba_exists|dba_fetch|dba_firstkey|dba_handlers|dba_insert|dba_key_split|dba_list|' + 'dba_nextkey|dba_open|dba_optimize|dba_popen|dba_replace|dba_sync|dbase_add_record|dbase_close|dbase_create|dbase_delete_record|' + 'dbase_get_header_info|dbase_get_record|dbase_get_record_with_names|dbase_numfields|dbase_numrecords|dbase_open|dbase_pack|' + 'dbase_replace_record|dbplus_add|dbplus_aql|dbplus_chdir|dbplus_close|dbplus_curr|dbplus_errcode|dbplus_errno|dbplus_find|dbplus_first|' + 'dbplus_flush|dbplus_freealllocks|dbplus_freelock|dbplus_freerlocks|dbplus_getlock|dbplus_getunique|dbplus_info|dbplus_last|dbplus_lockrel|' + 'dbplus_next|dbplus_open|dbplus_prev|dbplus_rchperm|dbplus_rcreate|dbplus_rcrtexact|dbplus_rcrtlike|dbplus_resolve|dbplus_restorepos|' + 'dbplus_rkeys|dbplus_ropen|dbplus_rquery|dbplus_rrename|dbplus_rsecindex|dbplus_runlink|dbplus_rzap|dbplus_savepos|dbplus_setindex|' + 'dbplus_setindexbynumber|dbplus_sql|dbplus_tcl|dbplus_tremove|dbplus_undo|dbplus_undoprepare|dbplus_unlockrel|dbplus_unselect|' + 'dbplus_update|dbplus_xlockrel|dbplus_xunlockrel|dbx_close|dbx_compare|dbx_connect|dbx_error|dbx_escape_string|dbx_fetch_row|dbx_query|' + 'dbx_sort|dcgettext|dcngettext|deaggregate|debug_backtrace|debug_print_backtrace|debug_zval_dump|decbin|dechex|decoct|define|' + 'define_syslog_variables|defined|deg2rad|delete|dgettext|die|dio_close|dio_fcntl|dio_open|dio_read|dio_seek|dio_stat|dio_tcsetattr|' + 'dio_truncate|dio_write|dir|directoryiterator|dirname|disk_free_space|disk_total_space|diskfreespace|dl|dngettext|dns_check_record|' + 'dns_get_mx|dns_get_record|dom_import_simplexml|domainexception|domattr|domattribute_name|domattribute_set_value|domattribute_specified|' + 'domattribute_value|domcharacterdata|domcomment|domdocument|domdocument_add_root|domdocument_create_attribute|' + 'domdocument_create_cdata_section|domdocument_create_comment|domdocument_create_element|domdocument_create_element_ns|' + 'domdocument_create_entity_reference|domdocument_create_processing_instruction|domdocument_create_text_node|domdocument_doctype|' + 'domdocument_document_element|domdocument_dump_file|domdocument_dump_mem|domdocument_get_element_by_id|domdocument_get_elements_by_tagname|' + 'domdocument_html_dump_mem|domdocument_xinclude|domdocumentfragment|domdocumenttype|domdocumenttype_entities|' + 'domdocumenttype_internal_subset|domdocumenttype_name|domdocumenttype_notations|domdocumenttype_public_id|domdocumenttype_system_id|' + 'domelement|domelement_get_attribute|domelement_get_attribute_node|domelement_get_elements_by_tagname|domelement_has_attribute|' + 'domelement_remove_attribute|domelement_set_attribute|domelement_set_attribute_node|domelement_tagname|domentity|domentityreference|' + 'domexception|domimplementation|domnamednodemap|domnode|domnode_add_namespace|domnode_append_child|domnode_append_sibling|' + 'domnode_attributes|domnode_child_nodes|domnode_clone_node|domnode_dump_node|domnode_first_child|domnode_get_content|' + 'domnode_has_attributes|domnode_has_child_nodes|domnode_insert_before|domnode_is_blank_node|domnode_last_child|domnode_next_sibling|' + 'domnode_node_name|domnode_node_type|domnode_node_value|domnode_owner_document|domnode_parent_node|domnode_prefix|domnode_previous_sibling|' + 'domnode_remove_child|domnode_replace_child|domnode_replace_node|domnode_set_content|domnode_set_name|domnode_set_namespace|' + 'domnode_unlink_node|domnodelist|domnotation|domprocessinginstruction|domprocessinginstruction_data|domprocessinginstruction_target|' + 'domtext|domxml_new_doc|domxml_open_file|domxml_open_mem|domxml_version|domxml_xmltree|domxml_xslt_stylesheet|domxml_xslt_stylesheet_doc|' + 'domxml_xslt_stylesheet_file|domxml_xslt_version|domxpath|domxsltstylesheet_process|domxsltstylesheet_result_dump_file|' + 'domxsltstylesheet_result_dump_mem|dotnet|dotnet_load|doubleval|each|easter_date|easter_days|echo|empty|emptyiterator|' + 'enchant_broker_describe|enchant_broker_dict_exists|enchant_broker_free|enchant_broker_free_dict|enchant_broker_get_error|' + 'enchant_broker_init|enchant_broker_list_dicts|enchant_broker_request_dict|enchant_broker_request_pwl_dict|enchant_broker_set_ordering|' + 'enchant_dict_add_to_personal|enchant_dict_add_to_session|enchant_dict_check|enchant_dict_describe|enchant_dict_get_error|' + 'enchant_dict_is_in_session|enchant_dict_quick_check|enchant_dict_store_replacement|enchant_dict_suggest|end|ereg|ereg_replace|eregi|' + 'eregi_replace|error_get_last|error_log|error_reporting|errorexception|escapeshellarg|escapeshellcmd|eval|event_add|event_base_free|' + 'event_base_loop|event_base_loopbreak|event_base_loopexit|event_base_new|event_base_priority_init|event_base_set|event_buffer_base_set|' + 'event_buffer_disable|event_buffer_enable|event_buffer_fd_set|event_buffer_free|event_buffer_new|event_buffer_priority_set|' + 'event_buffer_read|event_buffer_set_callback|event_buffer_timeout_set|event_buffer_watermark_set|event_buffer_write|event_del|event_free|' + 'event_new|event_set|exception|exec|exif_imagetype|exif_read_data|exif_tagname|exif_thumbnail|exit|exp|expect_expectl|expect_popen|explode|' + 'expm1|export|export|extension_loaded|extract|ezmlm_hash|fam_cancel_monitor|fam_close|fam_monitor_collection|fam_monitor_directory|' + 'fam_monitor_file|fam_next_event|fam_open|fam_pending|fam_resume_monitor|fam_suspend_monitor|fbsql_affected_rows|fbsql_autocommit|' + 'fbsql_blob_size|fbsql_change_user|fbsql_clob_size|fbsql_close|fbsql_commit|fbsql_connect|fbsql_create_blob|fbsql_create_clob|' + 'fbsql_create_db|fbsql_data_seek|fbsql_database|fbsql_database_password|fbsql_db_query|fbsql_db_status|fbsql_drop_db|fbsql_errno|' + 'fbsql_error|fbsql_fetch_array|fbsql_fetch_assoc|fbsql_fetch_field|fbsql_fetch_lengths|fbsql_fetch_object|fbsql_fetch_row|' + 'fbsql_field_flags|fbsql_field_len|fbsql_field_name|fbsql_field_seek|fbsql_field_table|fbsql_field_type|fbsql_free_result|' + 'fbsql_get_autostart_info|fbsql_hostname|fbsql_insert_id|fbsql_list_dbs|fbsql_list_fields|fbsql_list_tables|fbsql_next_result|' + 'fbsql_num_fields|fbsql_num_rows|fbsql_password|fbsql_pconnect|fbsql_query|fbsql_read_blob|fbsql_read_clob|fbsql_result|fbsql_rollback|' + 'fbsql_rows_fetched|fbsql_select_db|fbsql_set_characterset|fbsql_set_lob_mode|fbsql_set_password|fbsql_set_transaction|fbsql_start_db|' + 'fbsql_stop_db|fbsql_table_name|fbsql_tablename|fbsql_username|fbsql_warnings|fclose|fdf_add_doc_javascript|fdf_add_template|fdf_close|' + 'fdf_create|fdf_enum_values|fdf_errno|fdf_error|fdf_get_ap|fdf_get_attachment|fdf_get_encoding|fdf_get_file|fdf_get_flags|fdf_get_opt|' + 'fdf_get_status|fdf_get_value|fdf_get_version|fdf_header|fdf_next_field_name|fdf_open|fdf_open_string|fdf_remove_item|fdf_save|' + 'fdf_save_string|fdf_set_ap|fdf_set_encoding|fdf_set_file|fdf_set_flags|fdf_set_javascript_action|fdf_set_on_import_javascript|fdf_set_opt|' + 'fdf_set_status|fdf_set_submit_form_action|fdf_set_target_frame|fdf_set_value|fdf_set_version|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file|' + 'file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filepro|' + 'filepro_fieldcount|filepro_fieldname|filepro_fieldtype|filepro_fieldwidth|filepro_retrieve|filepro_rowcount|filesize|filesystemiterator|' + 'filetype|filter_has_var|filter_id|filter_input|filter_input_array|filter_list|filter_var|filter_var_array|filteriterator|finfo_buffer|' + 'finfo_close|finfo_file|finfo_open|finfo_set_flags|floatval|flock|floor|flush|fmod|fnmatch|fopen|forward_static_call|' + 'forward_static_call_array|fpassthru|fprintf|fputcsv|fputs|fread|frenchtojd|fribidi_log2vis|fscanf|fseek|fsockopen|fstat|ftell|ftok|' + 'ftp_alloc|ftp_cdup|ftp_chdir|ftp_chmod|ftp_close|ftp_connect|ftp_delete|ftp_exec|ftp_fget|ftp_fput|ftp_get|ftp_get_option|ftp_login|' + 'ftp_mdtm|ftp_mkdir|ftp_nb_continue|ftp_nb_fget|ftp_nb_fput|ftp_nb_get|ftp_nb_put|ftp_nlist|ftp_pasv|ftp_put|ftp_pwd|ftp_quit|ftp_raw|' + 'ftp_rawlist|ftp_rename|ftp_rmdir|ftp_set_option|ftp_site|ftp_size|ftp_ssl_connect|ftp_systype|ftruncate|func_get_arg|func_get_args|' + 'func_num_args|function_exists|fwrite|gc_collect_cycles|gc_disable|gc_enable|gc_enabled|gd_info|gearmanclient|gearmanjob|gearmantask|' + 'gearmanworker|geoip_continent_code_by_name|geoip_country_code3_by_name|geoip_country_code_by_name|geoip_country_name_by_name|' + 'geoip_database_info|geoip_db_avail|geoip_db_filename|geoip_db_get_all_info|geoip_id_by_name|geoip_isp_by_name|geoip_org_by_name|' + 'geoip_record_by_name|geoip_region_by_name|geoip_region_name_by_code|geoip_time_zone_by_country_and_region|getMeta|getNamed|getValue|' + 'get_browser|get_called_class|get_cfg_var|get_class|get_class_methods|get_class_vars|get_current_user|get_declared_classes|' + 'get_declared_interfaces|get_defined_constants|get_defined_functions|get_defined_vars|get_extension_funcs|get_headers|' + 'get_html_translation_table|get_include_path|get_included_files|get_loaded_extensions|get_magic_quotes_gpc|get_magic_quotes_runtime|' + 'get_meta_tags|get_object_vars|get_parent_class|get_required_files|get_resource_type|getallheaders|getconstant|getconstants|getconstructor|' + 'getcwd|getdate|getdefaultproperties|getdoccomment|getendline|getenv|getextension|getextensionname|getfilename|gethostbyaddr|gethostbyname|' + 'gethostbynamel|gethostname|getimagesize|getinterfacenames|getinterfaces|getlastmod|getmethod|getmethods|getmodifiers|getmxrr|getmygid|' + 'getmyinode|getmypid|getmyuid|getname|getnamespacename|getopt|getparentclass|getproperties|getproperty|getprotobyname|getprotobynumber|' + 'getrandmax|getrusage|getservbyname|getservbyport|getshortname|getstartline|getstaticproperties|getstaticpropertyvalue|gettext|' + 'gettimeofday|gettype|glob|globiterator|gmagick|gmagickdraw|gmagickpixel|gmdate|gmmktime|gmp_abs|gmp_add|gmp_and|gmp_clrbit|gmp_cmp|' + 'gmp_com|gmp_div|gmp_div_q|gmp_div_qr|gmp_div_r|gmp_divexact|gmp_fact|gmp_gcd|gmp_gcdext|gmp_hamdist|gmp_init|gmp_intval|gmp_invert|' + 'gmp_jacobi|gmp_legendre|gmp_mod|gmp_mul|gmp_neg|gmp_nextprime|gmp_or|gmp_perfect_square|gmp_popcount|gmp_pow|gmp_powm|gmp_prob_prime|' + 'gmp_random|gmp_scan0|gmp_scan1|gmp_setbit|gmp_sign|gmp_sqrt|gmp_sqrtrem|gmp_strval|gmp_sub|gmp_testbit|gmp_xor|gmstrftime|' + 'gnupg_adddecryptkey|gnupg_addencryptkey|gnupg_addsignkey|gnupg_cleardecryptkeys|gnupg_clearencryptkeys|gnupg_clearsignkeys|gnupg_decrypt|' + 'gnupg_decryptverify|gnupg_encrypt|gnupg_encryptsign|gnupg_export|gnupg_geterror|gnupg_getprotocol|gnupg_import|gnupg_init|gnupg_keyinfo|' + 'gnupg_setarmor|gnupg_seterrormode|gnupg_setsignmode|gnupg_sign|gnupg_verify|gopher_parsedir|grapheme_extract|grapheme_stripos|' + 'grapheme_stristr|grapheme_strlen|grapheme_strpos|grapheme_strripos|grapheme_strrpos|grapheme_strstr|grapheme_substr|gregoriantojd|' + 'gupnp_context_get_host_ip|gupnp_context_get_port|gupnp_context_get_subscription_timeout|gupnp_context_host_path|gupnp_context_new|' + 'gupnp_context_set_subscription_timeout|gupnp_context_timeout_add|gupnp_context_unhost_path|gupnp_control_point_browse_start|' + 'gupnp_control_point_browse_stop|gupnp_control_point_callback_set|gupnp_control_point_new|gupnp_device_action_callback_set|' + 'gupnp_device_info_get|gupnp_device_info_get_service|gupnp_root_device_get_available|gupnp_root_device_get_relative_location|' + 'gupnp_root_device_new|gupnp_root_device_set_available|gupnp_root_device_start|gupnp_root_device_stop|gupnp_service_action_get|' + 'gupnp_service_action_return|gupnp_service_action_return_error|gupnp_service_action_set|gupnp_service_freeze_notify|gupnp_service_info_get|' + 'gupnp_service_info_get_introspection|gupnp_service_introspection_get_state_variable|gupnp_service_notify|gupnp_service_proxy_action_get|' + 'gupnp_service_proxy_action_set|gupnp_service_proxy_add_notify|gupnp_service_proxy_callback_set|gupnp_service_proxy_get_subscribed|' + 'gupnp_service_proxy_remove_notify|gupnp_service_proxy_set_subscribed|gupnp_service_thaw_notify|gzclose|gzcompress|gzdecode|gzdeflate|' + 'gzencode|gzeof|gzfile|gzgetc|gzgets|gzgetss|gzinflate|gzopen|gzpassthru|gzputs|gzread|gzrewind|gzseek|gztell|gzuncompress|gzwrite|' + 'halt_compiler|haruannotation|haruannotation_setborderstyle|haruannotation_sethighlightmode|haruannotation_seticon|' + 'haruannotation_setopened|harudestination|harudestination_setfit|harudestination_setfitb|harudestination_setfitbh|harudestination_setfitbv|' + 'harudestination_setfith|harudestination_setfitr|harudestination_setfitv|harudestination_setxyz|harudoc|harudoc_addpage|' + 'harudoc_addpagelabel|harudoc_construct|harudoc_createoutline|harudoc_getcurrentencoder|harudoc_getcurrentpage|harudoc_getencoder|' + 'harudoc_getfont|harudoc_getinfoattr|harudoc_getpagelayout|harudoc_getpagemode|harudoc_getstreamsize|harudoc_insertpage|harudoc_loadjpeg|' + 'harudoc_loadpng|harudoc_loadraw|harudoc_loadttc|harudoc_loadttf|harudoc_loadtype1|harudoc_output|harudoc_readfromstream|' + 'harudoc_reseterror|harudoc_resetstream|harudoc_save|harudoc_savetostream|harudoc_setcompressionmode|harudoc_setcurrentencoder|' + 'harudoc_setencryptionmode|harudoc_setinfoattr|harudoc_setinfodateattr|harudoc_setopenaction|harudoc_setpagelayout|harudoc_setpagemode|' + 'harudoc_setpagesconfiguration|harudoc_setpassword|harudoc_setpermission|harudoc_usecnsencodings|harudoc_usecnsfonts|' + 'harudoc_usecntencodings|harudoc_usecntfonts|harudoc_usejpencodings|harudoc_usejpfonts|harudoc_usekrencodings|harudoc_usekrfonts|' + 'haruencoder|haruencoder_getbytetype|haruencoder_gettype|haruencoder_getunicode|haruencoder_getwritingmode|haruexception|harufont|' + 'harufont_getascent|harufont_getcapheight|harufont_getdescent|harufont_getencodingname|harufont_getfontname|harufont_gettextwidth|' + 'harufont_getunicodewidth|harufont_getxheight|harufont_measuretext|haruimage|haruimage_getbitspercomponent|haruimage_getcolorspace|' + 'haruimage_getheight|haruimage_getsize|haruimage_getwidth|haruimage_setcolormask|haruimage_setmaskimage|haruoutline|' + 'haruoutline_setdestination|haruoutline_setopened|harupage|harupage_arc|harupage_begintext|harupage_circle|harupage_closepath|' + 'harupage_concat|harupage_createdestination|harupage_createlinkannotation|harupage_createtextannotation|harupage_createurlannotation|' + 'harupage_curveto|harupage_curveto2|harupage_curveto3|harupage_drawimage|harupage_ellipse|harupage_endpath|harupage_endtext|' + 'harupage_eofill|harupage_eofillstroke|harupage_fill|harupage_fillstroke|harupage_getcharspace|harupage_getcmykfill|harupage_getcmykstroke|' + 'harupage_getcurrentfont|harupage_getcurrentfontsize|harupage_getcurrentpos|harupage_getcurrenttextpos|harupage_getdash|' + 'harupage_getfillingcolorspace|harupage_getflatness|harupage_getgmode|harupage_getgrayfill|harupage_getgraystroke|harupage_getheight|' + 'harupage_gethorizontalscaling|harupage_getlinecap|harupage_getlinejoin|harupage_getlinewidth|harupage_getmiterlimit|harupage_getrgbfill|' + 'harupage_getrgbstroke|harupage_getstrokingcolorspace|harupage_gettextleading|harupage_gettextmatrix|harupage_gettextrenderingmode|' + 'harupage_gettextrise|harupage_gettextwidth|harupage_gettransmatrix|harupage_getwidth|harupage_getwordspace|harupage_lineto|' + 'harupage_measuretext|harupage_movetextpos|harupage_moveto|harupage_movetonextline|harupage_rectangle|harupage_setcharspace|' + 'harupage_setcmykfill|harupage_setcmykstroke|harupage_setdash|harupage_setflatness|harupage_setfontandsize|harupage_setgrayfill|' + 'harupage_setgraystroke|harupage_setheight|harupage_sethorizontalscaling|harupage_setlinecap|harupage_setlinejoin|harupage_setlinewidth|' + 'harupage_setmiterlimit|harupage_setrgbfill|harupage_setrgbstroke|harupage_setrotate|harupage_setsize|harupage_setslideshow|' + 'harupage_settextleading|harupage_settextmatrix|harupage_settextrenderingmode|harupage_settextrise|harupage_setwidth|harupage_setwordspace|' + 'harupage_showtext|harupage_showtextnextline|harupage_stroke|harupage_textout|harupage_textrect|hasconstant|hash|hash_algos|hash_copy|' + 'hash_file|hash_final|hash_hmac|hash_hmac_file|hash_init|hash_update|hash_update_file|hash_update_stream|hasmethod|hasproperty|header|' + 'header_register_callback|header_remove|headers_list|headers_sent|hebrev|hebrevc|hex2bin|hexdec|highlight_file|highlight_string|' + 'html_entity_decode|htmlentities|htmlspecialchars|htmlspecialchars_decode|http_build_cookie|http_build_query|http_build_str|http_build_url|' + 'http_cache_etag|http_cache_last_modified|http_chunked_decode|http_date|http_deflate|http_get|http_get_request_body|' + 'http_get_request_body_stream|http_get_request_headers|http_head|http_inflate|http_match_etag|http_match_modified|' + 'http_match_request_header|http_negotiate_charset|http_negotiate_content_type|http_negotiate_language|http_parse_cookie|http_parse_headers|' + 'http_parse_message|http_parse_params|http_persistent_handles_clean|http_persistent_handles_count|http_persistent_handles_ident|' + 'http_post_data|http_post_fields|http_put_data|http_put_file|http_put_stream|http_redirect|http_request|http_request_body_encode|' + 'http_request_method_exists|http_request_method_name|http_request_method_register|http_request_method_unregister|http_response_code|' + 'http_send_content_disposition|http_send_content_type|http_send_data|http_send_file|http_send_last_modified|http_send_status|' + 'http_send_stream|http_support|http_throttle|httpdeflatestream|httpdeflatestream_construct|httpdeflatestream_factory|' + 'httpdeflatestream_finish|httpdeflatestream_flush|httpdeflatestream_update|httpinflatestream|httpinflatestream_construct|' + 'httpinflatestream_factory|httpinflatestream_finish|httpinflatestream_flush|httpinflatestream_update|httpmessage|httpmessage_addheaders|' + 'httpmessage_construct|httpmessage_detach|httpmessage_factory|httpmessage_fromenv|httpmessage_fromstring|httpmessage_getbody|' + 'httpmessage_getheader|httpmessage_getheaders|httpmessage_gethttpversion|httpmessage_getparentmessage|httpmessage_getrequestmethod|' + 'httpmessage_getrequesturl|httpmessage_getresponsecode|httpmessage_getresponsestatus|httpmessage_gettype|httpmessage_guesscontenttype|' + 'httpmessage_prepend|httpmessage_reverse|httpmessage_send|httpmessage_setbody|httpmessage_setheaders|httpmessage_sethttpversion|' + 'httpmessage_setrequestmethod|httpmessage_setrequesturl|httpmessage_setresponsecode|httpmessage_setresponsestatus|httpmessage_settype|' + 'httpmessage_tomessagetypeobject|httpmessage_tostring|httpquerystring|httpquerystring_construct|httpquerystring_get|httpquerystring_mod|' + 'httpquerystring_set|httpquerystring_singleton|httpquerystring_toarray|httpquerystring_tostring|httpquerystring_xlate|httprequest|' + 'httprequest_addcookies|httprequest_addheaders|httprequest_addpostfields|httprequest_addpostfile|httprequest_addputdata|' + 'httprequest_addquerydata|httprequest_addrawpostdata|httprequest_addssloptions|httprequest_clearhistory|httprequest_construct|' + 'httprequest_enablecookies|httprequest_getcontenttype|httprequest_getcookies|httprequest_getheaders|httprequest_gethistory|' + 'httprequest_getmethod|httprequest_getoptions|httprequest_getpostfields|httprequest_getpostfiles|httprequest_getputdata|' + 'httprequest_getputfile|httprequest_getquerydata|httprequest_getrawpostdata|httprequest_getrawrequestmessage|' + 'httprequest_getrawresponsemessage|httprequest_getrequestmessage|httprequest_getresponsebody|httprequest_getresponsecode|' + 'httprequest_getresponsecookies|httprequest_getresponsedata|httprequest_getresponseheader|httprequest_getresponseinfo|' + 'httprequest_getresponsemessage|httprequest_getresponsestatus|httprequest_getssloptions|httprequest_geturl|httprequest_resetcookies|' + 'httprequest_send|httprequest_setcontenttype|httprequest_setcookies|httprequest_setheaders|httprequest_setmethod|httprequest_setoptions|' + 'httprequest_setpostfields|httprequest_setpostfiles|httprequest_setputdata|httprequest_setputfile|httprequest_setquerydata|' + 'httprequest_setrawpostdata|httprequest_setssloptions|httprequest_seturl|httprequestpool|httprequestpool_attach|httprequestpool_construct|' + 'httprequestpool_destruct|httprequestpool_detach|httprequestpool_getattachedrequests|httprequestpool_getfinishedrequests|' + 'httprequestpool_reset|httprequestpool_send|httprequestpool_socketperform|httprequestpool_socketselect|httpresponse|httpresponse_capture|' + 'httpresponse_getbuffersize|httpresponse_getcache|httpresponse_getcachecontrol|httpresponse_getcontentdisposition|' + 'httpresponse_getcontenttype|httpresponse_getdata|httpresponse_getetag|httpresponse_getfile|httpresponse_getgzip|httpresponse_getheader|' + 'httpresponse_getlastmodified|httpresponse_getrequestbody|httpresponse_getrequestbodystream|httpresponse_getrequestheaders|' + 'httpresponse_getstream|httpresponse_getthrottledelay|httpresponse_guesscontenttype|httpresponse_redirect|httpresponse_send|' + 'httpresponse_setbuffersize|httpresponse_setcache|httpresponse_setcachecontrol|httpresponse_setcontentdisposition|' + 'httpresponse_setcontenttype|httpresponse_setdata|httpresponse_setetag|httpresponse_setfile|httpresponse_setgzip|httpresponse_setheader|' + 'httpresponse_setlastmodified|httpresponse_setstream|httpresponse_setthrottledelay|httpresponse_status|hw_array2objrec|hw_changeobject|' + 'hw_children|hw_childrenobj|hw_close|hw_connect|hw_connection_info|hw_cp|hw_deleteobject|hw_docbyanchor|hw_docbyanchorobj|' + 'hw_document_attributes|hw_document_bodytag|hw_document_content|hw_document_setcontent|hw_document_size|hw_dummy|hw_edittext|hw_error|' + 'hw_errormsg|hw_free_document|hw_getanchors|hw_getanchorsobj|hw_getandlock|hw_getchildcoll|hw_getchildcollobj|hw_getchilddoccoll|' + 'hw_getchilddoccollobj|hw_getobject|hw_getobjectbyquery|hw_getobjectbyquerycoll|hw_getobjectbyquerycollobj|hw_getobjectbyqueryobj|' + 'hw_getparents|hw_getparentsobj|hw_getrellink|hw_getremote|hw_getremotechildren|hw_getsrcbydestobj|hw_gettext|hw_getusername|hw_identify|' + 'hw_incollections|hw_info|hw_inscoll|hw_insdoc|hw_insertanchors|hw_insertdocument|hw_insertobject|hw_mapid|hw_modifyobject|hw_mv|' + 'hw_new_document|hw_objrec2array|hw_output_document|hw_pconnect|hw_pipedocument|hw_root|hw_setlinkroot|hw_stat|hw_unlock|hw_who|' + 'hwapi_attribute|hwapi_attribute_key|hwapi_attribute_langdepvalue|hwapi_attribute_value|hwapi_attribute_values|hwapi_checkin|' + 'hwapi_checkout|hwapi_children|hwapi_content|hwapi_content_mimetype|hwapi_content_read|hwapi_copy|hwapi_dbstat|hwapi_dcstat|' + 'hwapi_dstanchors|hwapi_dstofsrcanchor|hwapi_error_count|hwapi_error_reason|hwapi_find|hwapi_ftstat|hwapi_hgcsp|hwapi_hwstat|' + 'hwapi_identify|hwapi_info|hwapi_insert|hwapi_insertanchor|hwapi_insertcollection|hwapi_insertdocument|hwapi_link|hwapi_lock|hwapi_move|' + 'hwapi_new_content|hwapi_object|hwapi_object_assign|hwapi_object_attreditable|hwapi_object_count|hwapi_object_insert|hwapi_object_new|' + 'hwapi_object_remove|hwapi_object_title|hwapi_object_value|hwapi_objectbyanchor|hwapi_parents|hwapi_reason_description|hwapi_reason_type|' + 'hwapi_remove|hwapi_replace|hwapi_setcommittedversion|hwapi_srcanchors|hwapi_srcsofdst|hwapi_unlock|hwapi_user|hwapi_userlist|hypot|' + 'ibase_add_user|ibase_affected_rows|ibase_backup|ibase_blob_add|ibase_blob_cancel|ibase_blob_close|ibase_blob_create|ibase_blob_echo|' + 'ibase_blob_get|ibase_blob_import|ibase_blob_info|ibase_blob_open|ibase_close|ibase_commit|ibase_commit_ret|ibase_connect|ibase_db_info|' + 'ibase_delete_user|ibase_drop_db|ibase_errcode|ibase_errmsg|ibase_execute|ibase_fetch_assoc|ibase_fetch_object|ibase_fetch_row|' + 'ibase_field_info|ibase_free_event_handler|ibase_free_query|ibase_free_result|ibase_gen_id|ibase_maintain_db|ibase_modify_user|' + 'ibase_name_result|ibase_num_fields|ibase_num_params|ibase_param_info|ibase_pconnect|ibase_prepare|ibase_query|ibase_restore|' + 'ibase_rollback|ibase_rollback_ret|ibase_server_info|ibase_service_attach|ibase_service_detach|ibase_set_event_handler|ibase_timefmt|' + 'ibase_trans|ibase_wait_event|iconv|iconv_get_encoding|iconv_mime_decode|iconv_mime_decode_headers|iconv_mime_encode|iconv_set_encoding|' + 'iconv_strlen|iconv_strpos|iconv_strrpos|iconv_substr|id3_get_frame_long_name|id3_get_frame_short_name|id3_get_genre_id|id3_get_genre_list|' + 'id3_get_genre_name|id3_get_tag|id3_get_version|id3_remove_tag|id3_set_tag|id3v2attachedpictureframe|id3v2frame|id3v2tag|idate|' + 'idn_to_ascii|idn_to_unicode|idn_to_utf8|ifx_affected_rows|ifx_blobinfile_mode|ifx_byteasvarchar|ifx_close|ifx_connect|ifx_copy_blob|' + 'ifx_create_blob|ifx_create_char|ifx_do|ifx_error|ifx_errormsg|ifx_fetch_row|ifx_fieldproperties|ifx_fieldtypes|ifx_free_blob|' + 'ifx_free_char|ifx_free_result|ifx_get_blob|ifx_get_char|ifx_getsqlca|ifx_htmltbl_result|ifx_nullformat|ifx_num_fields|ifx_num_rows|' + 'ifx_pconnect|ifx_prepare|ifx_query|ifx_textasvarchar|ifx_update_blob|ifx_update_char|ifxus_close_slob|ifxus_create_slob|ifxus_free_slob|' + 'ifxus_open_slob|ifxus_read_slob|ifxus_seek_slob|ifxus_tell_slob|ifxus_write_slob|ignore_user_abort|iis_add_server|iis_get_dir_security|' + 'iis_get_script_map|iis_get_server_by_comment|iis_get_server_by_path|iis_get_server_rights|iis_get_service_state|iis_remove_server|' + 'iis_set_app_settings|iis_set_dir_security|iis_set_script_map|iis_set_server_rights|iis_start_server|iis_start_service|iis_stop_server|' + 'iis_stop_service|image2wbmp|image_type_to_extension|image_type_to_mime_type|imagealphablending|imageantialias|imagearc|imagechar|' + 'imagecharup|imagecolorallocate|imagecolorallocatealpha|imagecolorat|imagecolorclosest|imagecolorclosestalpha|imagecolorclosesthwb|' + 'imagecolordeallocate|imagecolorexact|imagecolorexactalpha|imagecolormatch|imagecolorresolve|imagecolorresolvealpha|imagecolorset|' + 'imagecolorsforindex|imagecolorstotal|imagecolortransparent|imageconvolution|imagecopy|imagecopymerge|imagecopymergegray|' + 'imagecopyresampled|imagecopyresized|imagecreate|imagecreatefromgd|imagecreatefromgd2|imagecreatefromgd2part|imagecreatefromgif|' + 'imagecreatefromjpeg|imagecreatefrompng|imagecreatefromstring|imagecreatefromwbmp|imagecreatefromxbm|imagecreatefromxpm|' + 'imagecreatetruecolor|imagedashedline|imagedestroy|imageellipse|imagefill|imagefilledarc|imagefilledellipse|imagefilledpolygon|' + 'imagefilledrectangle|imagefilltoborder|imagefilter|imagefontheight|imagefontwidth|imageftbbox|imagefttext|imagegammacorrect|imagegd|' + 'imagegd2|imagegif|imagegrabscreen|imagegrabwindow|imageinterlace|imageistruecolor|imagejpeg|imagelayereffect|imageline|imageloadfont|' + 'imagepalettecopy|imagepng|imagepolygon|imagepsbbox|imagepsencodefont|imagepsextendfont|imagepsfreefont|imagepsloadfont|imagepsslantfont|' + 'imagepstext|imagerectangle|imagerotate|imagesavealpha|imagesetbrush|imagesetpixel|imagesetstyle|imagesetthickness|imagesettile|' + 'imagestring|imagestringup|imagesx|imagesy|imagetruecolortopalette|imagettfbbox|imagettftext|imagetypes|imagewbmp|imagexbm|imagick|' + 'imagick_adaptiveblurimage|imagick_adaptiveresizeimage|imagick_adaptivesharpenimage|imagick_adaptivethresholdimage|imagick_addimage|' + 'imagick_addnoiseimage|imagick_affinetransformimage|imagick_animateimages|imagick_annotateimage|imagick_appendimages|imagick_averageimages|' + 'imagick_blackthresholdimage|imagick_blurimage|imagick_borderimage|imagick_charcoalimage|imagick_chopimage|imagick_clear|imagick_clipimage|' + 'imagick_clippathimage|imagick_clone|imagick_clutimage|imagick_coalesceimages|imagick_colorfloodfillimage|imagick_colorizeimage|' + 'imagick_combineimages|imagick_commentimage|imagick_compareimagechannels|imagick_compareimagelayers|imagick_compareimages|' + 'imagick_compositeimage|imagick_construct|imagick_contrastimage|imagick_contraststretchimage|imagick_convolveimage|imagick_cropimage|' + 'imagick_cropthumbnailimage|imagick_current|imagick_cyclecolormapimage|imagick_decipherimage|imagick_deconstructimages|' + 'imagick_deleteimageartifact|imagick_despeckleimage|imagick_destroy|imagick_displayimage|imagick_displayimages|imagick_distortimage|' + 'imagick_drawimage|imagick_edgeimage|imagick_embossimage|imagick_encipherimage|imagick_enhanceimage|imagick_equalizeimage|' + 'imagick_evaluateimage|imagick_extentimage|imagick_flattenimages|imagick_flipimage|imagick_floodfillpaintimage|imagick_flopimage|' + 'imagick_frameimage|imagick_fximage|imagick_gammaimage|imagick_gaussianblurimage|imagick_getcolorspace|imagick_getcompression|' + 'imagick_getcompressionquality|imagick_getcopyright|imagick_getfilename|imagick_getfont|imagick_getformat|imagick_getgravity|' + 'imagick_gethomeurl|imagick_getimage|imagick_getimagealphachannel|imagick_getimageartifact|imagick_getimagebackgroundcolor|' + 'imagick_getimageblob|imagick_getimageblueprimary|imagick_getimagebordercolor|imagick_getimagechanneldepth|' + 'imagick_getimagechanneldistortion|imagick_getimagechanneldistortions|imagick_getimagechannelextrema|imagick_getimagechannelmean|' + 'imagick_getimagechannelrange|imagick_getimagechannelstatistics|imagick_getimageclipmask|imagick_getimagecolormapcolor|' + 'imagick_getimagecolors|imagick_getimagecolorspace|imagick_getimagecompose|imagick_getimagecompression|imagick_getimagecompressionquality|' + 'imagick_getimagedelay|imagick_getimagedepth|imagick_getimagedispose|imagick_getimagedistortion|imagick_getimageextrema|' + 'imagick_getimagefilename|imagick_getimageformat|imagick_getimagegamma|imagick_getimagegeometry|imagick_getimagegravity|' + 'imagick_getimagegreenprimary|imagick_getimageheight|imagick_getimagehistogram|imagick_getimageindex|imagick_getimageinterlacescheme|' + 'imagick_getimageinterpolatemethod|imagick_getimageiterations|imagick_getimagelength|imagick_getimagemagicklicense|imagick_getimagematte|' + 'imagick_getimagemattecolor|imagick_getimageorientation|imagick_getimagepage|imagick_getimagepixelcolor|imagick_getimageprofile|' + 'imagick_getimageprofiles|imagick_getimageproperties|imagick_getimageproperty|imagick_getimageredprimary|imagick_getimageregion|' + 'imagick_getimagerenderingintent|imagick_getimageresolution|imagick_getimagesblob|imagick_getimagescene|imagick_getimagesignature|' + 'imagick_getimagesize|imagick_getimagetickspersecond|imagick_getimagetotalinkdensity|imagick_getimagetype|imagick_getimageunits|' + 'imagick_getimagevirtualpixelmethod|imagick_getimagewhitepoint|imagick_getimagewidth|imagick_getinterlacescheme|imagick_getiteratorindex|' + 'imagick_getnumberimages|imagick_getoption|imagick_getpackagename|imagick_getpage|imagick_getpixeliterator|imagick_getpixelregioniterator|' + 'imagick_getpointsize|imagick_getquantumdepth|imagick_getquantumrange|imagick_getreleasedate|imagick_getresource|imagick_getresourcelimit|' + 'imagick_getsamplingfactors|imagick_getsize|imagick_getsizeoffset|imagick_getversion|imagick_hasnextimage|imagick_haspreviousimage|' + 'imagick_identifyimage|imagick_implodeimage|imagick_labelimage|imagick_levelimage|imagick_linearstretchimage|imagick_liquidrescaleimage|' + 'imagick_magnifyimage|imagick_mapimage|imagick_mattefloodfillimage|imagick_medianfilterimage|imagick_mergeimagelayers|imagick_minifyimage|' + 'imagick_modulateimage|imagick_montageimage|imagick_morphimages|imagick_mosaicimages|imagick_motionblurimage|imagick_negateimage|' + 'imagick_newimage|imagick_newpseudoimage|imagick_nextimage|imagick_normalizeimage|imagick_oilpaintimage|imagick_opaquepaintimage|' + 'imagick_optimizeimagelayers|imagick_orderedposterizeimage|imagick_paintfloodfillimage|imagick_paintopaqueimage|' + 'imagick_painttransparentimage|imagick_pingimage|imagick_pingimageblob|imagick_pingimagefile|imagick_polaroidimage|imagick_posterizeimage|' + 'imagick_previewimages|imagick_previousimage|imagick_profileimage|imagick_quantizeimage|imagick_quantizeimages|imagick_queryfontmetrics|' + 'imagick_queryfonts|imagick_queryformats|imagick_radialblurimage|imagick_raiseimage|imagick_randomthresholdimage|imagick_readimage|' + 'imagick_readimageblob|imagick_readimagefile|imagick_recolorimage|imagick_reducenoiseimage|imagick_removeimage|imagick_removeimageprofile|' + 'imagick_render|imagick_resampleimage|imagick_resetimagepage|imagick_resizeimage|imagick_rollimage|imagick_rotateimage|' + 'imagick_roundcorners|imagick_sampleimage|imagick_scaleimage|imagick_separateimagechannel|imagick_sepiatoneimage|' + 'imagick_setbackgroundcolor|imagick_setcolorspace|imagick_setcompression|imagick_setcompressionquality|imagick_setfilename|' + 'imagick_setfirstiterator|imagick_setfont|imagick_setformat|imagick_setgravity|imagick_setimage|imagick_setimagealphachannel|' + 'imagick_setimageartifact|imagick_setimagebackgroundcolor|imagick_setimagebias|imagick_setimageblueprimary|imagick_setimagebordercolor|' + 'imagick_setimagechanneldepth|imagick_setimageclipmask|imagick_setimagecolormapcolor|imagick_setimagecolorspace|imagick_setimagecompose|' + 'imagick_setimagecompression|imagick_setimagecompressionquality|imagick_setimagedelay|imagick_setimagedepth|imagick_setimagedispose|' + 'imagick_setimageextent|imagick_setimagefilename|imagick_setimageformat|imagick_setimagegamma|imagick_setimagegravity|' + 'imagick_setimagegreenprimary|imagick_setimageindex|imagick_setimageinterlacescheme|imagick_setimageinterpolatemethod|' + 'imagick_setimageiterations|imagick_setimagematte|imagick_setimagemattecolor|imagick_setimageopacity|imagick_setimageorientation|' + 'imagick_setimagepage|imagick_setimageprofile|imagick_setimageproperty|imagick_setimageredprimary|imagick_setimagerenderingintent|' + 'imagick_setimageresolution|imagick_setimagescene|imagick_setimagetickspersecond|imagick_setimagetype|imagick_setimageunits|' + 'imagick_setimagevirtualpixelmethod|imagick_setimagewhitepoint|imagick_setinterlacescheme|imagick_setiteratorindex|imagick_setlastiterator|' + 'imagick_setoption|imagick_setpage|imagick_setpointsize|imagick_setresolution|imagick_setresourcelimit|imagick_setsamplingfactors|' + 'imagick_setsize|imagick_setsizeoffset|imagick_settype|imagick_shadeimage|imagick_shadowimage|imagick_sharpenimage|imagick_shaveimage|' + 'imagick_shearimage|imagick_sigmoidalcontrastimage|imagick_sketchimage|imagick_solarizeimage|imagick_spliceimage|imagick_spreadimage|' + 'imagick_steganoimage|imagick_stereoimage|imagick_stripimage|imagick_swirlimage|imagick_textureimage|imagick_thresholdimage|' + 'imagick_thumbnailimage|imagick_tintimage|imagick_transformimage|imagick_transparentpaintimage|imagick_transposeimage|' + 'imagick_transverseimage|imagick_trimimage|imagick_uniqueimagecolors|imagick_unsharpmaskimage|imagick_valid|imagick_vignetteimage|' + 'imagick_waveimage|imagick_whitethresholdimage|imagick_writeimage|imagick_writeimagefile|imagick_writeimages|imagick_writeimagesfile|' + 'imagickdraw|imagickdraw_affine|imagickdraw_annotation|imagickdraw_arc|imagickdraw_bezier|imagickdraw_circle|imagickdraw_clear|' + 'imagickdraw_clone|imagickdraw_color|imagickdraw_comment|imagickdraw_composite|imagickdraw_construct|imagickdraw_destroy|' + 'imagickdraw_ellipse|imagickdraw_getclippath|imagickdraw_getcliprule|imagickdraw_getclipunits|imagickdraw_getfillcolor|' + 'imagickdraw_getfillopacity|imagickdraw_getfillrule|imagickdraw_getfont|imagickdraw_getfontfamily|imagickdraw_getfontsize|' + 'imagickdraw_getfontstyle|imagickdraw_getfontweight|imagickdraw_getgravity|imagickdraw_getstrokeantialias|imagickdraw_getstrokecolor|' + 'imagickdraw_getstrokedasharray|imagickdraw_getstrokedashoffset|imagickdraw_getstrokelinecap|imagickdraw_getstrokelinejoin|' + 'imagickdraw_getstrokemiterlimit|imagickdraw_getstrokeopacity|imagickdraw_getstrokewidth|imagickdraw_gettextalignment|' + 'imagickdraw_gettextantialias|imagickdraw_gettextdecoration|imagickdraw_gettextencoding|imagickdraw_gettextundercolor|' + 'imagickdraw_getvectorgraphics|imagickdraw_line|imagickdraw_matte|imagickdraw_pathclose|imagickdraw_pathcurvetoabsolute|' + 'imagickdraw_pathcurvetoquadraticbezierabsolute|imagickdraw_pathcurvetoquadraticbezierrelative|' + 'imagickdraw_pathcurvetoquadraticbeziersmoothabsolute|imagickdraw_pathcurvetoquadraticbeziersmoothrelative|imagickdraw_pathcurvetorelative|' + 'imagickdraw_pathcurvetosmoothabsolute|imagickdraw_pathcurvetosmoothrelative|imagickdraw_pathellipticarcabsolute|' + 'imagickdraw_pathellipticarcrelative|imagickdraw_pathfinish|imagickdraw_pathlinetoabsolute|imagickdraw_pathlinetohorizontalabsolute|' + 'imagickdraw_pathlinetohorizontalrelative|imagickdraw_pathlinetorelative|imagickdraw_pathlinetoverticalabsolute|' + 'imagickdraw_pathlinetoverticalrelative|imagickdraw_pathmovetoabsolute|imagickdraw_pathmovetorelative|imagickdraw_pathstart|' + 'imagickdraw_point|imagickdraw_polygon|imagickdraw_polyline|imagickdraw_pop|imagickdraw_popclippath|imagickdraw_popdefs|' + 'imagickdraw_poppattern|imagickdraw_push|imagickdraw_pushclippath|imagickdraw_pushdefs|imagickdraw_pushpattern|imagickdraw_rectangle|' + 'imagickdraw_render|imagickdraw_rotate|imagickdraw_roundrectangle|imagickdraw_scale|imagickdraw_setclippath|imagickdraw_setcliprule|' + 'imagickdraw_setclipunits|imagickdraw_setfillalpha|imagickdraw_setfillcolor|imagickdraw_setfillopacity|imagickdraw_setfillpatternurl|' + 'imagickdraw_setfillrule|imagickdraw_setfont|imagickdraw_setfontfamily|imagickdraw_setfontsize|imagickdraw_setfontstretch|' + 'imagickdraw_setfontstyle|imagickdraw_setfontweight|imagickdraw_setgravity|imagickdraw_setstrokealpha|imagickdraw_setstrokeantialias|' + 'imagickdraw_setstrokecolor|imagickdraw_setstrokedasharray|imagickdraw_setstrokedashoffset|imagickdraw_setstrokelinecap|' + 'imagickdraw_setstrokelinejoin|imagickdraw_setstrokemiterlimit|imagickdraw_setstrokeopacity|imagickdraw_setstrokepatternurl|' + 'imagickdraw_setstrokewidth|imagickdraw_settextalignment|imagickdraw_settextantialias|imagickdraw_settextdecoration|' + 'imagickdraw_settextencoding|imagickdraw_settextundercolor|imagickdraw_setvectorgraphics|imagickdraw_setviewbox|imagickdraw_skewx|' + 'imagickdraw_skewy|imagickdraw_translate|imagickpixel|imagickpixel_clear|imagickpixel_construct|imagickpixel_destroy|imagickpixel_getcolor|' + 'imagickpixel_getcolorasstring|imagickpixel_getcolorcount|imagickpixel_getcolorvalue|imagickpixel_gethsl|imagickpixel_issimilar|' + 'imagickpixel_setcolor|imagickpixel_setcolorvalue|imagickpixel_sethsl|imagickpixeliterator|imagickpixeliterator_clear|' + 'imagickpixeliterator_construct|imagickpixeliterator_destroy|imagickpixeliterator_getcurrentiteratorrow|' + 'imagickpixeliterator_getiteratorrow|imagickpixeliterator_getnextiteratorrow|imagickpixeliterator_getpreviousiteratorrow|' + 'imagickpixeliterator_newpixeliterator|imagickpixeliterator_newpixelregioniterator|imagickpixeliterator_resetiterator|' + 'imagickpixeliterator_setiteratorfirstrow|imagickpixeliterator_setiteratorlastrow|imagickpixeliterator_setiteratorrow|' + 'imagickpixeliterator_synciterator|imap_8bit|imap_alerts|imap_append|imap_base64|imap_binary|imap_body|imap_bodystruct|imap_check|' + 'imap_clearflag_full|imap_close|imap_create|imap_createmailbox|imap_delete|imap_deletemailbox|imap_errors|imap_expunge|imap_fetch_overview|' + 'imap_fetchbody|imap_fetchheader|imap_fetchmime|imap_fetchstructure|imap_fetchtext|imap_gc|imap_get_quota|imap_get_quotaroot|imap_getacl|' + 'imap_getmailboxes|imap_getsubscribed|imap_header|imap_headerinfo|imap_headers|imap_last_error|imap_list|imap_listmailbox|imap_listscan|' + 'imap_listsubscribed|imap_lsub|imap_mail|imap_mail_compose|imap_mail_copy|imap_mail_move|imap_mailboxmsginfo|imap_mime_header_decode|' + 'imap_msgno|imap_num_msg|imap_num_recent|imap_open|imap_ping|imap_qprint|imap_rename|imap_renamemailbox|imap_reopen|' + 'imap_rfc822_parse_adrlist|imap_rfc822_parse_headers|imap_rfc822_write_address|imap_savebody|imap_scan|imap_scanmailbox|imap_search|' + 'imap_set_quota|imap_setacl|imap_setflag_full|imap_sort|imap_status|imap_subscribe|imap_thread|imap_timeout|imap_uid|imap_undelete|' + 'imap_unsubscribe|imap_utf7_decode|imap_utf7_encode|imap_utf8|implementsinterface|implode|import_request_variables|in_array|include|' + 'include_once|inclued_get_data|inet_ntop|inet_pton|infiniteiterator|ingres_autocommit|ingres_autocommit_state|ingres_charset|ingres_close|' + 'ingres_commit|ingres_connect|ingres_cursor|ingres_errno|ingres_error|ingres_errsqlstate|ingres_escape_string|ingres_execute|' + 'ingres_fetch_array|ingres_fetch_assoc|ingres_fetch_object|ingres_fetch_proc_return|ingres_fetch_row|ingres_field_length|ingres_field_name|' + 'ingres_field_nullable|ingres_field_precision|ingres_field_scale|ingres_field_type|ingres_free_result|ingres_next_error|ingres_num_fields|' + 'ingres_num_rows|ingres_pconnect|ingres_prepare|ingres_query|ingres_result_seek|ingres_rollback|ingres_set_environment|' + 'ingres_unbuffered_query|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|innamespace|inotify_add_watch|inotify_init|inotify_queue_len|' + 'inotify_read|inotify_rm_watch|interface_exists|intl_error_name|intl_get_error_code|intl_get_error_message|intl_is_failure|' + 'intldateformatter|intval|invalidargumentexception|invoke|invokeargs|ip2long|iptcembed|iptcparse|is_a|is_array|is_bool|is_callable|is_dir|' + 'is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|' + 'is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|isabstract|' + 'iscloneable|isdisabled|isfinal|isinstance|isinstantiable|isinterface|isinternal|isiterateable|isset|issubclassof|isuserdefined|iterator|' + 'iterator_apply|iterator_count|iterator_to_array|iteratoraggregate|iteratoriterator|java_last_exception_clear|java_last_exception_get|' + 'jddayofweek|jdmonthname|jdtofrench|jdtogregorian|jdtojewish|jdtojulian|jdtounix|jewishtojd|join|jpeg2wbmp|json_decode|json_encode|' + 'json_last_error|jsonserializable|judy|judy_type|judy_version|juliantojd|kadm5_chpass_principal|kadm5_create_principal|' + 'kadm5_delete_principal|kadm5_destroy|kadm5_flush|kadm5_get_policies|kadm5_get_principal|kadm5_get_principals|kadm5_init_with_password|' + 'kadm5_modify_principal|key|krsort|ksort|lcfirst|lcg_value|lchgrp|lchown|ldap_8859_to_t61|ldap_add|ldap_bind|ldap_close|ldap_compare|' + 'ldap_connect|ldap_count_entries|ldap_delete|ldap_dn2ufn|ldap_err2str|ldap_errno|ldap_error|ldap_explode_dn|ldap_first_attribute|' + 'ldap_first_entry|ldap_first_reference|ldap_free_result|ldap_get_attributes|ldap_get_dn|ldap_get_entries|ldap_get_option|ldap_get_values|' + 'ldap_get_values_len|ldap_list|ldap_mod_add|ldap_mod_del|ldap_mod_replace|ldap_modify|ldap_next_attribute|ldap_next_entry|' + 'ldap_next_reference|ldap_parse_reference|ldap_parse_result|ldap_read|ldap_rename|ldap_sasl_bind|ldap_search|ldap_set_option|' + 'ldap_set_rebind_proc|ldap_sort|ldap_start_tls|ldap_t61_to_8859|ldap_unbind|lengthexception|levenshtein|libxml_clear_errors|' + 'libxml_disable_entity_loader|libxml_get_errors|libxml_get_last_error|libxml_set_streams_context|libxml_use_internal_errors|libxmlerror|' + 'limititerator|link|linkinfo|list|locale|localeconv|localtime|log|log10|log1p|logicexception|long2ip|lstat|ltrim|lzf_compress|' + 'lzf_decompress|lzf_optimized_for|m_checkstatus|m_completeauthorizations|m_connect|m_connectionerror|m_deletetrans|m_destroyconn|' + 'm_destroyengine|m_getcell|m_getcellbynum|m_getcommadelimited|m_getheader|m_initconn|m_initengine|m_iscommadelimited|m_maxconntimeout|' + 'm_monitor|m_numcolumns|m_numrows|m_parsecommadelimited|m_responsekeys|m_responseparam|m_returnstatus|m_setblocking|m_setdropfile|m_setip|' + 'm_setssl|m_setssl_cafile|m_setssl_files|m_settimeout|m_sslcert_gen_hash|m_transactionssent|m_transinqueue|m_transkeyval|m_transnew|' + 'm_transsend|m_uwait|m_validateidentifier|m_verifyconnection|m_verifysslcert|magic_quotes_runtime|mail|' + 'mailparse_determine_best_xfer_encoding|mailparse_msg_create|mailparse_msg_extract_part|mailparse_msg_extract_part_file|' + 'mailparse_msg_extract_whole_part_file|mailparse_msg_free|mailparse_msg_get_part|mailparse_msg_get_part_data|mailparse_msg_get_structure|' + 'mailparse_msg_parse|mailparse_msg_parse_file|mailparse_rfc822_parse_addresses|mailparse_stream_encode|mailparse_uudecode_all|main|max|' + 'maxdb_affected_rows|maxdb_autocommit|maxdb_bind_param|maxdb_bind_result|maxdb_change_user|maxdb_character_set_name|maxdb_client_encoding|' + 'maxdb_close|maxdb_close_long_data|maxdb_commit|maxdb_connect|maxdb_connect_errno|maxdb_connect_error|maxdb_data_seek|maxdb_debug|' + 'maxdb_disable_reads_from_master|maxdb_disable_rpl_parse|maxdb_dump_debug_info|maxdb_embedded_connect|maxdb_enable_reads_from_master|' + 'maxdb_enable_rpl_parse|maxdb_errno|maxdb_error|maxdb_escape_string|maxdb_execute|maxdb_fetch|maxdb_fetch_array|maxdb_fetch_assoc|' + 'maxdb_fetch_field|maxdb_fetch_field_direct|maxdb_fetch_fields|maxdb_fetch_lengths|maxdb_fetch_object|maxdb_fetch_row|maxdb_field_count|' + 'maxdb_field_seek|maxdb_field_tell|maxdb_free_result|maxdb_get_client_info|maxdb_get_client_version|maxdb_get_host_info|maxdb_get_metadata|' + 'maxdb_get_proto_info|maxdb_get_server_info|maxdb_get_server_version|maxdb_info|maxdb_init|maxdb_insert_id|maxdb_kill|maxdb_master_query|' + 'maxdb_more_results|maxdb_multi_query|maxdb_next_result|maxdb_num_fields|maxdb_num_rows|maxdb_options|maxdb_param_count|maxdb_ping|' + 'maxdb_prepare|maxdb_query|maxdb_real_connect|maxdb_real_escape_string|maxdb_real_query|maxdb_report|maxdb_rollback|' + 'maxdb_rpl_parse_enabled|maxdb_rpl_probe|maxdb_rpl_query_type|maxdb_select_db|maxdb_send_long_data|maxdb_send_query|maxdb_server_end|' + 'maxdb_server_init|maxdb_set_opt|maxdb_sqlstate|maxdb_ssl_set|maxdb_stat|maxdb_stmt_affected_rows|maxdb_stmt_bind_param|' + 'maxdb_stmt_bind_result|maxdb_stmt_close|maxdb_stmt_close_long_data|maxdb_stmt_data_seek|maxdb_stmt_errno|maxdb_stmt_error|' + 'maxdb_stmt_execute|maxdb_stmt_fetch|maxdb_stmt_free_result|maxdb_stmt_init|maxdb_stmt_num_rows|maxdb_stmt_param_count|maxdb_stmt_prepare|' + 'maxdb_stmt_reset|maxdb_stmt_result_metadata|maxdb_stmt_send_long_data|maxdb_stmt_sqlstate|maxdb_stmt_store_result|maxdb_store_result|' + 'maxdb_thread_id|maxdb_thread_safe|maxdb_use_result|maxdb_warning_count|mb_check_encoding|mb_convert_case|mb_convert_encoding|' + 'mb_convert_kana|mb_convert_variables|mb_decode_mimeheader|mb_decode_numericentity|mb_detect_encoding|mb_detect_order|mb_encode_mimeheader|' + 'mb_encode_numericentity|mb_encoding_aliases|mb_ereg|mb_ereg_match|mb_ereg_replace|mb_ereg_search|mb_ereg_search_getpos|' + 'mb_ereg_search_getregs|mb_ereg_search_init|mb_ereg_search_pos|mb_ereg_search_regs|mb_ereg_search_setpos|mb_eregi|mb_eregi_replace|' + 'mb_get_info|mb_http_input|mb_http_output|mb_internal_encoding|mb_language|mb_list_encodings|mb_output_handler|mb_parse_str|' + 'mb_preferred_mime_name|mb_regex_encoding|mb_regex_set_options|mb_send_mail|mb_split|mb_strcut|mb_strimwidth|mb_stripos|mb_stristr|' + 'mb_strlen|mb_strpos|mb_strrchr|mb_strrichr|mb_strripos|mb_strrpos|mb_strstr|mb_strtolower|mb_strtoupper|mb_strwidth|' + 'mb_substitute_character|mb_substr|mb_substr_count|mcrypt_cbc|mcrypt_cfb|mcrypt_create_iv|mcrypt_decrypt|mcrypt_ecb|' + 'mcrypt_enc_get_algorithms_name|mcrypt_enc_get_block_size|mcrypt_enc_get_iv_size|mcrypt_enc_get_key_size|mcrypt_enc_get_modes_name|' + 'mcrypt_enc_get_supported_key_sizes|mcrypt_enc_is_block_algorithm|mcrypt_enc_is_block_algorithm_mode|mcrypt_enc_is_block_mode|' + 'mcrypt_enc_self_test|mcrypt_encrypt|mcrypt_generic|mcrypt_generic_deinit|mcrypt_generic_end|mcrypt_generic_init|mcrypt_get_block_size|' + 'mcrypt_get_cipher_name|mcrypt_get_iv_size|mcrypt_get_key_size|mcrypt_list_algorithms|mcrypt_list_modes|mcrypt_module_close|' + 'mcrypt_module_get_algo_block_size|mcrypt_module_get_algo_key_size|mcrypt_module_get_supported_key_sizes|mcrypt_module_is_block_algorithm|' + 'mcrypt_module_is_block_algorithm_mode|mcrypt_module_is_block_mode|mcrypt_module_open|mcrypt_module_self_test|mcrypt_ofb|md5|md5_file|' + 'mdecrypt_generic|memcache|memcache_debug|memcached|memory_get_peak_usage|memory_get_usage|messageformatter|metaphone|method_exists|mhash|' + 'mhash_count|mhash_get_block_size|mhash_get_hash_name|mhash_keygen_s2k|microtime|mime_content_type|min|ming_keypress|' + 'ming_setcubicthreshold|ming_setscale|ming_setswfcompression|ming_useconstants|ming_useswfversion|mkdir|mktime|money_format|mongo|' + 'mongobindata|mongocode|mongocollection|mongoconnectionexception|mongocursor|mongocursorexception|mongocursortimeoutexception|mongodate|' + 'mongodb|mongodbref|mongoexception|mongogridfs|mongogridfscursor|mongogridfsexception|mongogridfsfile|mongoid|mongoint32|mongoint64|' + 'mongomaxkey|mongominkey|mongoregex|mongotimestamp|move_uploaded_file|mpegfile|mqseries_back|mqseries_begin|mqseries_close|mqseries_cmit|' + 'mqseries_conn|mqseries_connx|mqseries_disc|mqseries_get|mqseries_inq|mqseries_open|mqseries_put|mqseries_put1|mqseries_set|' + 'mqseries_strerror|msession_connect|msession_count|msession_create|msession_destroy|msession_disconnect|msession_find|msession_get|' + 'msession_get_array|msession_get_data|msession_inc|msession_list|msession_listvar|msession_lock|msession_plugin|msession_randstr|' + 'msession_set|msession_set_array|msession_set_data|msession_timeout|msession_uniq|msession_unlock|msg_get_queue|msg_queue_exists|' + 'msg_receive|msg_remove_queue|msg_send|msg_set_queue|msg_stat_queue|msql|msql_affected_rows|msql_close|msql_connect|msql_create_db|' + 'msql_createdb|msql_data_seek|msql_db_query|msql_dbname|msql_drop_db|msql_error|msql_fetch_array|msql_fetch_field|msql_fetch_object|' + 'msql_fetch_row|msql_field_flags|msql_field_len|msql_field_name|msql_field_seek|msql_field_table|msql_field_type|msql_fieldflags|' + 'msql_fieldlen|msql_fieldname|msql_fieldtable|msql_fieldtype|msql_free_result|msql_list_dbs|msql_list_fields|msql_list_tables|' + 'msql_num_fields|msql_num_rows|msql_numfields|msql_numrows|msql_pconnect|msql_query|msql_regcase|msql_result|msql_select_db|msql_tablename|' + 'mssql_bind|mssql_close|mssql_connect|mssql_data_seek|mssql_execute|mssql_fetch_array|mssql_fetch_assoc|mssql_fetch_batch|' + 'mssql_fetch_field|mssql_fetch_object|mssql_fetch_row|mssql_field_length|mssql_field_name|mssql_field_seek|mssql_field_type|' + 'mssql_free_result|mssql_free_statement|mssql_get_last_message|mssql_guid_string|mssql_init|mssql_min_error_severity|' + 'mssql_min_message_severity|mssql_next_result|mssql_num_fields|mssql_num_rows|mssql_pconnect|mssql_query|mssql_result|mssql_rows_affected|' + 'mssql_select_db|mt_getrandmax|mt_rand|mt_srand|multipleiterator|mysql_affected_rows|mysql_client_encoding|mysql_close|mysql_connect|' + 'mysql_create_db|mysql_data_seek|mysql_db_name|mysql_db_query|mysql_drop_db|mysql_errno|mysql_error|mysql_escape_string|mysql_fetch_array|' + 'mysql_fetch_assoc|mysql_fetch_field|mysql_fetch_lengths|mysql_fetch_object|mysql_fetch_row|mysql_field_flags|mysql_field_len|' + 'mysql_field_name|mysql_field_seek|mysql_field_table|mysql_field_type|mysql_free_result|mysql_get_client_info|mysql_get_host_info|' + 'mysql_get_proto_info|mysql_get_server_info|mysql_info|mysql_insert_id|mysql_list_dbs|mysql_list_fields|mysql_list_processes|' + 'mysql_list_tables|mysql_num_fields|mysql_num_rows|mysql_pconnect|mysql_ping|mysql_query|mysql_real_escape_string|mysql_result|' + 'mysql_select_db|mysql_set_charset|mysql_stat|mysql_tablename|mysql_thread_id|mysql_unbuffered_query|mysqli|mysqli_bind_param|' + 'mysqli_bind_result|mysqli_client_encoding|mysqli_connect|mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_driver|' + 'mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_escape_string|mysqli_execute|mysqli_fetch|mysqli_get_metadata|' + 'mysqli_master_query|mysqli_param_count|mysqli_report|mysqli_result|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|' + 'mysqli_send_long_data|mysqli_send_query|mysqli_set_opt|mysqli_slave_query|mysqli_stmt|mysqli_warning|mysqlnd_ms_get_stats|' + 'mysqlnd_ms_query_is_select|mysqlnd_ms_set_user_pick_server|mysqlnd_qc_change_handler|mysqlnd_qc_clear_cache|mysqlnd_qc_get_cache_info|' + 'mysqlnd_qc_get_core_stats|mysqlnd_qc_get_handler|mysqlnd_qc_get_query_trace_log|mysqlnd_qc_set_user_handlers|natcasesort|natsort|' + 'ncurses_addch|ncurses_addchnstr|ncurses_addchstr|ncurses_addnstr|ncurses_addstr|ncurses_assume_default_colors|ncurses_attroff|' + 'ncurses_attron|ncurses_attrset|ncurses_baudrate|ncurses_beep|ncurses_bkgd|ncurses_bkgdset|ncurses_border|ncurses_bottom_panel|' + 'ncurses_can_change_color|ncurses_cbreak|ncurses_clear|ncurses_clrtobot|ncurses_clrtoeol|ncurses_color_content|ncurses_color_set|' + 'ncurses_curs_set|ncurses_def_prog_mode|ncurses_def_shell_mode|ncurses_define_key|ncurses_del_panel|ncurses_delay_output|ncurses_delch|' + 'ncurses_deleteln|ncurses_delwin|ncurses_doupdate|ncurses_echo|ncurses_echochar|ncurses_end|ncurses_erase|ncurses_erasechar|ncurses_filter|' + 'ncurses_flash|ncurses_flushinp|ncurses_getch|ncurses_getmaxyx|ncurses_getmouse|ncurses_getyx|ncurses_halfdelay|ncurses_has_colors|' + 'ncurses_has_ic|ncurses_has_il|ncurses_has_key|ncurses_hide_panel|ncurses_hline|ncurses_inch|ncurses_init|ncurses_init_color|' + 'ncurses_init_pair|ncurses_insch|ncurses_insdelln|ncurses_insertln|ncurses_insstr|ncurses_instr|ncurses_isendwin|ncurses_keyok|' + 'ncurses_keypad|ncurses_killchar|ncurses_longname|ncurses_meta|ncurses_mouse_trafo|ncurses_mouseinterval|ncurses_mousemask|ncurses_move|' + 'ncurses_move_panel|ncurses_mvaddch|ncurses_mvaddchnstr|ncurses_mvaddchstr|ncurses_mvaddnstr|ncurses_mvaddstr|ncurses_mvcur|' + 'ncurses_mvdelch|ncurses_mvgetch|ncurses_mvhline|ncurses_mvinch|ncurses_mvvline|ncurses_mvwaddstr|ncurses_napms|ncurses_new_panel|' + 'ncurses_newpad|ncurses_newwin|ncurses_nl|ncurses_nocbreak|ncurses_noecho|ncurses_nonl|ncurses_noqiflush|ncurses_noraw|' + 'ncurses_pair_content|ncurses_panel_above|ncurses_panel_below|ncurses_panel_window|ncurses_pnoutrefresh|ncurses_prefresh|ncurses_putp|' + 'ncurses_qiflush|ncurses_raw|ncurses_refresh|ncurses_replace_panel|ncurses_reset_prog_mode|ncurses_reset_shell_mode|ncurses_resetty|' + 'ncurses_savetty|ncurses_scr_dump|ncurses_scr_init|ncurses_scr_restore|ncurses_scr_set|ncurses_scrl|ncurses_show_panel|ncurses_slk_attr|' + 'ncurses_slk_attroff|ncurses_slk_attron|ncurses_slk_attrset|ncurses_slk_clear|ncurses_slk_color|ncurses_slk_init|ncurses_slk_noutrefresh|' + 'ncurses_slk_refresh|ncurses_slk_restore|ncurses_slk_set|ncurses_slk_touch|ncurses_standend|ncurses_standout|ncurses_start_color|' + 'ncurses_termattrs|ncurses_termname|ncurses_timeout|ncurses_top_panel|ncurses_typeahead|ncurses_ungetch|ncurses_ungetmouse|' + 'ncurses_update_panels|ncurses_use_default_colors|ncurses_use_env|ncurses_use_extended_names|ncurses_vidattr|ncurses_vline|ncurses_waddch|' + 'ncurses_waddstr|ncurses_wattroff|ncurses_wattron|ncurses_wattrset|ncurses_wborder|ncurses_wclear|ncurses_wcolor_set|ncurses_werase|' + 'ncurses_wgetch|ncurses_whline|ncurses_wmouse_trafo|ncurses_wmove|ncurses_wnoutrefresh|ncurses_wrefresh|ncurses_wstandend|' + 'ncurses_wstandout|ncurses_wvline|newinstance|newinstanceargs|newt_bell|newt_button|newt_button_bar|newt_centered_window|newt_checkbox|' + 'newt_checkbox_get_value|newt_checkbox_set_flags|newt_checkbox_set_value|newt_checkbox_tree|newt_checkbox_tree_add_item|' + 'newt_checkbox_tree_find_item|newt_checkbox_tree_get_current|newt_checkbox_tree_get_entry_value|newt_checkbox_tree_get_multi_selection|' + 'newt_checkbox_tree_get_selection|newt_checkbox_tree_multi|newt_checkbox_tree_set_current|newt_checkbox_tree_set_entry|' + 'newt_checkbox_tree_set_entry_value|newt_checkbox_tree_set_width|newt_clear_key_buffer|newt_cls|newt_compact_button|' + 'newt_component_add_callback|newt_component_takes_focus|newt_create_grid|newt_cursor_off|newt_cursor_on|newt_delay|newt_draw_form|' + 'newt_draw_root_text|newt_entry|newt_entry_get_value|newt_entry_set|newt_entry_set_filter|newt_entry_set_flags|newt_finished|newt_form|' + 'newt_form_add_component|newt_form_add_components|newt_form_add_hot_key|newt_form_destroy|newt_form_get_current|newt_form_run|' + 'newt_form_set_background|newt_form_set_height|newt_form_set_size|newt_form_set_timer|newt_form_set_width|newt_form_watch_fd|' + 'newt_get_screen_size|newt_grid_add_components_to_form|newt_grid_basic_window|newt_grid_free|newt_grid_get_size|newt_grid_h_close_stacked|' + 'newt_grid_h_stacked|newt_grid_place|newt_grid_set_field|newt_grid_simple_window|newt_grid_v_close_stacked|newt_grid_v_stacked|' + 'newt_grid_wrapped_window|newt_grid_wrapped_window_at|newt_init|newt_label|newt_label_set_text|newt_listbox|newt_listbox_append_entry|' + 'newt_listbox_clear|newt_listbox_clear_selection|newt_listbox_delete_entry|newt_listbox_get_current|newt_listbox_get_selection|' + 'newt_listbox_insert_entry|newt_listbox_item_count|newt_listbox_select_item|newt_listbox_set_current|newt_listbox_set_current_by_key|' + 'newt_listbox_set_data|newt_listbox_set_entry|newt_listbox_set_width|newt_listitem|newt_listitem_get_data|newt_listitem_set|' + 'newt_open_window|newt_pop_help_line|newt_pop_window|newt_push_help_line|newt_radio_get_current|newt_radiobutton|newt_redraw_help_line|' + 'newt_reflow_text|newt_refresh|newt_resize_screen|newt_resume|newt_run_form|newt_scale|newt_scale_set|newt_scrollbar_set|' + 'newt_set_help_callback|newt_set_suspend_callback|newt_suspend|newt_textbox|newt_textbox_get_num_lines|newt_textbox_reflowed|' + 'newt_textbox_set_height|newt_textbox_set_text|newt_vertical_scrollbar|newt_wait_for_key|newt_win_choice|newt_win_entries|newt_win_menu|' + 'newt_win_message|newt_win_messagev|newt_win_ternary|next|ngettext|nl2br|nl_langinfo|norewinditerator|normalizer|notes_body|notes_copy_db|' + 'notes_create_db|notes_create_note|notes_drop_db|notes_find_note|notes_header_info|notes_list_msgs|notes_mark_read|notes_mark_unread|' + 'notes_nav_create|notes_search|notes_unread|notes_version|nsapi_request_headers|nsapi_response_headers|nsapi_virtual|nthmac|number_format|' + 'numberformatter|oauth|oauth_get_sbs|oauth_urlencode|oauthexception|oauthprovider|ob_clean|ob_deflatehandler|ob_end_clean|ob_end_flush|' + 'ob_etaghandler|ob_flush|ob_get_clean|ob_get_contents|ob_get_flush|ob_get_length|ob_get_level|ob_get_status|ob_gzhandler|ob_iconv_handler|' + 'ob_implicit_flush|ob_inflatehandler|ob_list_handlers|ob_start|ob_tidyhandler|oci_bind_array_by_name|oci_bind_by_name|oci_cancel|' + 'oci_client_version|oci_close|oci_collection_append|oci_collection_assign|oci_collection_element_assign|oci_collection_element_get|' + 'oci_collection_free|oci_collection_max|oci_collection_size|oci_collection_trim|oci_commit|oci_connect|oci_define_by_name|oci_error|' + 'oci_execute|oci_fetch|oci_fetch_all|oci_fetch_array|oci_fetch_assoc|oci_fetch_object|oci_fetch_row|oci_field_is_null|oci_field_name|' + 'oci_field_precision|oci_field_scale|oci_field_size|oci_field_type|oci_field_type_raw|oci_free_statement|oci_internal_debug|oci_lob_append|' + 'oci_lob_close|oci_lob_copy|oci_lob_eof|oci_lob_erase|oci_lob_export|oci_lob_flush|oci_lob_free|oci_lob_getbuffering|oci_lob_import|' + 'oci_lob_is_equal|oci_lob_load|oci_lob_read|oci_lob_rewind|oci_lob_save|oci_lob_savefile|oci_lob_seek|oci_lob_setbuffering|oci_lob_size|' + 'oci_lob_tell|oci_lob_truncate|oci_lob_write|oci_lob_writetemporary|oci_lob_writetofile|oci_new_collection|oci_new_connect|oci_new_cursor|' + 'oci_new_descriptor|oci_num_fields|oci_num_rows|oci_parse|oci_password_change|oci_pconnect|oci_result|oci_rollback|oci_server_version|' + 'oci_set_action|oci_set_client_identifier|oci_set_client_info|oci_set_edition|oci_set_module_name|oci_set_prefetch|oci_statement_type|' + 'ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|' + 'ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|' + 'ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|' + 'ociloadlob|ocilogoff|ocilogon|ocinewcollection|ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|' + 'ocirollback|ocirowcount|ocisavelob|ocisavelobfile|ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|' + 'octdec|odbc_autocommit|odbc_binmode|odbc_close|odbc_close_all|odbc_columnprivileges|odbc_columns|odbc_commit|odbc_connect|odbc_cursor|' + 'odbc_data_source|odbc_do|odbc_error|odbc_errormsg|odbc_exec|odbc_execute|odbc_fetch_array|odbc_fetch_into|odbc_fetch_object|' + 'odbc_fetch_row|odbc_field_len|odbc_field_name|odbc_field_num|odbc_field_precision|odbc_field_scale|odbc_field_type|odbc_foreignkeys|' + 'odbc_free_result|odbc_gettypeinfo|odbc_longreadlen|odbc_next_result|odbc_num_fields|odbc_num_rows|odbc_pconnect|odbc_prepare|' + 'odbc_primarykeys|odbc_procedurecolumns|odbc_procedures|odbc_result|odbc_result_all|odbc_rollback|odbc_setoption|odbc_specialcolumns|' + 'odbc_statistics|odbc_tableprivileges|odbc_tables|openal_buffer_create|openal_buffer_data|openal_buffer_destroy|openal_buffer_get|' + 'openal_buffer_loadwav|openal_context_create|openal_context_current|openal_context_destroy|openal_context_process|openal_context_suspend|' + 'openal_device_close|openal_device_open|openal_listener_get|openal_listener_set|openal_source_create|openal_source_destroy|' + 'openal_source_get|openal_source_pause|openal_source_play|openal_source_rewind|openal_source_set|openal_source_stop|openal_stream|opendir|' + 'openlog|openssl_cipher_iv_length|openssl_csr_export|openssl_csr_export_to_file|openssl_csr_get_public_key|openssl_csr_get_subject|' + 'openssl_csr_new|openssl_csr_sign|openssl_decrypt|openssl_dh_compute_key|openssl_digest|openssl_encrypt|openssl_error_string|' + 'openssl_free_key|openssl_get_cipher_methods|openssl_get_md_methods|openssl_get_privatekey|openssl_get_publickey|openssl_open|' + 'openssl_pkcs12_export|openssl_pkcs12_export_to_file|openssl_pkcs12_read|openssl_pkcs7_decrypt|openssl_pkcs7_encrypt|openssl_pkcs7_sign|' + 'openssl_pkcs7_verify|openssl_pkey_export|openssl_pkey_export_to_file|openssl_pkey_free|openssl_pkey_get_details|openssl_pkey_get_private|' + 'openssl_pkey_get_public|openssl_pkey_new|openssl_private_decrypt|openssl_private_encrypt|openssl_public_decrypt|openssl_public_encrypt|' + 'openssl_random_pseudo_bytes|openssl_seal|openssl_sign|openssl_verify|openssl_x509_check_private_key|openssl_x509_checkpurpose|' + 'openssl_x509_export|openssl_x509_export_to_file|openssl_x509_free|openssl_x509_parse|openssl_x509_read|ord|outeriterator|' + 'outofboundsexception|outofrangeexception|output_add_rewrite_var|output_reset_rewrite_vars|overflowexception|overload|override_function|' + 'ovrimos_close|ovrimos_commit|ovrimos_connect|ovrimos_cursor|ovrimos_exec|ovrimos_execute|ovrimos_fetch_into|ovrimos_fetch_row|' + 'ovrimos_field_len|ovrimos_field_name|ovrimos_field_num|ovrimos_field_type|ovrimos_free_result|ovrimos_longreadlen|ovrimos_num_fields|' + 'ovrimos_num_rows|ovrimos_prepare|ovrimos_result|ovrimos_result_all|ovrimos_rollback|pack|parentiterator|parse_ini_file|parse_ini_string|' + 'parse_str|parse_url|parsekit_compile_file|parsekit_compile_string|parsekit_func_arginfo|passthru|pathinfo|pclose|pcntl_alarm|pcntl_exec|' + 'pcntl_fork|pcntl_getpriority|pcntl_setpriority|pcntl_signal|pcntl_signal_dispatch|pcntl_sigprocmask|pcntl_sigtimedwait|pcntl_sigwaitinfo|' + 'pcntl_wait|pcntl_waitpid|pcntl_wexitstatus|pcntl_wifexited|pcntl_wifsignaled|pcntl_wifstopped|pcntl_wstopsig|pcntl_wtermsig|' + 'pdf_activate_item|pdf_add_annotation|pdf_add_bookmark|pdf_add_launchlink|pdf_add_locallink|pdf_add_nameddest|pdf_add_note|pdf_add_outline|' + 'pdf_add_pdflink|pdf_add_table_cell|pdf_add_textflow|pdf_add_thumbnail|pdf_add_weblink|pdf_arc|pdf_arcn|pdf_attach_file|pdf_begin_document|' + 'pdf_begin_font|pdf_begin_glyph|pdf_begin_item|pdf_begin_layer|pdf_begin_page|pdf_begin_page_ext|pdf_begin_pattern|pdf_begin_template|' + 'pdf_begin_template_ext|pdf_circle|pdf_clip|pdf_close|pdf_close_image|pdf_close_pdi|pdf_close_pdi_page|pdf_closepath|' + 'pdf_closepath_fill_stroke|pdf_closepath_stroke|pdf_concat|pdf_continue_text|pdf_create_3dview|pdf_create_action|pdf_create_annotation|' + 'pdf_create_bookmark|pdf_create_field|pdf_create_fieldgroup|pdf_create_gstate|pdf_create_pvf|pdf_create_textflow|pdf_curveto|' + 'pdf_define_layer|pdf_delete|pdf_delete_pvf|pdf_delete_table|pdf_delete_textflow|pdf_encoding_set_char|pdf_end_document|pdf_end_font|' + 'pdf_end_glyph|pdf_end_item|pdf_end_layer|pdf_end_page|pdf_end_page_ext|pdf_end_pattern|pdf_end_template|pdf_endpath|pdf_fill|' + 'pdf_fill_imageblock|pdf_fill_pdfblock|pdf_fill_stroke|pdf_fill_textblock|pdf_findfont|pdf_fit_image|pdf_fit_pdi_page|pdf_fit_table|' + 'pdf_fit_textflow|pdf_fit_textline|pdf_get_apiname|pdf_get_buffer|pdf_get_errmsg|pdf_get_errnum|pdf_get_font|pdf_get_fontname|' + 'pdf_get_fontsize|pdf_get_image_height|pdf_get_image_width|pdf_get_majorversion|pdf_get_minorversion|pdf_get_parameter|' + 'pdf_get_pdi_parameter|pdf_get_pdi_value|pdf_get_value|pdf_info_font|pdf_info_matchbox|pdf_info_table|pdf_info_textflow|pdf_info_textline|' + 'pdf_initgraphics|pdf_lineto|pdf_load_3ddata|pdf_load_font|pdf_load_iccprofile|pdf_load_image|pdf_makespotcolor|pdf_moveto|pdf_new|' + 'pdf_open_ccitt|pdf_open_file|pdf_open_gif|pdf_open_image|pdf_open_image_file|pdf_open_jpeg|pdf_open_memory_image|pdf_open_pdi|' + 'pdf_open_pdi_document|pdf_open_pdi_page|pdf_open_tiff|pdf_pcos_get_number|pdf_pcos_get_stream|pdf_pcos_get_string|pdf_place_image|' + 'pdf_place_pdi_page|pdf_process_pdi|pdf_rect|pdf_restore|pdf_resume_page|pdf_rotate|pdf_save|pdf_scale|pdf_set_border_color|' + 'pdf_set_border_dash|pdf_set_border_style|pdf_set_char_spacing|pdf_set_duration|pdf_set_gstate|pdf_set_horiz_scaling|pdf_set_info|' + 'pdf_set_info_author|pdf_set_info_creator|pdf_set_info_keywords|pdf_set_info_subject|pdf_set_info_title|pdf_set_layer_dependency|' + 'pdf_set_leading|pdf_set_parameter|pdf_set_text_matrix|pdf_set_text_pos|pdf_set_text_rendering|pdf_set_text_rise|pdf_set_value|' + 'pdf_set_word_spacing|pdf_setcolor|pdf_setdash|pdf_setdashpattern|pdf_setflat|pdf_setfont|pdf_setgray|pdf_setgray_fill|pdf_setgray_stroke|' + 'pdf_setlinecap|pdf_setlinejoin|pdf_setlinewidth|pdf_setmatrix|pdf_setmiterlimit|pdf_setpolydash|pdf_setrgbcolor|pdf_setrgbcolor_fill|' + 'pdf_setrgbcolor_stroke|pdf_shading|pdf_shading_pattern|pdf_shfill|pdf_show|pdf_show_boxed|pdf_show_xy|pdf_skew|pdf_stringwidth|pdf_stroke|' + 'pdf_suspend_page|pdf_translate|pdf_utf16_to_utf8|pdf_utf32_to_utf16|pdf_utf8_to_utf16|pdo|pdo_cubrid_schema|pdo_pgsqllobcreate|' + 'pdo_pgsqllobopen|pdo_pgsqllobunlink|pdo_sqlitecreateaggregate|pdo_sqlitecreatefunction|pdoexception|pdostatement|pfsockopen|' + 'pg_affected_rows|pg_cancel_query|pg_client_encoding|pg_close|pg_connect|pg_connection_busy|pg_connection_reset|pg_connection_status|' + 'pg_convert|pg_copy_from|pg_copy_to|pg_dbname|pg_delete|pg_end_copy|pg_escape_bytea|pg_escape_string|pg_execute|pg_fetch_all|' + 'pg_fetch_all_columns|pg_fetch_array|pg_fetch_assoc|pg_fetch_object|pg_fetch_result|pg_fetch_row|pg_field_is_null|pg_field_name|' + 'pg_field_num|pg_field_prtlen|pg_field_size|pg_field_table|pg_field_type|pg_field_type_oid|pg_free_result|pg_get_notify|pg_get_pid|' + 'pg_get_result|pg_host|pg_insert|pg_last_error|pg_last_notice|pg_last_oid|pg_lo_close|pg_lo_create|pg_lo_export|pg_lo_import|pg_lo_open|' + 'pg_lo_read|pg_lo_read_all|pg_lo_seek|pg_lo_tell|pg_lo_unlink|pg_lo_write|pg_meta_data|pg_num_fields|pg_num_rows|pg_options|' + 'pg_parameter_status|pg_pconnect|pg_ping|pg_port|pg_prepare|pg_put_line|pg_query|pg_query_params|pg_result_error|pg_result_error_field|' + 'pg_result_seek|pg_result_status|pg_select|pg_send_execute|pg_send_prepare|pg_send_query|pg_send_query_params|pg_set_client_encoding|' + 'pg_set_error_verbosity|pg_trace|pg_transaction_status|pg_tty|pg_unescape_bytea|pg_untrace|pg_update|pg_version|php_check_syntax|' + 'php_ini_loaded_file|php_ini_scanned_files|php_logo_guid|php_sapi_name|php_strip_whitespace|php_uname|phpcredits|phpinfo|phpversion|pi|' + 'png2wbmp|popen|pos|posix_access|posix_ctermid|posix_errno|posix_get_last_error|posix_getcwd|posix_getegid|posix_geteuid|posix_getgid|' + 'posix_getgrgid|posix_getgrnam|posix_getgroups|posix_getlogin|posix_getpgid|posix_getpgrp|posix_getpid|posix_getppid|posix_getpwnam|' + 'posix_getpwuid|posix_getrlimit|posix_getsid|posix_getuid|posix_initgroups|posix_isatty|posix_kill|posix_mkfifo|posix_mknod|posix_setegid|' + 'posix_seteuid|posix_setgid|posix_setpgid|posix_setsid|posix_setuid|posix_strerror|posix_times|posix_ttyname|posix_uname|pow|preg_filter|' + 'preg_grep|preg_last_error|preg_match|preg_match_all|preg_quote|preg_replace|preg_replace_callback|preg_split|prev|print|print_r|' + 'printer_abort|printer_close|printer_create_brush|printer_create_dc|printer_create_font|printer_create_pen|printer_delete_brush|' + 'printer_delete_dc|printer_delete_font|printer_delete_pen|printer_draw_bmp|printer_draw_chord|printer_draw_elipse|printer_draw_line|' + 'printer_draw_pie|printer_draw_rectangle|printer_draw_roundrect|printer_draw_text|printer_end_doc|printer_end_page|printer_get_option|' + 'printer_list|printer_logical_fontheight|printer_open|printer_select_brush|printer_select_font|printer_select_pen|printer_set_option|' + 'printer_start_doc|printer_start_page|printer_write|printf|proc_close|proc_get_status|proc_nice|proc_open|proc_terminate|property_exists|' + 'ps_add_bookmark|ps_add_launchlink|ps_add_locallink|ps_add_note|ps_add_pdflink|ps_add_weblink|ps_arc|ps_arcn|ps_begin_page|' + 'ps_begin_pattern|ps_begin_template|ps_circle|ps_clip|ps_close|ps_close_image|ps_closepath|ps_closepath_stroke|ps_continue_text|ps_curveto|' + 'ps_delete|ps_end_page|ps_end_pattern|ps_end_template|ps_fill|ps_fill_stroke|ps_findfont|ps_get_buffer|ps_get_parameter|ps_get_value|' + 'ps_hyphenate|ps_include_file|ps_lineto|ps_makespotcolor|ps_moveto|ps_new|ps_open_file|ps_open_image|ps_open_image_file|' + 'ps_open_memory_image|ps_place_image|ps_rect|ps_restore|ps_rotate|ps_save|ps_scale|ps_set_border_color|ps_set_border_dash|' + 'ps_set_border_style|ps_set_info|ps_set_parameter|ps_set_text_pos|ps_set_value|ps_setcolor|ps_setdash|ps_setflat|ps_setfont|ps_setgray|' + 'ps_setlinecap|ps_setlinejoin|ps_setlinewidth|ps_setmiterlimit|ps_setoverprintmode|ps_setpolydash|ps_shading|ps_shading_pattern|ps_shfill|' + 'ps_show|ps_show2|ps_show_boxed|ps_show_xy|ps_show_xy2|ps_string_geometry|ps_stringwidth|ps_stroke|ps_symbol|ps_symbol_name|' + 'ps_symbol_width|ps_translate|pspell_add_to_personal|pspell_add_to_session|pspell_check|pspell_clear_session|pspell_config_create|' + 'pspell_config_data_dir|pspell_config_dict_dir|pspell_config_ignore|pspell_config_mode|pspell_config_personal|pspell_config_repl|' + 'pspell_config_runtogether|pspell_config_save_repl|pspell_new|pspell_new_config|pspell_new_personal|pspell_save_wordlist|' + 'pspell_store_replacement|pspell_suggest|putenv|px_close|px_create_fp|px_date2string|px_delete|px_delete_record|px_get_field|px_get_info|' + 'px_get_parameter|px_get_record|px_get_schema|px_get_value|px_insert_record|px_new|px_numfields|px_numrecords|px_open_fp|px_put_record|' + 'px_retrieve_record|px_set_blob_file|px_set_parameter|px_set_tablename|px_set_targetencoding|px_set_value|px_timestamp2string|' + 'px_update_record|qdom_error|qdom_tree|quoted_printable_decode|quoted_printable_encode|quotemeta|rad2deg|radius_acct_open|' + 'radius_add_server|radius_auth_open|radius_close|radius_config|radius_create_request|radius_cvt_addr|radius_cvt_int|radius_cvt_string|' + 'radius_demangle|radius_demangle_mppe_key|radius_get_attr|radius_get_vendor_attr|radius_put_addr|radius_put_attr|radius_put_int|' + 'radius_put_string|radius_put_vendor_addr|radius_put_vendor_attr|radius_put_vendor_int|radius_put_vendor_string|' + 'radius_request_authenticator|radius_send_request|radius_server_secret|radius_strerror|rand|range|rangeexception|rar_wrapper_cache_stats|' + 'rararchive|rarentry|rarexception|rawurldecode|rawurlencode|read_exif_data|readdir|readfile|readgzfile|readline|readline_add_history|' + 'readline_callback_handler_install|readline_callback_handler_remove|readline_callback_read_char|readline_clear_history|' + 'readline_completion_function|readline_info|readline_list_history|readline_on_new_line|readline_read_history|readline_redisplay|' + 'readline_write_history|readlink|realpath|realpath_cache_get|realpath_cache_size|recode|recode_file|recode_string|recursivearrayiterator|' + 'recursivecachingiterator|recursivecallbackfilteriterator|recursivedirectoryiterator|recursivefilteriterator|recursiveiterator|' + 'recursiveiteratoriterator|recursiveregexiterator|recursivetreeiterator|reflection|reflectionclass|reflectionexception|reflectionextension|' + 'reflectionfunction|reflectionfunctionabstract|reflectionmethod|reflectionobject|reflectionparameter|reflectionproperty|reflector|' + 'regexiterator|register_shutdown_function|register_tick_function|rename|rename_function|require|require_once|reset|resetValue|' + 'resourcebundle|restore_error_handler|restore_exception_handler|restore_include_path|return|rewind|rewinddir|rmdir|round|rpm_close|' + 'rpm_get_tag|rpm_is_valid|rpm_open|rpm_version|rrd_create|rrd_error|rrd_fetch|rrd_first|rrd_graph|rrd_info|rrd_last|rrd_lastupdate|' + 'rrd_restore|rrd_tune|rrd_update|rrd_xport|rrdcreator|rrdgraph|rrdupdater|rsort|rtrim|runkit_class_adopt|runkit_class_emancipate|' + 'runkit_constant_add|runkit_constant_redefine|runkit_constant_remove|runkit_function_add|runkit_function_copy|runkit_function_redefine|' + 'runkit_function_remove|runkit_function_rename|runkit_import|runkit_lint|runkit_lint_file|runkit_method_add|runkit_method_copy|' + 'runkit_method_redefine|runkit_method_remove|runkit_method_rename|runkit_return_value_used|runkit_sandbox_output_handler|' + 'runkit_superglobals|runtimeexception|samconnection_commit|samconnection_connect|samconnection_constructor|samconnection_disconnect|' + 'samconnection_errno|samconnection_error|samconnection_isconnected|samconnection_peek|samconnection_peekall|samconnection_receive|' + 'samconnection_remove|samconnection_rollback|samconnection_send|samconnection_setDebug|samconnection_subscribe|samconnection_unsubscribe|' + 'sammessage_body|sammessage_constructor|sammessage_header|sca_createdataobject|sca_getservice|sca_localproxy_createdataobject|' + 'sca_soapproxy_createdataobject|scandir|sdo_das_changesummary_beginlogging|sdo_das_changesummary_endlogging|' + 'sdo_das_changesummary_getchangeddataobjects|sdo_das_changesummary_getchangetype|sdo_das_changesummary_getoldcontainer|' + 'sdo_das_changesummary_getoldvalues|sdo_das_changesummary_islogging|sdo_das_datafactory_addpropertytotype|sdo_das_datafactory_addtype|' + 'sdo_das_datafactory_getdatafactory|sdo_das_dataobject_getchangesummary|sdo_das_relational_applychanges|sdo_das_relational_construct|' + 'sdo_das_relational_createrootdataobject|sdo_das_relational_executepreparedquery|sdo_das_relational_executequery|' + 'sdo_das_setting_getlistindex|sdo_das_setting_getpropertyindex|sdo_das_setting_getpropertyname|sdo_das_setting_getvalue|' + 'sdo_das_setting_isset|sdo_das_xml_addtypes|sdo_das_xml_create|sdo_das_xml_createdataobject|sdo_das_xml_createdocument|' + 'sdo_das_xml_document_getrootdataobject|sdo_das_xml_document_getrootelementname|sdo_das_xml_document_getrootelementuri|' + 'sdo_das_xml_document_setencoding|sdo_das_xml_document_setxmldeclaration|sdo_das_xml_document_setxmlversion|sdo_das_xml_loadfile|' + 'sdo_das_xml_loadstring|sdo_das_xml_savefile|sdo_das_xml_savestring|sdo_datafactory_create|sdo_dataobject_clear|' + 'sdo_dataobject_createdataobject|sdo_dataobject_getcontainer|sdo_dataobject_getsequence|sdo_dataobject_gettypename|' + 'sdo_dataobject_gettypenamespaceuri|sdo_exception_getcause|sdo_list_insert|sdo_model_property_getcontainingtype|' + 'sdo_model_property_getdefault|sdo_model_property_getname|sdo_model_property_gettype|sdo_model_property_iscontainment|' + 'sdo_model_property_ismany|sdo_model_reflectiondataobject_construct|sdo_model_reflectiondataobject_export|' + 'sdo_model_reflectiondataobject_getcontainmentproperty|sdo_model_reflectiondataobject_getinstanceproperties|' + 'sdo_model_reflectiondataobject_gettype|sdo_model_type_getbasetype|sdo_model_type_getname|sdo_model_type_getnamespaceuri|' + 'sdo_model_type_getproperties|sdo_model_type_getproperty|sdo_model_type_isabstracttype|sdo_model_type_isdatatype|sdo_model_type_isinstance|' + 'sdo_model_type_isopentype|sdo_model_type_issequencedtype|sdo_sequence_getproperty|sdo_sequence_insert|sdo_sequence_move|seekableiterator|' + 'sem_acquire|sem_get|sem_release|sem_remove|serializable|serialize|session_cache_expire|session_cache_limiter|session_commit|' + 'session_decode|session_destroy|session_encode|session_get_cookie_params|session_id|session_is_registered|session_module_name|session_name|' + 'session_pgsql_add_error|session_pgsql_get_error|session_pgsql_get_field|session_pgsql_reset|session_pgsql_set_field|session_pgsql_status|' + 'session_regenerate_id|session_register|session_save_path|session_set_cookie_params|session_set_save_handler|session_start|' + 'session_unregister|session_unset|session_write_close|setCounterClass|set_error_handler|set_exception_handler|set_file_buffer|' + 'set_include_path|set_magic_quotes_runtime|set_socket_blocking|set_time_limit|setcookie|setlocale|setproctitle|setrawcookie|' + 'setstaticpropertyvalue|setthreadtitle|settype|sha1|sha1_file|shell_exec|shm_attach|shm_detach|shm_get_var|shm_has_var|shm_put_var|' + 'shm_remove|shm_remove_var|shmop_close|shmop_delete|shmop_open|shmop_read|shmop_size|shmop_write|show_source|shuffle|signeurlpaiement|' + 'similar_text|simplexml_import_dom|simplexml_load_file|simplexml_load_string|simplexmlelement|simplexmliterator|sin|sinh|sizeof|sleep|snmp|' + 'snmp2_get|snmp2_getnext|snmp2_real_walk|snmp2_set|snmp2_walk|snmp3_get|snmp3_getnext|snmp3_real_walk|snmp3_set|snmp3_walk|' + 'snmp_get_quick_print|snmp_get_valueretrieval|snmp_read_mib|snmp_set_enum_print|snmp_set_oid_numeric_print|snmp_set_oid_output_format|' + 'snmp_set_quick_print|snmp_set_valueretrieval|snmpget|snmpgetnext|snmprealwalk|snmpset|snmpwalk|snmpwalkoid|soapclient|soapfault|' + 'soapheader|soapparam|soapserver|soapvar|socket_accept|socket_bind|socket_clear_error|socket_close|socket_connect|socket_create|' + 'socket_create_listen|socket_create_pair|socket_get_option|socket_get_status|socket_getpeername|socket_getsockname|socket_last_error|' + 'socket_listen|socket_read|socket_recv|socket_recvfrom|socket_select|socket_send|socket_sendto|socket_set_block|socket_set_blocking|' + 'socket_set_nonblock|socket_set_option|socket_set_timeout|socket_shutdown|socket_strerror|socket_write|solr_get_version|solrclient|' + 'solrclientexception|solrdocument|solrdocumentfield|solrexception|solrgenericresponse|solrillegalargumentexception|' + 'solrillegaloperationexception|solrinputdocument|solrmodifiableparams|solrobject|solrparams|solrpingresponse|solrquery|solrqueryresponse|' + 'solrresponse|solrupdateresponse|solrutils|sort|soundex|sphinxclient|spl_autoload|spl_autoload_call|spl_autoload_extensions|' + 'spl_autoload_functions|spl_autoload_register|spl_autoload_unregister|spl_classes|spl_object_hash|splbool|spldoublylinkedlist|splenum|' + 'splfileinfo|splfileobject|splfixedarray|splfloat|splheap|splint|split|spliti|splmaxheap|splminheap|splobjectstorage|splobserver|' + 'splpriorityqueue|splqueue|splstack|splstring|splsubject|spltempfileobject|spoofchecker|sprintf|sql_regcase|sqlite3|sqlite3result|' + 'sqlite3stmt|sqlite_array_query|sqlite_busy_timeout|sqlite_changes|sqlite_close|sqlite_column|sqlite_create_aggregate|' + 'sqlite_create_function|sqlite_current|sqlite_error_string|sqlite_escape_string|sqlite_exec|sqlite_factory|sqlite_fetch_all|' + 'sqlite_fetch_array|sqlite_fetch_column_types|sqlite_fetch_object|sqlite_fetch_single|sqlite_fetch_string|sqlite_field_name|' + 'sqlite_has_more|sqlite_has_prev|sqlite_key|sqlite_last_error|sqlite_last_insert_rowid|sqlite_libencoding|sqlite_libversion|sqlite_next|' + 'sqlite_num_fields|sqlite_num_rows|sqlite_open|sqlite_popen|sqlite_prev|sqlite_query|sqlite_rewind|sqlite_seek|sqlite_single_query|' + 'sqlite_udf_decode_binary|sqlite_udf_encode_binary|sqlite_unbuffered_query|sqlite_valid|sqrt|srand|sscanf|ssdeep_fuzzy_compare|' + 'ssdeep_fuzzy_hash|ssdeep_fuzzy_hash_filename|ssh2_auth_hostbased_file|ssh2_auth_none|ssh2_auth_password|ssh2_auth_pubkey_file|' + 'ssh2_connect|ssh2_exec|ssh2_fetch_stream|ssh2_fingerprint|ssh2_methods_negotiated|ssh2_publickey_add|ssh2_publickey_init|' + 'ssh2_publickey_list|ssh2_publickey_remove|ssh2_scp_recv|ssh2_scp_send|ssh2_sftp|ssh2_sftp_lstat|ssh2_sftp_mkdir|ssh2_sftp_readlink|' + 'ssh2_sftp_realpath|ssh2_sftp_rename|ssh2_sftp_rmdir|ssh2_sftp_stat|ssh2_sftp_symlink|ssh2_sftp_unlink|ssh2_shell|ssh2_tunnel|stat|' + 'stats_absolute_deviation|stats_cdf_beta|stats_cdf_binomial|stats_cdf_cauchy|stats_cdf_chisquare|stats_cdf_exponential|stats_cdf_f|' + 'stats_cdf_gamma|stats_cdf_laplace|stats_cdf_logistic|stats_cdf_negative_binomial|stats_cdf_noncentral_chisquare|stats_cdf_noncentral_f|' + 'stats_cdf_poisson|stats_cdf_t|stats_cdf_uniform|stats_cdf_weibull|stats_covariance|stats_den_uniform|stats_dens_beta|stats_dens_cauchy|' + 'stats_dens_chisquare|stats_dens_exponential|stats_dens_f|stats_dens_gamma|stats_dens_laplace|stats_dens_logistic|' + 'stats_dens_negative_binomial|stats_dens_normal|stats_dens_pmf_binomial|stats_dens_pmf_hypergeometric|stats_dens_pmf_poisson|stats_dens_t|' + 'stats_dens_weibull|stats_harmonic_mean|stats_kurtosis|stats_rand_gen_beta|stats_rand_gen_chisquare|stats_rand_gen_exponential|' + 'stats_rand_gen_f|stats_rand_gen_funiform|stats_rand_gen_gamma|stats_rand_gen_ibinomial|stats_rand_gen_ibinomial_negative|' + 'stats_rand_gen_int|stats_rand_gen_ipoisson|stats_rand_gen_iuniform|stats_rand_gen_noncenral_chisquare|stats_rand_gen_noncentral_f|' + 'stats_rand_gen_noncentral_t|stats_rand_gen_normal|stats_rand_gen_t|stats_rand_get_seeds|stats_rand_phrase_to_seeds|stats_rand_ranf|' + 'stats_rand_setall|stats_skew|stats_standard_deviation|stats_stat_binomial_coef|stats_stat_correlation|stats_stat_gennch|' + 'stats_stat_independent_t|stats_stat_innerproduct|stats_stat_noncentral_t|stats_stat_paired_t|stats_stat_percentile|stats_stat_powersum|' + 'stats_variance|stomp|stomp_connect_error|stomp_version|stompexception|stompframe|str_getcsv|str_ireplace|str_pad|str_repeat|str_replace|' + 'str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|stream_bucket_append|stream_bucket_make_writeable|' + 'stream_bucket_new|stream_bucket_prepend|stream_context_create|stream_context_get_default|stream_context_get_options|' + 'stream_context_get_params|stream_context_set_default|stream_context_set_option|stream_context_set_params|stream_copy_to_stream|' + 'stream_encoding|stream_filter_append|stream_filter_prepend|stream_filter_register|stream_filter_remove|stream_get_contents|' + 'stream_get_filters|stream_get_line|stream_get_meta_data|stream_get_transports|stream_get_wrappers|stream_is_local|' + 'stream_notification_callback|stream_register_wrapper|stream_resolve_include_path|stream_select|stream_set_blocking|stream_set_read_buffer|' + 'stream_set_timeout|stream_set_write_buffer|stream_socket_accept|stream_socket_client|stream_socket_enable_crypto|stream_socket_get_name|' + 'stream_socket_pair|stream_socket_recvfrom|stream_socket_sendto|stream_socket_server|stream_socket_shutdown|stream_supports_lock|' + 'stream_wrapper_register|stream_wrapper_restore|stream_wrapper_unregister|streamwrapper|strftime|strip_tags|stripcslashes|stripos|' + 'stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|' + 'strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare|substr_count|substr_replace|svm|svmmodel|svn_add|' + 'svn_auth_get_parameter|svn_auth_set_parameter|svn_blame|svn_cat|svn_checkout|svn_cleanup|svn_client_version|svn_commit|svn_delete|' + 'svn_diff|svn_export|svn_fs_abort_txn|svn_fs_apply_text|svn_fs_begin_txn2|svn_fs_change_node_prop|svn_fs_check_path|' + 'svn_fs_contents_changed|svn_fs_copy|svn_fs_delete|svn_fs_dir_entries|svn_fs_file_contents|svn_fs_file_length|svn_fs_is_dir|svn_fs_is_file|' + 'svn_fs_make_dir|svn_fs_make_file|svn_fs_node_created_rev|svn_fs_node_prop|svn_fs_props_changed|svn_fs_revision_prop|svn_fs_revision_root|' + 'svn_fs_txn_root|svn_fs_youngest_rev|svn_import|svn_log|svn_ls|svn_mkdir|svn_repos_create|svn_repos_fs|svn_repos_fs_begin_txn_for_commit|' + 'svn_repos_fs_commit_txn|svn_repos_hotcopy|svn_repos_open|svn_repos_recover|svn_revert|svn_status|svn_update|swf_actiongeturl|' + 'swf_actiongotoframe|swf_actiongotolabel|swf_actionnextframe|swf_actionplay|swf_actionprevframe|swf_actionsettarget|swf_actionstop|' + 'swf_actiontogglequality|swf_actionwaitforframe|swf_addbuttonrecord|swf_addcolor|swf_closefile|swf_definebitmap|swf_definefont|' + 'swf_defineline|swf_definepoly|swf_definerect|swf_definetext|swf_endbutton|swf_enddoaction|swf_endshape|swf_endsymbol|swf_fontsize|' + 'swf_fontslant|swf_fonttracking|swf_getbitmapinfo|swf_getfontinfo|swf_getframe|swf_labelframe|swf_lookat|swf_modifyobject|swf_mulcolor|' + 'swf_nextid|swf_oncondition|swf_openfile|swf_ortho|swf_ortho2|swf_perspective|swf_placeobject|swf_polarview|swf_popmatrix|swf_posround|' + 'swf_pushmatrix|swf_removeobject|swf_rotate|swf_scale|swf_setfont|swf_setframe|swf_shapearc|swf_shapecurveto|swf_shapecurveto3|' + 'swf_shapefillbitmapclip|swf_shapefillbitmaptile|swf_shapefilloff|swf_shapefillsolid|swf_shapelinesolid|swf_shapelineto|swf_shapemoveto|' + 'swf_showframe|swf_startbutton|swf_startdoaction|swf_startshape|swf_startsymbol|swf_textwidth|swf_translate|swf_viewport|swfaction|' + 'swfbitmap|swfbutton|swfdisplayitem|swffill|swffont|swffontchar|swfgradient|swfmorph|swfmovie|swfprebuiltclip|swfshape|swfsound|' + 'swfsoundinstance|swfsprite|swftext|swftextfield|swfvideostream|swish_construct|swish_getmetalist|swish_getpropertylist|swish_prepare|' + 'swish_query|swishresult_getmetalist|swishresult_stem|swishresults_getparsedwords|swishresults_getremovedstopwords|swishresults_nextresult|' + 'swishresults_seekresult|swishsearch_execute|swishsearch_resetlimit|swishsearch_setlimit|swishsearch_setphrasedelimiter|' + 'swishsearch_setsort|swishsearch_setstructure|sybase_affected_rows|sybase_close|sybase_connect|sybase_data_seek|' + 'sybase_deadlock_retry_count|sybase_fetch_array|sybase_fetch_assoc|sybase_fetch_field|sybase_fetch_object|sybase_fetch_row|' + 'sybase_field_seek|sybase_free_result|sybase_get_last_message|sybase_min_client_severity|sybase_min_error_severity|' + 'sybase_min_message_severity|sybase_min_server_severity|sybase_num_fields|sybase_num_rows|sybase_pconnect|sybase_query|sybase_result|' + 'sybase_select_db|sybase_set_message_handler|sybase_unbuffered_query|symlink|sys_get_temp_dir|sys_getloadavg|syslog|system|tag|tan|tanh|' + 'tcpwrap_check|tempnam|textdomain|tidy|tidy_access_count|tidy_config_count|tidy_diagnose|tidy_error_count|tidy_get_error_buffer|' + 'tidy_get_output|tidy_load_config|tidy_reset_config|tidy_save_config|tidy_set_encoding|tidy_setopt|tidy_warning_count|tidynode|time|' + 'time_nanosleep|time_sleep_until|timezone_abbreviations_list|timezone_identifiers_list|timezone_location_get|timezone_name_from_abbr|' + 'timezone_name_get|timezone_offset_get|timezone_open|timezone_transitions_get|timezone_version_get|tmpfile|token_get_all|token_name|' + 'tokyotyrant|tokyotyrantquery|tokyotyranttable|tostring|tostring|touch|transliterator|traversable|trigger_error|trim|uasort|ucfirst|' + 'ucwords|udm_add_search_limit|udm_alloc_agent|udm_alloc_agent_array|udm_api_version|udm_cat_list|udm_cat_path|udm_check_charset|' + 'udm_check_stored|udm_clear_search_limits|udm_close_stored|udm_crc32|udm_errno|udm_error|udm_find|udm_free_agent|udm_free_ispell_data|' + 'udm_free_res|udm_get_doc_count|udm_get_res_field|udm_get_res_param|udm_hash32|udm_load_ispell_data|udm_open_stored|udm_set_agent_param|' + 'uksort|umask|underflowexception|unexpectedvalueexception|uniqid|unixtojd|unlink|unpack|unregister_tick_function|unserialize|unset|' + 'urldecode|urlencode|use_soap_error_handler|user_error|usleep|usort|utf8_decode|utf8_encode|v8js|v8jsexception|var_dump|var_export|variant|' + 'variant_abs|variant_add|variant_and|variant_cast|variant_cat|variant_cmp|variant_date_from_timestamp|variant_date_to_timestamp|' + 'variant_div|variant_eqv|variant_fix|variant_get_type|variant_idiv|variant_imp|variant_int|variant_mod|variant_mul|variant_neg|variant_not|' + 'variant_or|variant_pow|variant_round|variant_set|variant_set_type|variant_sub|variant_xor|version_compare|vfprintf|virtual|' + 'vpopmail_add_alias_domain|vpopmail_add_alias_domain_ex|vpopmail_add_domain|vpopmail_add_domain_ex|vpopmail_add_user|vpopmail_alias_add|' + 'vpopmail_alias_del|vpopmail_alias_del_domain|vpopmail_alias_get|vpopmail_alias_get_all|vpopmail_auth_user|vpopmail_del_domain|' + 'vpopmail_del_domain_ex|vpopmail_del_user|vpopmail_error|vpopmail_passwd|vpopmail_set_user_quota|vprintf|vsprintf|w32api_deftype|' + 'w32api_init_dtype|w32api_invoke_function|w32api_register_function|w32api_set_call_method|wddx_add_vars|wddx_deserialize|wddx_packet_end|' + 'wddx_packet_start|wddx_serialize_value|wddx_serialize_vars|win32_continue_service|win32_create_service|win32_delete_service|' + 'win32_get_last_control_message|win32_pause_service|win32_ps_list_procs|win32_ps_stat_mem|win32_ps_stat_proc|win32_query_service_status|' + 'win32_set_service_status|win32_start_service|win32_start_service_ctrl_dispatcher|win32_stop_service|wincache_fcache_fileinfo|' + 'wincache_fcache_meminfo|wincache_lock|wincache_ocache_fileinfo|wincache_ocache_meminfo|wincache_refresh_if_changed|' + 'wincache_rplist_fileinfo|wincache_rplist_meminfo|wincache_scache_info|wincache_scache_meminfo|wincache_ucache_add|wincache_ucache_cas|' + 'wincache_ucache_clear|wincache_ucache_dec|wincache_ucache_delete|wincache_ucache_exists|wincache_ucache_get|wincache_ucache_inc|' + 'wincache_ucache_info|wincache_ucache_meminfo|wincache_ucache_set|wincache_unlock|wordwrap|xattr_get|xattr_list|xattr_remove|xattr_set|' + 'xattr_supported|xdiff_file_bdiff|xdiff_file_bdiff_size|xdiff_file_bpatch|xdiff_file_diff|xdiff_file_diff_binary|xdiff_file_merge3|' + 'xdiff_file_patch|xdiff_file_patch_binary|xdiff_file_rabdiff|xdiff_string_bdiff|xdiff_string_bdiff_size|xdiff_string_bpatch|' + 'xdiff_string_diff|xdiff_string_diff_binary|xdiff_string_merge3|xdiff_string_patch|xdiff_string_patch_binary|xdiff_string_rabdiff|' + 'xhprof_disable|xhprof_enable|xhprof_sample_disable|xhprof_sample_enable|xml_error_string|xml_get_current_byte_index|' + 'xml_get_current_column_number|xml_get_current_line_number|xml_get_error_code|xml_parse|xml_parse_into_struct|xml_parser_create|' + 'xml_parser_create_ns|xml_parser_free|xml_parser_get_option|xml_parser_set_option|xml_set_character_data_handler|xml_set_default_handler|' + 'xml_set_element_handler|xml_set_end_namespace_decl_handler|xml_set_external_entity_ref_handler|xml_set_notation_decl_handler|' + 'xml_set_object|xml_set_processing_instruction_handler|xml_set_start_namespace_decl_handler|xml_set_unparsed_entity_decl_handler|xmlreader|' + 'xmlrpc_decode|xmlrpc_decode_request|xmlrpc_encode|xmlrpc_encode_request|xmlrpc_get_type|xmlrpc_is_fault|xmlrpc_parse_method_descriptions|' + 'xmlrpc_server_add_introspection_data|xmlrpc_server_call_method|xmlrpc_server_create|xmlrpc_server_destroy|' + 'xmlrpc_server_register_introspection_callback|xmlrpc_server_register_method|xmlrpc_set_type|xmlwriter_end_attribute|xmlwriter_end_cdata|' + 'xmlwriter_end_comment|xmlwriter_end_document|xmlwriter_end_dtd|xmlwriter_end_dtd_attlist|xmlwriter_end_dtd_element|' + 'xmlwriter_end_dtd_entity|xmlwriter_end_element|xmlwriter_end_pi|xmlwriter_flush|xmlwriter_full_end_element|xmlwriter_open_memory|' + 'xmlwriter_open_uri|xmlwriter_output_memory|xmlwriter_set_indent|xmlwriter_set_indent_string|xmlwriter_start_attribute|' + 'xmlwriter_start_attribute_ns|xmlwriter_start_cdata|xmlwriter_start_comment|xmlwriter_start_document|xmlwriter_start_dtd|' + 'xmlwriter_start_dtd_attlist|xmlwriter_start_dtd_element|xmlwriter_start_dtd_entity|xmlwriter_start_element|xmlwriter_start_element_ns|' + 'xmlwriter_start_pi|xmlwriter_text|xmlwriter_write_attribute|xmlwriter_write_attribute_ns|xmlwriter_write_cdata|xmlwriter_write_comment|' + 'xmlwriter_write_dtd|xmlwriter_write_dtd_attlist|xmlwriter_write_dtd_element|xmlwriter_write_dtd_entity|xmlwriter_write_element|' + 'xmlwriter_write_element_ns|xmlwriter_write_pi|xmlwriter_write_raw|xpath_eval|xpath_eval_expression|xpath_new_context|xpath_register_ns|' + 'xpath_register_ns_auto|xptr_eval|xptr_new_context|xslt_backend_info|xslt_backend_name|xslt_backend_version|xslt_create|xslt_errno|' + 'xslt_error|xslt_free|xslt_getopt|xslt_process|xslt_set_base|xslt_set_encoding|xslt_set_error_handler|xslt_set_log|xslt_set_object|' + 'xslt_set_sax_handler|xslt_set_sax_handlers|xslt_set_scheme_handler|xslt_set_scheme_handlers|xslt_setopt|xsltprocessor|yaml_emit|' + 'yaml_emit_file|yaml_parse|yaml_parse_file|yaml_parse_url|yaz_addinfo|yaz_ccl_conf|yaz_ccl_parse|yaz_close|yaz_connect|yaz_database|' + 'yaz_element|yaz_errno|yaz_error|yaz_es|yaz_es_result|yaz_get_option|yaz_hits|yaz_itemorder|yaz_present|yaz_range|yaz_record|yaz_scan|' + 'yaz_scan_result|yaz_schema|yaz_search|yaz_set_option|yaz_sort|yaz_syntax|yaz_wait|yp_all|yp_cat|yp_err_string|yp_errno|yp_first|' + 'yp_get_default_domain|yp_master|yp_match|yp_next|yp_order|zend_logo_guid|zend_thread_id|zend_version|zip_close|zip_entry_close|' + 'zip_entry_compressedsize|zip_entry_compressionmethod|zip_entry_filesize|zip_entry_name|zip_entry_open|zip_entry_read|zip_open|zip_read|' + 'ziparchive|ziparchive_addemptydir|ziparchive_addfile|ziparchive_addfromstring|ziparchive_close|ziparchive_deleteindex|' + 'ziparchive_deletename|ziparchive_extractto|ziparchive_getarchivecomment|ziparchive_getcommentindex|ziparchive_getcommentname|' + 'ziparchive_getfromindex|ziparchive_getfromname|ziparchive_getnameindex|ziparchive_getstatusstring|ziparchive_getstream|' + 'ziparchive_locatename|ziparchive_open|ziparchive_renameindex|ziparchive_renamename|ziparchive_setCommentName|ziparchive_setarchivecomment|' + 'ziparchive_setcommentindex|ziparchive_statindex|ziparchive_statname|ziparchive_unchangeall|ziparchive_unchangearchive|' + 'ziparchive_unchangeindex|ziparchive_unchangename|zlib_get_coding_type').split('|') ); // http://php.net/manual/en/reserved.keywords.php var keywords = lang.arrayToMap( ('abstract|and|array|as|break|case|catch|class|clone|const|continue|declare|default|do|else|elseif|enddeclare|endfor|endforeach|endif|' + 'endswitch|endwhile|extends|final|for|foreach|function|global|goto|if|implements|interface|instanceof|namespace|new|or|private|protected|' + 'public|static|switch|throw|try|use|var|while|xor').split('|') ); // http://php.net/manual/en/reserved.keywords.php var languageConstructs = lang.arrayToMap( ('die|echo|empty|exit|eval|include|include_once|isset|list|require|require_once|return|print|unset').split('|') ); var builtinConstants = lang.arrayToMap( ('true|false|null|__CLASS__|__DIR__|__FILE__|__LINE__|__METHOD__|__FUNCTION__|__NAMESPACE__').split('|') ); var builtinVariables = lang.arrayToMap( ('$GLOBALS|$_SERVER|$_GET|$_POST|$_FILES|$_REQUEST|$_SESSION|$_ENV|$_COOKIE|$php_errormsg|$HTTP_RAW_POST_DATA|' + '$http_response_header|$argc|$argv').split('|') ); // Discovery done by downloading 'Many HTML files' from: http://php.net/download-docs.php // Then search for files containing 'deprecated' (case-insensitive) and look at each file that turns up. var builtinFunctionsDeprecated = lang.arrayToMap( ('key_exists|cairo_matrix_create_scale|cairo_matrix_create_translate|call_user_method|call_user_method_array|com_addref|com_get|' + 'com_invoke|com_isenum|com_load|com_release|com_set|connection_timeout|cubrid_load_from_glo|cubrid_new_glo|cubrid_save_to_glo|' + 'cubrid_send_glo|define_syslog_variables|dl|ereg|ereg_replace|eregi|eregi_replace|hw_documentattributes|hw_documentbodytag|' + 'hw_documentsize|hw_outputdocument|imagedashedline|maxdb_bind_param|maxdb_bind_result|maxdb_client_encoding|maxdb_close_long_data|' + 'maxdb_execute|maxdb_fetch|maxdb_get_metadata|maxdb_param_count|maxdb_send_long_data|mcrypt_ecb|mcrypt_generic_end|mime_content_type|' + 'mysql_createdb|mysql_dbname|mysql_db_query|mysql_drop_db|mysql_dropdb|mysql_escape_string|mysql_fieldflags|mysql_fieldflags|' + 'mysql_fieldname|mysql_fieldtable|mysql_fieldtype|mysql_freeresult|mysql_listdbs|mysql_list_fields|mysql_listfields|mysql_list_tables|' + 'mysql_listtables|mysql_numfields|mysql_numrows|mysql_selectdb|mysql_tablename|mysqli_bind_param|mysqli_bind_result|' + 'mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_execute|' + 'mysqli_fetch|mysqli_get_metadata|mysqli_master_query|mysqli_param_count|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|' + 'mysqli_send_long_data|mysqli_send_query|mysqli_slave_query|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|' + 'ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|' + 'ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|' + 'ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|' + 'ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|' + 'ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|PDF_add_annotation|PDF_add_bookmark|' + 'PDF_add_launchlink|PDF_add_locallink|PDF_add_note|PDF_add_outline|PDF_add_pdflink|PDF_add_weblink|PDF_attach_file|PDF_begin_page|' + 'PDF_begin_template|PDF_close_pdi|PDF_close|PDF_findfont|PDF_get_font|PDF_get_fontname|PDF_get_fontsize|PDF_get_image_height|' + 'PDF_get_image_width|PDF_get_majorversion|PDF_get_minorversion|PDF_get_pdi_parameter|PDF_get_pdi_value|PDF_open_ccitt|PDF_open_file|' + 'PDF_open_gif|PDF_open_image_file|PDF_open_image|PDF_open_jpeg|PDF_open_pdi|PDF_open_tiff|PDF_place_image|PDF_place_pdi_page|' + 'PDF_set_border_color|PDF_set_border_dash|PDF_set_border_style|PDF_set_char_spacing|PDF_set_duration|PDF_set_horiz_scaling|' + 'PDF_set_info_author|PDF_set_info_creator|PDF_set_info_keywords|PDF_set_info_subject|PDF_set_info_title|PDF_set_leading|' + 'PDF_set_text_matrix|PDF_set_text_rendering|PDF_set_text_rise|PDF_set_word_spacing|PDF_setgray_fill|PDF_setgray_stroke|PDF_setgray|' + 'PDF_setpolydash|PDF_setrgbcolor_fill|PDF_setrgbcolor_stroke|PDF_setrgbcolor|PDF_show_boxed|php_check_syntax|px_set_tablename|' + 'px_set_targetencoding|runkit_sandbox_output_handler|session_is_registered|session_register|session_unregister' + 'set_magic_quotes_runtime|magic_quotes_runtime|set_socket_blocking|socket_set_blocking|set_socket_timeout|socket_set_timeout|split|spliti|' + 'sql_regcase').split('|') ); var keywordsDeprecated = lang.arrayToMap( ('cfunction|old_function').split('|') ); var futureReserved = lang.arrayToMap([]); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "support.php_tag", // php open tag regex : "<\\?(?:php|\\=)" }, { token : "support.php_tag", // php close tag regex : "\\?>" }, { token : "comment", regex : "<\\!--", next : "htmlcomment" }, { token : "meta.tag", regex : "<style", next : "css" }, { token : "meta.tag", // opening tag regex : "<\\/?[-_a-zA-Z0-9:]+", next : "htmltag" }, { token : 'meta.tag', regex : '<\!DOCTYPE.*?>' }, { token : "comment", regex : "\\/\\/.*$" }, { token : "comment", regex : "#.*$" }, docComment.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/][gimy]*\\s*(?=[).,;]|$)" }, { token : "string", // " string start regex : '"', next : "qqstring" }, { token : "string", // ' string start regex : "'", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language", // constants regex : "\\b(?:DEFAULT_INCLUDE_PATH|E_(?:ALL|CO(?:MPILE_(?:ERROR|WARNING)|RE_(?:ERROR|WARNING))|" + "ERROR|NOTICE|PARSE|STRICT|USER_(?:ERROR|NOTICE|WARNING)|WARNING)|P(?:EAR_(?:EXTENSION_DIR|INSTALL_DIR)|" + "HP_(?:BINDIR|CONFIG_FILE_(?:PATH|SCAN_DIR)|DATADIR|E(?:OL|XTENSION_DIR)|INT_(?:MAX|SIZE)|" + "L(?:IBDIR|OCALSTATEDIR)|O(?:S|UTPUT_HANDLER_(?:CONT|END|START))|PREFIX|S(?:API|HLIB_SUFFIX|YSCONFDIR)|" + "VERSION))|__COMPILER_HALT_OFFSET__)\\b" }, { token : "constant.language", // constants regex : "\\b(?:A(?:B(?:DAY_(?:1|2|3|4|5|6|7)|MON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9))|LT_DIGITS|M_STR|" + "SSERT_(?:ACTIVE|BAIL|CALLBACK|QUIET_EVAL|WARNING))|C(?:ASE_(?:LOWER|UPPER)|HAR_MAX|" + "O(?:DESET|NNECTION_(?:ABORTED|NORMAL|TIMEOUT)|UNT_(?:NORMAL|RECURSIVE))|" + "R(?:EDITS_(?:ALL|DOCS|FULLPAGE|G(?:ENERAL|ROUP)|MODULES|QA|SAPI)|NCYSTR|" + "YPT_(?:BLOWFISH|EXT_DES|MD5|S(?:ALT_LENGTH|TD_DES)))|URRENCY_SYMBOL)|D(?:AY_(?:1|2|3|4|5|6|7)|" + "ECIMAL_POINT|IRECTORY_SEPARATOR|_(?:FMT|T_FMT))|E(?:NT_(?:COMPAT|NOQUOTES|QUOTES)|RA(?:_(?:D_(?:FMT|T_FMT)|" + "T_FMT|YEAR)|)|XTR_(?:IF_EXISTS|OVERWRITE|PREFIX_(?:ALL|I(?:F_EXISTS|NVALID)|SAME)|SKIP))|FRAC_DIGITS|GROUPING|" + "HTML_(?:ENTITIES|SPECIALCHARS)|IN(?:FO_(?:ALL|C(?:ONFIGURATION|REDITS)|ENVIRONMENT|GENERAL|LICENSE|MODULES|VARIABLES)|" + "I_(?:ALL|PERDIR|SYSTEM|USER)|T_(?:CURR_SYMBOL|FRAC_DIGITS))|L(?:C_(?:ALL|C(?:OLLATE|TYPE)|M(?:ESSAGES|ONETARY)|NUMERIC|TIME)|" + "O(?:CK_(?:EX|NB|SH|UN)|G_(?:A(?:LERT|UTH(?:PRIV|))|C(?:ONS|R(?:IT|ON))|D(?:AEMON|EBUG)|E(?:MERG|RR)|INFO|KERN|" + "L(?:OCAL(?:0|1|2|3|4|5|6|7)|PR)|MAIL|N(?:DELAY|EWS|O(?:TICE|WAIT))|ODELAY|P(?:ERROR|ID)|SYSLOG|U(?:SER|UCP)|WARNING)))|" + "M(?:ON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9|DECIMAL_POINT|GROUPING|THOUSANDS_SEP)|_(?:1_PI|2_(?:PI|SQRTPI)|E|L(?:N(?:10|2)|" + "OG(?:10E|2E))|PI(?:_(?:2|4)|)|SQRT(?:1_2|2)))|N(?:EGATIVE_SIGN|O(?:EXPR|STR)|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "P(?:ATH(?:INFO_(?:BASENAME|DIRNAME|EXTENSION)|_SEPARATOR)|M_STR|OSITIVE_SIGN|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "RADIXCHAR|S(?:EEK_(?:CUR|END|SET)|ORT_(?:ASC|DESC|NUMERIC|REGULAR|STRING)|TR_PAD_(?:BOTH|LEFT|RIGHT))|" + "T(?:HOUS(?:ANDS_SEP|EP)|_FMT(?:_AMPM|))|YES(?:EXPR|STR)|STD(?:IN|OUT|ERR))\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinVariables.hasOwnProperty(value)) return "variable.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else if(value.match(/^(\$[a-zA-Z][a-zA-Z0-9_]*|self|parent)$/)) return "variable"; return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : '\\\\(?:[nrtvef\\\\"$]|[0-7]{1,3}|x[0-9A-Fa-f]{1,2})' }, { token : "constant.language.escape", regex : /\$[\w\d]+(?:\[[\w\d]+\])?/ }, { token : "constant.language.escape", regex : /\$\{[^"\}]+\}?/ // this is wrong but ok for now }, { token : "string", regex : '"', next : "start" }, { token : "string", regex : '.+?' } ], "qstring" : [ { token : "constant.language.escape", regex : "\\\\['\\\\]" }, { token : "string", regex : "'", next : "start" }, { token : "string", regex : ".+?" } ], "htmlcomment" : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", regex : ".+" } ], "htmltag" : [ { token : "meta.tag", regex : ">", next : "start" }, { token : "text", regex : "[-_a-zA-Z0-9:]+" }, { token : "text", regex : "\\s+" }, { token : "string", regex : '".*?"' }, { token : "string", regex : "'.*?'" } ], "css" : [ { token : "meta.tag", regex : "<\/style>", next : "htmltag" }, { token : "meta.tag", regex : ">" }, { token : 'text', regex : "(?:media|type|href)" }, { token : 'string', regex : '=".*?"' }, { token : "paren.lparen", regex : "\{", next : "cssdeclaration" }, { token : "keyword", regex : "#[A-Za-z0-9\-\_\.]+" }, { token : "variable", regex : "\\.[A-Za-z0-9\-\_\.]+" }, { token : "constant", regex : "[A-Za-z0-9]+" } ], "cssdeclaration" : [ { token : "support.type", regex : "[\-a-zA-Z]+", next : "cssvalue" }, { token : "paren.rparen", regex : '\}', next : "css" } ], "cssvalue" : [ { token : "text", regex : "\:" }, { token : "constant", regex : "#[0-9a-zA-Z]+" }, { token : "text", regex : "[\-\_0-9a-zA-Z\"' ,%]+" }, { token : "text", regex : ";", next : "cssdeclaration" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(PhpHighlightRules, TextHighlightRules); exports.PhpHighlightRules = PhpHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-php.js
JavaScript
asf20
146,063
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/pastel_on_dark', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-pastel-on-dark"; exports.cssText = "\ .ace-pastel-on-dark .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-pastel-on-dark .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-pastel-on-dark .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-pastel-on-dark .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-pastel-on-dark .ace_scroller {\ background-color: #2C2828;\ }\ \ .ace-pastel-on-dark .ace_text-layer {\ cursor: text;\ color: #8F938F;\ }\ \ .ace-pastel-on-dark .ace_cursor {\ border-left: 2px solid #A7A7A7;\ }\ \ .ace-pastel-on-dark .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #A7A7A7;\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_selection {\ background: rgba(221, 240, 255, 0.20);\ }\ \ .ace-pastel-on-dark.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #2C2828;\ border-radius: 2px;\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(255, 255, 255, 0.25);\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_active_line {\ background: rgba(255, 255, 255, 0.031);\ }\ \ .ace-pastel-on-dark .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(221, 240, 255, 0.20);\ }\ \ .ace-pastel-on-dark .ace_invisible {\ color: rgba(255, 255, 255, 0.25);\ }\ \ .ace-pastel-on-dark .ace_keyword, .ace-pastel-on-dark .ace_meta {\ color:#757aD8;\ }\ \ .ace-pastel-on-dark .ace_keyword.ace_operator {\ color:#797878;\ }\ \ .ace-pastel-on-dark .ace_constant, .ace-pastel-on-dark .ace_constant.ace_other {\ color:#4FB7C5;\ }\ \ .ace-pastel-on-dark .ace_constant.ace_character, {\ color:#4FB7C5;\ }\ \ .ace-pastel-on-dark .ace_constant.ace_character.ace_escape, {\ color:#4FB7C5;\ }\ \ .ace-pastel-on-dark .ace_constant.ace_language {\ color:#DE8E30;\ }\ \ .ace-pastel-on-dark .ace_constant.ace_numeric {\ color:#CCCCCC;\ }\ \ .ace-pastel-on-dark .ace_invalid {\ color:#F8F8F8;\ background-color:rgba(86, 45, 86, 0.75);\ }\ \ .ace-pastel-on-dark .ace_invalid.ace_illegal {\ color:#F8F8F8;\ background-color:rgba(86, 45, 86, 0.75);\ }\ \ .ace-pastel-on-dark .ace_invalid.ace_deprecated {\ text-decoration:underline;\ font-style:italic;\ color:#D2A8A1;\ }\ \ .ace-pastel-on-dark .ace_fold {\ background-color: #757aD8;\ border-color: #8F938F;\ }\ \ .ace-pastel-on-dark .ace_support.ace_function {\ color:#AEB2F8;\ }\ \ .ace-pastel-on-dark .ace_string {\ color:#66A968;\ }\ \ .ace-pastel-on-dark .ace_string.ace_regexp {\ color:#E9C062;\ }\ \ .ace-pastel-on-dark .ace_comment {\ color:#A6C6FF;\ }\ \ .ace-pastel-on-dark .ace_variable {\ color:#BEBF55;\ }\ \ .ace-pastel-on-dark .ace_variable.ace_language {\ color:#C1C144;\ }\ \ .ace-pastel-on-dark .ace_xml_pe {\ color:#494949;\ }\ \ .ace-pastel-on-dark .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-pastel_on_dark.js
JavaScript
asf20
5,077
define('ace/mode/java', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/javascript', 'ace/tokenizer', 'ace/mode/java_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var JavaScriptMode = require("./javascript").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaHighlightRules = require("./java_highlight_rules").JavaHighlightRules; var Mode = function() { JavaScriptMode.call(this); this.$tokenizer = new Tokenizer(new JavaHighlightRules().getRules()); }; oop.inherits(Mode, JavaScriptMode); (function() { this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/java_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaHighlightRules = function() { // taken from http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html var keywords = lang.arrayToMap( ("abstract|continue|for|new|switch|" + "assert|default|goto|package|synchronized|" + "boolean|do|if|private|this|" + "break|double|implements|protected|throw|" + "byte|else|import|public|throws|" + "case|enum|instanceof|return|transient|" + "catch|extends|int|short|try|" + "char|final|interface|static|void|" + "class|finally|long|strictfp|volatile|" + "const|float|native|super|while").split("|") ); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var langClasses = lang.arrayToMap( ("AbstractMethodError|AssertionError|ClassCircularityError|"+ "ClassFormatError|Deprecated|EnumConstantNotPresentException|"+ "ExceptionInInitializerError|IllegalAccessError|"+ "IllegalThreadStateException|InstantiationError|InternalError|"+ "NegativeArraySizeException|NoSuchFieldError|Override|Process|"+ "ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|"+ "SuppressWarnings|TypeNotPresentException|UnknownError|"+ "UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|"+ "InstantiationException|IndexOutOfBoundsException|"+ "ArrayIndexOutOfBoundsException|CloneNotSupportedException|"+ "NoSuchFieldException|IllegalArgumentException|NumberFormatException|"+ "SecurityException|Void|InheritableThreadLocal|IllegalStateException|"+ "InterruptedException|NoSuchMethodException|IllegalAccessException|"+ "UnsupportedOperationException|Enum|StrictMath|Package|Compiler|"+ "Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|"+ "NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|"+ "NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|"+ "Character|Boolean|StackTraceElement|Appendable|StringBuffer|"+ "Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|"+ "StackOverflowError|OutOfMemoryError|VirtualMachineError|"+ "ArrayStoreException|ClassCastException|LinkageError|"+ "NoClassDefFoundError|ClassNotFoundException|RuntimeException|"+ "Exception|ThreadDeath|Error|Throwable|System|ClassLoader|"+ "Cloneable|Class|CharSequence|Comparable|String|Object").split("|") ); var importClasses = lang.arrayToMap( ("").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (langClasses.hasOwnProperty(value)) return "support.function"; else if (importClasses.hasOwnProperty(value)) return "support.function"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaHighlightRules, TextHighlightRules); exports.JavaHighlightRules = JavaHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-java.js
JavaScript
asf20
44,561
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Satoshi Murakami <murky.satyr AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/coffee', ['require', 'exports', 'module' , 'ace/tokenizer', 'ace/mode/coffee_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/pythonic', 'ace/range', 'ace/mode/text', 'ace/worker/worker_client', 'ace/lib/oop'], function(require, exports, module) { var Tokenizer = require("../tokenizer").Tokenizer; var Rules = require("./coffee_highlight_rules").CoffeeHighlightRules; var Outdent = require("./matching_brace_outdent").MatchingBraceOutdent; var PythonFoldMode = require("./folding/pythonic").FoldMode; var Range = require("../range").Range; var TextMode = require("./text").Mode; var WorkerClient = require("../worker/worker_client").WorkerClient; var oop = require("../lib/oop"); function Mode() { this.$tokenizer = new Tokenizer(new Rules().getRules()); this.$outdent = new Outdent(); this.foldingRules = new PythonFoldMode("=|=>|->|\\s*class [^#]*"); } oop.inherits(Mode, TextMode); (function() { var indenter = /(?:[({[=:]|[-=]>|\b(?:else|switch|try|catch(?:\s*[$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)?|finally))\s*$/; var commentLine = /^(\s*)#/; var hereComment = /^\s*###(?!#)/; var indentation = /^\s*/; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (!(tokens.length && tokens[tokens.length - 1].type === 'comment') && state === 'start' && indenter.test(line)) indent += tab; return indent; }; this.toggleCommentLines = function(state, doc, startRow, endRow){ console.log("toggle"); var range = new Range(0, 0, 0, 0); for (var i = startRow; i <= endRow; ++i) { var line = doc.getLine(i); if (hereComment.test(line)) continue; if (commentLine.test(line)) line = line.replace(commentLine, '$1'); else line = line.replace(indentation, '$&#'); range.end.row = range.start.row = i; range.end.column = line.length + 1; doc.replace(range, line); } }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-coffee.js", "ace/mode/coffee_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("error", function(e) { session.setAnnotations([e.data]); }); worker.on("ok", function(e) { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/coffee_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/lang', 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var lang = require("../lib/lang"); var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; oop.inherits(CoffeeHighlightRules, TextHighlightRules); function CoffeeHighlightRules() { var identifier = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*"; var stringfill = { token : "string", merge : true, regex : ".+" }; var keywords = lang.arrayToMap(( "this|throw|then|try|typeof|super|switch|return|break|by)|continue|" + "catch|class|in|instanceof|is|isnt|if|else|extends|for|forown|" + "finally|function|while|when|new|no|not|delete|debugger|do|loop|of|off|" + "or|on|unless|until|and|yes").split("|") ); var langConstant = lang.arrayToMap(( "true|false|null|undefined").split("|") ); var illegal = lang.arrayToMap(( "case|const|default|function|var|void|with|enum|export|implements|" + "interface|let|package|private|protected|public|static|yield|" + "__hasProp|extends|slice|bind|indexOf").split("|") ); var supportClass = lang.arrayToMap(( "Array|Boolean|Date|Function|Number|Object|RegExp|ReferenceError|" + "RangeError|String|SyntaxError|Error|EvalError|TypeError|URIError").split("|") ); var supportFunction = lang.arrayToMap(( "Math|JSON|isNaN|isFinite|parseInt|parseFloat|encodeURI|" + "encodeURIComponent|decodeURI|decodeURIComponent|RangeError|String|" + "SyntaxError|Error|EvalError|TypeError|URIError").split("|") ); this.$rules = { start : [ { token : "identifier", regex : "(?:(?:\\.|::)\\s*)" + identifier }, { token : "variable", regex : "@(?:" + identifier + ")?" }, { token: function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (langConstant.hasOwnProperty(value)) return "constant.language"; else if (illegal.hasOwnProperty(value)) return "invalid.illegal"; else if (supportClass.hasOwnProperty(value)) return "language.support.class"; else if (supportFunction.hasOwnProperty(value)) return "language.support.function"; else return "identifier"; }, regex : identifier }, { token : "constant.numeric", regex : "(?:0x[\\da-fA-F]+|(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?)" }, { token : "string", merge : true, regex : "'''", next : "qdoc" }, { token : "string", merge : true, regex : '"""', next : "qqdoc" }, { token : "string", merge : true, regex : "'", next : "qstring" }, { token : "string", merge : true, regex : '"', next : "qqstring" }, { token : "string", merge : true, regex : "`", next : "js" }, { token : "string.regex", merge : true, regex : "///", next : "heregex" }, { token : "string.regex", regex : "/(?!\\s)[^[/\\n\\\\]*(?: (?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[/\\n\\\\]*)*/[imgy]{0,4}(?!\\w)" }, { token : "comment", merge : true, regex : "###(?!#)", next : "comment" }, { token : "comment", regex : "#.*" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\." }, { token : "keyword.operator", regex : "(?:[\\-=]>|[-+*/%<>&|^!?=]=|>>>=?|\\-\\-|\\+\\+|::|&&=|\\|\\|=|<<=|>>=|\\?\\.|\\.{2,3}|\\!)" }, { token : "paren.lparen", regex : "[({[]" }, { token : "paren.rparen", regex : "[\\]})]" }, { token : "text", regex : "\\s+" }], qdoc : [{ token : "string", regex : ".*?'''", next : "start" }, stringfill], qqdoc : [{ token : "string", regex : '.*?"""', next : "start" }, stringfill], qstring : [{ token : "string", regex : "[^\\\\']*(?:\\\\.[^\\\\']*)*'", merge : true, next : "start" }, stringfill], qqstring : [{ token : "string", regex : '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"', merge : true, next : "start" }, stringfill], js : [{ token : "string", merge : true, regex : "[^\\\\`]*(?:\\\\.[^\\\\`]*)*`", next : "start" }, stringfill], heregex : [{ token : "string.regex", regex : '.*?///[imgy]{0,4}', next : "start" }, { token : "comment.regex", regex : "\\s+(?:#.*)?" }, { token : "string.regex", merge : true, regex : "\\S+" }], comment : [{ token : "comment", regex : '.*?###', next : "start" }, { token : "comment", merge : true, regex : ".+" }] }; } exports.CoffeeHighlightRules = CoffeeHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/pythonic', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(markers) { this.foldingStartMarker = new RegExp("(?:([\\[{])|(" + markers + "))(?:\\s*)(?:#.*)?$"); }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { if (match[1]) return this.openingBracketBlock(session, match[1], row, match.index); if (match[2]) return this.indentationBlock(session, row, match.index + match[2].length); return this.indentationBlock(session, row); } } }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-coffee.js
JavaScript
asf20
16,016
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Colin Gourlay <colin DOT j DOT gourlay AT gmail DOT com> * Lee Gao * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/lua', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/lua_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var LuaHighlightRules = require("./lua_highlight_rules").LuaHighlightRules; var Mode = function() { this.$tokenizer = new Tokenizer(new LuaHighlightRules().getRules()); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var chunks = ["function", "then", "do", "repeat"]; if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } else { for (var i in tokens){ var token = tokens[i]; if (token.type != "keyword") continue; var chunk_i = chunks.indexOf(token.value); if (chunk_i != -1){ indent += tab; break; } } } } return indent; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/lua_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LuaHighlightRules = function() { var keywords = lang.arrayToMap( ("break|do|else|elseif|end|for|function|if|in|local|repeat|"+ "return|then|until|while|or|and|not").split("|") ); var builtinConstants = lang.arrayToMap( ("true|false|nil|_G|_VERSION").split("|") ); var builtinFunctions = lang.arrayToMap( ("string|xpcall|package|tostring|print|os|unpack|require|"+ "getfenv|setmetatable|next|assert|tonumber|io|rawequal|"+ "collectgarbage|getmetatable|module|rawset|math|debug|"+ "pcall|table|newproxy|type|coroutine|_G|select|gcinfo|"+ "pairs|rawget|loadstring|ipairs|_VERSION|dofile|setfenv|"+ "load|error|loadfile|"+ "sub|upper|len|gfind|rep|find|match|char|dump|gmatch|"+ "reverse|byte|format|gsub|lower|preload|loadlib|loaded|"+ "loaders|cpath|config|path|seeall|exit|setlocale|date|"+ "getenv|difftime|remove|time|clock|tmpname|rename|execute|"+ "lines|write|close|flush|open|output|type|read|stderr|"+ "stdin|input|stdout|popen|tmpfile|log|max|acos|huge|"+ "ldexp|pi|cos|tanh|pow|deg|tan|cosh|sinh|random|randomseed|"+ "frexp|ceil|floor|rad|abs|sqrt|modf|asin|min|mod|fmod|log10|"+ "atan2|exp|sin|atan|getupvalue|debug|sethook|getmetatable|"+ "gethook|setmetatable|setlocal|traceback|setfenv|getinfo|"+ "setupvalue|getlocal|getregistry|getfenv|setn|insert|getn|"+ "foreachi|maxn|foreach|concat|sort|remove|resume|yield|"+ "status|wrap|create|running").split("|") ); var stdLibaries = lang.arrayToMap( ("string|package|os|io|math|debug|table|coroutine").split("|") ); var metatableMethods = lang.arrayToMap( ("__add|__sub|__mod|__unm|__concat|__lt|__index|__call|__gc|__metatable|"+ "__mul|__div|__pow|__len|__eq|__le|__newindex|__tostring|__mode|__tonumber").split("|") ); var futureReserved = lang.arrayToMap( ("").split("|") ); var deprecatedIn5152 = lang.arrayToMap( ("setn|foreach|foreachi|gcinfo|log10|maxn").split("|") ); var strPre = ""; var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var integer = "(?:" + decimalInteger + "|" + hexInteger + ")"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var floatNumber = "(?:" + pointFloat + ")"; var comment_stack = []; this.$rules = { "start" : // bracketed comments [{ token : "comment", // --[[ comment regex : strPre + '\\-\\-\\[\\[.*\\]\\]' }, { token : "comment", // --[=[ comment regex : strPre + '\\-\\-\\[\\=\\[.*\\]\\=\\]' }, { token : "comment", // --[==[ comment regex : strPre + '\\-\\-\\[\\={2}\\[.*\\]\\={2}\\]' }, { token : "comment", // --[===[ comment regex : strPre + '\\-\\-\\[\\={3}\\[.*\\]\\={3}\\]' }, { token : "comment", // --[====[ comment regex : strPre + '\\-\\-\\[\\={4}\\[.*\\]\\={4}\\]' }, { token : "comment", // --[====+[ comment regex : strPre + '\\-\\-\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]' }, // multiline bracketed comments { token : "comment", // --[[ comment regex : strPre + '\\-\\-\\[\\[.*$', merge : true, next : "qcomment" }, { token : "comment", // --[=[ comment regex : strPre + '\\-\\-\\[\\=\\[.*$', merge : true, next : "qcomment1" }, { token : "comment", // --[==[ comment regex : strPre + '\\-\\-\\[\\={2}\\[.*$', merge : true, next : "qcomment2" }, { token : "comment", // --[===[ comment regex : strPre + '\\-\\-\\[\\={3}\\[.*$', merge : true, next : "qcomment3" }, { token : "comment", // --[====[ comment regex : strPre + '\\-\\-\\[\\={4}\\[.*$', merge : true, next : "qcomment4" }, { token : function(value){ // --[====+[ comment // WARNING: EXTREMELY SLOW, but this is the only way to circumvent the // limits imposed by the current automaton. // I've never personally seen any practical code where 5 or more '='s are // used for string or commenting, so this will rarely be invoked. var pattern = /\-\-\[(\=+)\[/, match; // you can never be too paranoid ;) if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined) comment_stack.push(match.length); return "comment"; }, regex : strPre + '\\-\\-\\[\\={5}\\=*\\[.*$', merge : true, next : "qcomment5" }, // single line comments { token : "comment", regex : "\\-\\-.*$" }, // bracketed strings { token : "string", // [[ string regex : strPre + '\\[\\[.*\\]\\]' }, { token : "string", // [=[ string regex : strPre + '\\[\\=\\[.*\\]\\=\\]' }, { token : "string", // [==[ string regex : strPre + '\\[\\={2}\\[.*\\]\\={2}\\]' }, { token : "string", // [===[ string regex : strPre + '\\[\\={3}\\[.*\\]\\={3}\\]' }, { token : "string", // [====[ string regex : strPre + '\\[\\={4}\\[.*\\]\\={4}\\]' }, { token : "string", // [====+[ string regex : strPre + '\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]' }, // multiline bracketed strings { token : "string", // [[ string regex : strPre + '\\[\\[.*$', merge : true, next : "qstring" }, { token : "string", // [=[ string regex : strPre + '\\[\\=\\[.*$', merge : true, next : "qstring1" }, { token : "string", // [==[ string regex : strPre + '\\[\\={2}\\[.*$', merge : true, next : "qstring2" }, { token : "string", // [===[ string regex : strPre + '\\[\\={3}\\[.*$', merge : true, next : "qstring3" }, { token : "string", // [====[ string regex : strPre + '\\[\\={4}\\[.*$', merge : true, next : "qstring4" }, { token : function(value){ // --[====+[ string // WARNING: EXTREMELY SLOW, see above. var pattern = /\[(\=+)\[/, match; if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined) comment_stack.push(match.length); return "string"; }, regex : strPre + '\\[\\={5}\\=*\\[.*$', merge : true, next : "qstring5" }, { token : "string", // " string regex : strPre + '"(?:[^\\\\]|\\\\.)*?"' }, { token : "string", // ' string regex : strPre + "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (stdLibaries.hasOwnProperty(value)) return "constant.library"; else if (deprecatedIn5152.hasOwnProperty(value)) return "invalid.deprecated"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (metatableMethods.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, 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+" } ], "qcomment": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment1": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\=\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment2": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment3": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment4": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment5": [ { token : function(value){ // very hackish, mutates the qcomment5 field on the fly. var pattern = /\](\=+)\]/, rule = this.rules.qcomment5[0], match; rule.next = "start"; if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined){ var found = match.length, expected; if ((expected = comment_stack.pop()) != found){ comment_stack.push(expected); rule.next = "qcomment5"; } } return "comment"; }, regex : "(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qstring": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring1": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\=\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring2": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring3": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring4": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring5": [ { token : function(value){ // very hackish, mutates the qstring5 field on the fly. var pattern = /\](\=+)\]/, rule = this.rules.qstring5[0], match; rule.next = "start"; if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined){ var found = match.length, expected; if ((expected = comment_stack.pop()) != found){ comment_stack.push(expected); rule.next = "qstring5"; } } return "string"; }, regex : "(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; } oop.inherits(LuaHighlightRules, TextHighlightRules); exports.LuaHighlightRules = LuaHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-lua.js
JavaScript
asf20
17,222
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/json', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/json_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle', 'ace/worker/worker_client'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HighlightRules = require("./json_highlight_rules").JsonHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var WorkerClient = require("../worker/worker_client").WorkerClient; var Mode = function() { this.$tokenizer = new Tokenizer(new HighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-json.js", "ace/mode/json_worker", "JsonWorker"); worker.attachToDocument(session.getDocument()); worker.on("error", function(e) { session.setAnnotations([e.data]); }); worker.on("ok", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/json_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JsonHighlightRules = function() { // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "variable", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]\\s*(?=:)' }, { token : "string", // single line regex : '"', next : "string" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : "invalid.illegal", // single quoted strings are not allowed regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "invalid.illegal", // comments are not allowed regex : "\\/\\/.*$" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "string" : [ { token : "constant.language.escape", regex : /\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4})/ }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : '"', next : "start", merge : true }, { token : "string", regex : "", next : "start", merge : true } ] }; }; oop.inherits(JsonHighlightRules, TextHighlightRules); exports.JsonHighlightRules = JsonHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-json.js
JavaScript
asf20
18,705
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/vibrant_ink', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-vibrant-ink"; exports.cssText = "\ .ace-vibrant-ink .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-vibrant-ink .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-vibrant-ink .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-vibrant-ink .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-vibrant-ink .ace_scroller {\ background-color: #0F0F0F;\ }\ \ .ace-vibrant-ink .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-vibrant-ink .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-vibrant-ink .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_selection {\ background: #6699CC;\ }\ \ .ace-vibrant-ink.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #0F0F0F;\ border-radius: 2px;\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #404040;\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_active_line {\ background: #333333;\ }\ \ .ace-vibrant-ink .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_selected_word {\ border: 1px solid #6699CC;\ }\ \ .ace-vibrant-ink .ace_invisible {\ color: #404040;\ }\ \ .ace-vibrant-ink .ace_keyword, .ace-vibrant-ink .ace_meta {\ color:#FF6600;\ }\ \ .ace-vibrant-ink .ace_constant, .ace-vibrant-ink .ace_constant.ace_other {\ color:#339999;\ }\ \ .ace-vibrant-ink .ace_constant.ace_character, {\ color:#339999;\ }\ \ .ace-vibrant-ink .ace_constant.ace_character.ace_escape, {\ color:#339999;\ }\ \ .ace-vibrant-ink .ace_constant.ace_numeric {\ color:#99CC99;\ }\ \ .ace-vibrant-ink .ace_invalid {\ color:#CCFF33;\ background-color:#000000;\ }\ \ .ace-vibrant-ink .ace_invalid.ace_deprecated {\ color:#CCFF33;\ background-color:#000000;\ }\ \ .ace-vibrant-ink .ace_fold {\ background-color: #FFCC00;\ border-color: #FFFFFF;\ }\ \ .ace-vibrant-ink .ace_support.ace_function {\ color:#FFCC00;\ }\ \ .ace-vibrant-ink .ace_variable {\ color:#FFCC00;\ }\ \ .ace-vibrant-ink .ace_variable.ace_parameter {\ font-style:italic;\ }\ \ .ace-vibrant-ink .ace_string {\ color:#66FF00;\ }\ \ .ace-vibrant-ink .ace_string.ace_regexp {\ color:#44B4CC;\ }\ \ .ace-vibrant-ink .ace_comment {\ color:#9933CC;\ }\ \ .ace-vibrant-ink .ace_entity.ace_other.ace_attribute-name {\ font-style:italic;\ color:#99CC99;\ }\ \ .ace-vibrant-ink .ace_entity.ace_name.ace_function {\ color:#FFCC00;\ }\ \ .ace-vibrant-ink .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-vibrant_ink.js
JavaScript
asf20
4,715
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/dawn', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-dawn"; exports.cssText = "\ .ace-dawn .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-dawn .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-dawn .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-dawn .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-dawn .ace_scroller {\ background-color: #F9F9F9;\ }\ \ .ace-dawn .ace_text-layer {\ cursor: text;\ color: #080808;\ }\ \ .ace-dawn .ace_cursor {\ border-left: 2px solid #000000;\ }\ \ .ace-dawn .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #000000;\ }\ \ .ace-dawn .ace_marker-layer .ace_selection {\ background: rgba(39, 95, 255, 0.30);\ }\ \ .ace-dawn.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #F9F9F9;\ border-radius: 2px;\ }\ \ .ace-dawn .ace_marker-layer .ace_step {\ background: rgb(255, 255, 0);\ }\ \ .ace-dawn .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(75, 75, 126, 0.50);\ }\ \ .ace-dawn .ace_marker-layer .ace_active_line {\ background: rgba(36, 99, 180, 0.12);\ }\ \ .ace-dawn .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-dawn .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(39, 95, 255, 0.30);\ }\ \ .ace-dawn .ace_invisible {\ color: rgba(75, 75, 126, 0.50);\ }\ \ .ace-dawn .ace_keyword, .ace-dawn .ace_meta {\ color:#794938;\ }\ \ .ace-dawn .ace_constant, .ace-dawn .ace_constant.ace_other {\ color:#811F24;\ }\ \ .ace-dawn .ace_constant.ace_character, {\ color:#811F24;\ }\ \ .ace-dawn .ace_constant.ace_character.ace_escape, {\ color:#811F24;\ }\ \ .ace-dawn .ace_invalid.ace_illegal {\ text-decoration:underline;\ font-style:italic;\ color:#F8F8F8;\ background-color:#B52A1D;\ }\ \ .ace-dawn .ace_invalid.ace_deprecated {\ text-decoration:underline;\ font-style:italic;\ color:#B52A1D;\ }\ \ .ace-dawn .ace_support {\ color:#691C97;\ }\ \ .ace-dawn .ace_support.ace_constant {\ color:#B4371F;\ }\ \ .ace-dawn .ace_fold {\ background-color: #794938;\ border-color: #080808;\ }\ \ .ace-dawn .ace_support.ace_function {\ color:#693A17;\ }\ \ .ace-dawn .ace_storage {\ font-style:italic;\ color:#A71D5D;\ }\ \ .ace-dawn .ace_string {\ color:#0B6125;\ }\ \ .ace-dawn .ace_string.ace_regexp {\ color:#CF5628;\ }\ \ .ace-dawn .ace_comment {\ font-style:italic;\ color:#5A525F;\ }\ \ .ace-dawn .ace_variable {\ color:#234A97;\ }\ \ .ace-dawn .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-dawn .ace_markup.ace_heading {\ color:#19356D;\ }\ \ .ace-dawn .ace_markup.ace_list {\ color:#693A17;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-dawn.js
JavaScript
asf20
4,639
/* ***** BEGIN LICENSE BLOCK ***** * The Original Code is Ajax.org Code Editor (ACE). * * Contributor(s): * Meg Sharkey <megshark AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/yaml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/yaml_highlight_rules', 'ace/mode/matching_brace_outdent'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var YamlHighlightRules = require("./yaml_highlight_rules").YamlHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Mode = function() { this.$tokenizer = new Tokenizer(new YamlHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/yaml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var YamlHighlightRules = function() { // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "comment", regex : "^---" }, { token: "variable", regex: "[&\\*][a-zA-Z0-9-_]+" }, { token: ["identifier", "text"], regex: "(\\w+\\s*:)(\\w*)" }, { token : "keyword.operator", regex : "<<\\w*:\\w*" }, { token : "keyword.operator", regex : "-\\s*(?=[{])" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '[\\|>]\\w*', next : "qqstring" }, { token : "string", // single quoted string regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false|yes|no)\\b" }, { token : "invalid.illegal", // comments are not allowed regex : "\\/\\/.*$" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "qqstring" : [ { token : "string", regex : '(?=(?:(?:\\\\.)|(?:[^:]))*?:)', next : "start" }, { token : "string", merge : true, regex : '.+' } ]} }; oop.inherits(YamlHighlightRules, TextHighlightRules); exports.YamlHighlightRules = YamlHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-yaml.js
JavaScript
asf20
5,984
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/kr_theme', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-kr-theme"; exports.cssText = "\ .ace-kr-theme .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-kr-theme .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-kr-theme .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-kr-theme .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-kr-theme .ace_scroller {\ background-color: #0B0A09;\ }\ \ .ace-kr-theme .ace_text-layer {\ cursor: text;\ color: #FCFFE0;\ }\ \ .ace-kr-theme .ace_cursor {\ border-left: 2px solid #FF9900;\ }\ \ .ace-kr-theme .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FF9900;\ }\ \ .ace-kr-theme .ace_marker-layer .ace_selection {\ background: rgba(170, 0, 255, 0.45);\ }\ \ .ace-kr-theme.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #0B0A09;\ border-radius: 2px;\ }\ \ .ace-kr-theme .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-kr-theme .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(255, 177, 111, 0.32);\ }\ \ .ace-kr-theme .ace_marker-layer .ace_active_line {\ background: #38403D;\ }\ \ .ace-kr-theme .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-kr-theme .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(170, 0, 255, 0.45);\ }\ \ .ace-kr-theme .ace_invisible {\ color: rgba(255, 177, 111, 0.32);\ }\ \ .ace-kr-theme .ace_keyword, .ace-kr-theme .ace_meta {\ color:#949C8B;\ }\ \ .ace-kr-theme .ace_constant, .ace-kr-theme .ace_constant.ace_other {\ color:rgba(210, 117, 24, 0.76);\ }\ \ .ace-kr-theme .ace_constant.ace_character, {\ color:rgba(210, 117, 24, 0.76);\ }\ \ .ace-kr-theme .ace_constant.ace_character.ace_escape, {\ color:rgba(210, 117, 24, 0.76);\ }\ \ .ace-kr-theme .ace_invalid {\ color:#F8F8F8;\ background-color:#A41300;\ }\ \ .ace-kr-theme .ace_support {\ color:#9FC28A;\ }\ \ .ace-kr-theme .ace_support.ace_constant {\ color:#C27E66;\ }\ \ .ace-kr-theme .ace_fold {\ background-color: #949C8B;\ border-color: #FCFFE0;\ }\ \ .ace-kr-theme .ace_support.ace_function {\ color:#85873A;\ }\ \ .ace-kr-theme .ace_storage {\ color:#FFEE80;\ }\ \ .ace-kr-theme .ace_string.ace_regexp {\ color:rgba(125, 255, 192, 0.65);\ }\ \ .ace-kr-theme .ace_comment {\ font-style:italic;\ color:#706D5B;\ }\ \ .ace-kr-theme .ace_variable {\ color:#D1A796;\ }\ \ .ace-kr-theme .ace_variable.ace_language {\ color:#FF80E1;\ }\ \ .ace-kr-theme .ace_meta.ace_tag {\ color:#BABD9C;\ }\ \ .ace-kr-theme .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-kr-theme .ace_markup.ace_list {\ background-color:#0F0040;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-kr_theme.js
JavaScript
asf20
4,670
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Garen J. Torikian <gjtorikian AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/c9search', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/c9search_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/c9search'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var C9SearchHighlightRules = require("./c9search_highlight_rules").C9SearchHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var C9StyleFoldMode = require("./folding/c9search").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new C9SearchHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new C9StyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/c9search_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var C9SearchHighlightRules = function() { // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : ["constant.numeric", "text", "text"], regex : "(^\\s+[0-9]+)(:\\s*)(.+)" }, { token : ["string", "text"], // single line regex : "(.+)(:$)" } ] }; }; oop.inherits(C9SearchHighlightRules, TextHighlightRules); exports.C9SearchHighlightRules = C9SearchHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/c9search', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /[a-zA-Z](:)\s*$/; this.foldingStopMarker = /^(\s*)$/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i, false, true); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-c9search.js
JavaScript
asf20
9,313
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/diff', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/diff_highlight_rules', 'ace/mode/folding/diff'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HighlightRules = require("./diff_highlight_rules").DiffHighlightRules; var FoldMode = require("./folding/diff").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new HighlightRules().getRules(), "i"); this.foldingRules = new FoldMode(["diff", "index", "\\+{3}", "@@|\\*{5}"], "i"); }; oop.inherits(Mode, TextMode); (function() { }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/diff_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DiffHighlightRules = function() { // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [{ "regex": "^(?:\\*{15}|={67}|-{3}|\\+{3})$", "token": "punctuation.definition.separator.diff", "name": "keyword" }, { //diff.range.unified "regex": "^(@@)(\\s*.+?\\s*)(@@)(.*)$", "token": [ "constant", "constant.numeric", "constant", "comment.doc.tag" ] }, { //diff.range.normal "regex": "^(\\d+)([,\\d]+)(a|d|c)(\\d+)([,\\d]+)(.*)$", "token": [ "constant.numeric", "punctuation.definition.range.diff", "constant.function", "constant.numeric", "punctuation.definition.range.diff", "invalid" ], "name": "meta." }, { "regex": "^(?:(\\-{3}|\\+{3}|\\*{3})( .+))$", "token": [ "constant.numeric", "meta.tag" ] }, { // added "regex": "^([!+>])(.*?)(\\s*)$", "token": [ "support.constant", "text", "invalid" ], }, { // removed "regex": "^([<\\-])(.*?)(\\s*)$", "token": [ "support.function", "string", "invalid" ], }, { "regex": "^(diff)(\\s+--\\w+)?(.+?)( .+)?$", "token": ["variable", "variable", "keyword", "variable"] }, { "regex": "^Index.+$", "token": "variable" }, { "regex": "^(.*?)(\\s*)$", "token": ["invisible", "invalid"] } ] }; }; oop.inherits(DiffHighlightRules, TextHighlightRules); exports.DiffHighlightRules = DiffHighlightRules; }); define('ace/mode/folding/diff', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function(levels, flag) { this.regExpList = levels; this.flag = flag; this.foldingStartMarker = RegExp("^(" + levels.join("|") + ")", this.flag); }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var start = {row: row, column: line.length}; var regList = this.regExpList; for (var i = 1; i <= regList.length; i++) { var re = RegExp("^(" + regList.slice(0, i).join("|") + ")", this.flag); if (re.test(line)) break; } for (var l = session.getLength(); ++row < l; ) { line = session.getLine(row); if (re.test(line)) break } if (row == start.row + 1) return; return Range.fromPoints(start, {row: row - 1, column: line.length}); }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-diff.js
JavaScript
asf20
8,559
define('ace/mode/powershell', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/powershell_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var PowershellHighlightRules = require("./powershell_highlight_rules").PowershellHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new PowershellHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/powershell_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PowershellHighlightRules = function() { var keywords = lang.arrayToMap( ("function|if|else|elseif|switch|while|default|for|do|until|break|continue|" + "foreach|return|filter|in|trap|throw|param|begin|process|end").split("|") ); var builtinFunctions = lang.arrayToMap( ("Get-Alias|Import-Alias|New-Alias|Set-Alias|Get-AuthenticodeSignature|Set-AuthenticodeSignature|" + "Set-Location|Get-ChildItem|Clear-Item|Get-Command|Measure-Command|Trace-Command|" + "Add-Computer|Checkpoint-Computer|Remove-Computer|Restart-Computer|Restore-Computer|Stop-Computer|" + "Reset-ComputerMachinePassword|Test-ComputerSecureChannel|Add-Content|Get-Content|Set-Content|Clear-Content|" + "Get-Command|Invoke-Command|Enable-ComputerRestore|Disable-ComputerRestore|Get-ComputerRestorePoint|Test-Connection|" + "ConvertFrom-CSV|ConvertTo-CSV|ConvertTo-Html|ConvertTo-Xml|ConvertFrom-SecureString|ConvertTo-SecureString|" + "Copy-Item|Export-Counter|Get-Counter|Import-Counter|Get-Credential|Get-Culture|" + "Get-ChildItem|Get-Date|Set-Date|Remove-Item|Compare-Object|Get-Event|" + "Get-WinEvent|New-Event|Remove-Event|Unregister-Event|Wait-Event|Clear-EventLog|" + "Get-Eventlog|Limit-EventLog|New-Eventlog|Remove-EventLog|Show-EventLog|Write-EventLog|" + "Get-EventSubscriber|Register-EngineEvent|Register-ObjectEvent|Register-WmiEvent|Get-ExecutionPolicy|Set-ExecutionPolicy|" + "Export-Alias|Export-Clixml|Export-Console|Export-Csv|ForEach-Object|Format-Custom|" + "Format-List|Format-Table|Format-Wide|Export-FormatData|Get-FormatData|Get-Item|" + "Get-ChildItem|Get-Help|Add-History|Clear-History|Get-History|Invoke-History|" + "Get-Host|Read-Host|Write-Host|Get-HotFix|Import-Clixml|Import-Csv|" + "Invoke-Command|Invoke-Expression|Get-Item|Invoke-Item|New-Item|Remove-Item|" + "Set-Item|Clear-ItemProperty|Copy-ItemProperty|Get-ItemProperty|Move-ItemProperty|New-ItemProperty|" + "Remove-ItemProperty|Rename-ItemProperty|Set-ItemProperty|Get-Job|Receive-Job|Remove-Job|" + "Start-Job|Stop-Job|Wait-Job|Stop-Process|Update-List|Get-Location|" + "Pop-Location|Push-Location|Set-Location|Send-MailMessage|Add-Member|Get-Member|" + "Move-Item|Compare-Object|Group-Object|Measure-Object|New-Object|Select-Object|" + "Sort-Object|Where-Object|Out-Default|Out-File|Out-GridView|Out-Host|" + "Out-Null|Out-Printer|Out-String|Convert-Path|Join-Path|Resolve-Path|" + "Split-Path|Test-Path|Get-Pfxcertificate|Pop-Location|Push-Location|Get-Process|" + "Start-Process|Stop-Process|Wait-Process|Enable-PSBreakpoint|Disable-PSBreakpoint|Get-PSBreakpoint|" + "Set-PSBreakpoint|Remove-PSBreakpoint|Get-PSDrive|New-PSDrive|Remove-PSDrive|Get-PSProvider|" + "Set-PSdebug|Enter-PSSession|Exit-PSSession|Export-PSSession|Get-PSSession|Import-PSSession|" + "New-PSSession|Remove-PSSession|Disable-PSSessionConfiguration|Enable-PSSessionConfiguration|Get-PSSessionConfiguration|Register-PSSessionConfiguration|" + "Set-PSSessionConfiguration|Unregister-PSSessionConfiguration|New-PSSessionOption|Add-PsSnapIn|Get-PsSnapin|Remove-PSSnapin|" + "Get-Random|Read-Host|Remove-Item|Rename-Item|Rename-ItemProperty|Select-Object|" + "Select-XML|Send-MailMessage|Get-Service|New-Service|Restart-Service|Resume-Service|" + "Set-Service|Start-Service|Stop-Service|Suspend-Service|Sort-Object|Start-Sleep|" + "ConvertFrom-StringData|Select-String|Tee-Object|New-Timespan|Trace-Command|Get-Tracesource|" + "Set-Tracesource|Start-Transaction|Complete-Transaction|Get-Transaction|Use-Transaction|Undo-Transaction|" + "Start-Transcript|Stop-Transcript|Add-Type|Update-TypeData|Get-Uiculture|Get-Unique|" + "Update-Formatdata|Update-Typedata|Clear-Variable|Get-Variable|New-Variable|Remove-Variable|" + "Set-Variable|New-WebServiceProxy|Where-Object|Write-Debug|Write-Error|Write-Host|" + "Write-Output|Write-Progress|Write-Verbose|Write-Warning|Set-WmiInstance|Invoke-WmiMethod|" + "Get-WmiObject|Remove-WmiObject|Connect-WSMan|Disconnect-WSMan|Test-WSMan|Invoke-WSManAction|" + "Disable-WSManCredSSP|Enable-WSManCredSSP|Get-WSManCredSSP|New-WSManInstance|Get-WSManInstance|Set-WSManInstance|" + "Remove-WSManInstance|Set-WSManQuickConfig|New-WSManSessionOption").split("|")); var binaryOperatorsRe = "eq|ne|ge|gt|lt|le|like|notlike|match|notmatch|replace|contains|notcontains|" + "ieq|ine|ige|igt|ile|ilt|ilike|inotlike|imatch|inotmatch|ireplace|icontains|inotcontains|" + "is|isnot|as|" + "and|or|band|bor|not"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "[$](?:[Tt]rue|[Ff]alse)\\b" }, { token : "constant.language", regex : "[$][Nn]ull\\b" }, { token : "variable.instance", regex : "[$][a-zA-Z][a-zA-Z0-9_]*\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$\\-]*\\b" }, { token : "keyword.operator", regex : "\\-(?:" + binaryOperatorsRe + ")" }, { token : "keyword.operator", regex : "&|\\*|\\+|\\-|\\=|\\+=|\\-=" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; }; oop.inherits(PowershellHighlightRules, TextHighlightRules); exports.PowershellHighlightRules = PowershellHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-powershell.js
JavaScript
asf20
22,107
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** 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 = ""; var global = (function() { return this; })(); var _define = function(module, deps, payload) { if (typeof module !== 'string') { if (_define.original) _define.original.apply(window, arguments); else { console.error('dropping module because define wasn\'t a string.'); console.trace(); } return; } if (arguments.length == 2) payload = deps; if (!_define.modules) _define.modules = {}; _define.modules[module] = payload; }; var _require = function(parentId, module, callback) { 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 && _require.original) return _require.original.apply(window, arguments); params.push(dep); } if (callback) { callback.apply(null, params); } } else if (typeof module === 'string') { var payload = lookup(parentId, module); if (!payload && _require.original) return _require.original.apply(window, arguments); if (callback) { callback(); } return payload; } else { if (_require.original) return _require.original.apply(window, arguments); } }; 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; }; var lookup = function(parentId, moduleName) { moduleName = normalizeModule(parentId, moduleName); var module = _define.modules[moduleName]; if (!module) { return null; } 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; // cache the resulting module object for next time _define.modules[moduleName] = exports; return exports; } return module; }; function exportAce(ns) { if (typeof requirejs !== "undefined") { var define = global.define; global.define = function(id, deps, callback) { if (typeof callback !== "function") return define.apply(this, arguments); return define(id, deps, function(require, exports, module) { if (deps[2] == "module") module.packaged = true; return callback.apply(this, arguments); }); }; global.define.packaged = true; return; } var require = function(module, callback) { return _require("", module, callback); }; require.packaged = true; var root = global; if (ns) { if (!global[ns]) global[ns] = {}; root = global[ns]; } if (root.define) _define.original = root.define; root.define = _define; if (root.require) _require.original = root.require; root.require = require; } exportAce(ACE_NAMESPACE); })(); /** * class Ace * * The main class required to set up an Ace instance in the browser. * * **/ 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/multi_select', 'ace/worker/worker_client', 'ace/keyboard/hash_handler', 'ace/keyboard/state_handler', 'ace/placeholder', 'ace/config', 'ace/theme/textmate'], function(require, exports, module) { 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; var MultiSelect = require("./multi_select").MultiSelect; // The following require()s are for inclusion in the built ace file require("./worker/worker_client"); require("./keyboard/hash_handler"); require("./keyboard/state_handler"); require("./placeholder"); exports.config = require("./config"); exports.edit = function(el) { if (typeof(el) == "string") { el = document.getElementById(el); } if (el.env && el.env.editor instanceof Editor) return el.env.editor; var doc = new EditSession(Dom.getInnerText(el)); doc.setUndoManager(new UndoManager()); el.innerHTML = ''; var editor = new Editor(new Renderer(el, require("./theme/textmate"))); new MultiSelect(editor); editor.setSession(doc); var env = {}; env.document = doc; env.editor = editor; editor.resize(); Event.addListener(window, "resize", function() { editor.resize(); }); el.env = env; // Store env on editor such that it can be accessed later on from // the returned object. editor.env = env; return editor; }; }); // vim:set ts=4 sts=4 sw=4 st: // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Irakli Gozalishvili Copyright (C) 2010 MIT License /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) { require("./regexp"); require("./es5-shim"); }); define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) { //--------------------------------- // Private variables //--------------------------------- 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; //--------------------------------- // Overriden native methods //--------------------------------- // Adds named capture support (with backreferences returned as `result.name`), and fixes two // cross-browser issues per ES3: // - Captured values for nonparticipating capturing groups should be returned as `undefined`, // rather than the empty string. // - `lastIndex` should not be incremented after zero-length matches. RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed // matching due to characters outside the match 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; } }); } // Attach named capture properties 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]; } } // Fix browsers that increment `lastIndex` after zero-length matches if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; } return match; }; // Don't override `test` if it won't change anything if (!compliantLastIndexIncrement) { // Fix browser bug in native method RegExp.prototype.test = function (str) { // Use the native `exec` to skip some processing overhead, even though the overriden // `exec` would take care of the `lastIndex` fix var match = real.exec.call(this, str); // Fix browsers that increment `lastIndex` after zero-length matches if (match && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; return !!match; }; } //--------------------------------- // Private helper functions //--------------------------------- 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; }; }); // vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License // -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License // -- kossnocorp Sasha Koss XXX TODO License or CLA // -- bryanforbes Bryan Forbes XXX TODO License or CLA // -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence // -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License // -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License // -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain) // -- iwyg XXX TODO License or CLA // -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License // -- xavierm02 Montillet Xavier XXX TODO License or CLA // -- Raynos Raynos XXX TODO License or CLA // -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License // -- rwldrn Rick Waldron Copyright (C) 2011 MIT License // -- lexer Alexey Zakharov XXX TODO License or CLA /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) { /* * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * * @module */ /*whatsupdoc*/ // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (typeof target != "function") throw new TypeError(); // TODO message // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){}; F.prototype = target.prototype; var self = new F; var result = target.apply( self, args.concat(slice.call(arguments)) ); if (result !== null && Object(result) === result) return result; return self; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(slice.call(arguments)) ); } }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. 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); // If JS engine supports accessors creating shortcuts. 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__); } // // Array // ===== // // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function isArray(obj) { return toString(obj) == "[object Array]"; }; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var self = toObject(this), thisp = arguments[1], i = 0, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object context fun.call(thisp, self[i], i, self); } i++; } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var self = toObject(this), length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, self); } return result; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, result = [], thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) result.push(self[i]); } return result; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, self)) return false; } return true; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) return true; } return false; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value and an empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) throw new TypeError(); // TODO message } while (true); } for (; i < length; i++) { if (i in self) result = fun.call(void 0, result, self[i], i, self); } return result; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value, empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) throw new TypeError(); // TODO message } while (true); } do { if (i in this) result = fun.call(void 0, result, self[i], i, self); } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = toObject(this), length = self.length >>> 0; if (!length) return -1; var i = 0; if (arguments.length > 1) i = toInteger(arguments[1]); // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = 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])); // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) return i; } return -1; }; } // // Object // ====== // // ES5 15.2.3.2 // http://es5.github.com/#x15.2.3.2 if (!Object.getPrototypeOf) { // https://github.com/kriskowal/es5-shim/issues#issue/2 // http://ejohn.org/blog/objectgetprototypeof/ // recommended by fschaefer on github Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } // ES5 15.2.3.3 // http://es5.github.com/#x15.2.3.3 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 object does not owns property return undefined immediately. if (!owns(object, property)) return; var descriptor, getter, setter; // If object has a property then it's for sure both `enumerable` and // `configurable`. descriptor = { enumerable: true, configurable: true }; // If JS engine supports accessor properties then property may be a // getter or setter. if (supportsAccessors) { // Unfortunately `__lookupGetter__` will return a getter even // if object has own non getter property along with a same named // inherited getter. To avoid misbehavior we temporary remove // `__proto__` so that `__lookupGetter__` will return getter only // if it's owned by an object. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); // Once we have getter and setter we can put values back. object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; // If it was accessor property we're done and return here // in order to avoid adding `value` to the descriptor. return descriptor; } } // If we got this far we know that object has an own property that is // not an accessor so we set it as a value and return descriptor. descriptor.value = object[property]; return descriptor; }; } // ES5 15.2.3.4 // http://es5.github.com/#x15.2.3.4 if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!Object.create) { Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = { "__proto__": null }; } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); // IE has no built-in implementation of `Object.getPrototypeOf` // neither `__proto__`, but this manually setting `__proto__` will // guarantee that `Object.getPrototypeOf` will work as expected with // objects created using `Object.create` object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } // ES5 15.2.3.6 // http://es5.github.com/#x15.2.3.6 // Patch for WebKit and IE8 standard mode // Designed by hax <hax.github.com> // related issue: https://github.com/kriskowal/es5-shim/issues#issue/5 // IE8 Reference: // http://msdn.microsoft.com/en-us/library/dd282900.aspx // http://msdn.microsoft.com/en-us/library/dd229916.aspx // WebKit Bugs: // https://bugs.webkit.org/show_bug.cgi?id=36423 function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { // returns falsy } } // check whether defineProperty works if it's given. Otherwise, // shim partially. 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); // make a valiant attempt to use the real defineProperty // for I8's DOM elements. if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { // try the shim if the real one doesn't work } } // If it's a data property. if (owns(descriptor, "value")) { // fail silently if "writable", "enumerable", or "configurable" // are requested but not supported /* // alternate approach: if ( // can't implement these features; allow false but not true !(owns(descriptor, "writable") ? descriptor.writable : true) || !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) || !(owns(descriptor, "configurable") ? descriptor.configurable : true) ) throw new RangeError( "This implementation of Object.defineProperty does not " + "support configurable, enumerable, or writable." ); */ if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { // As accessors are supported only on engines implementing // `__proto__` we can safely override `__proto__` while defining // a property to make sure that we don't hit an inherited // accessor. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; // Deleting a property anyway since getter / setter may be // defined on object itself. delete object[property]; object[property] = descriptor.value; // Setting original `__proto__` back now. object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); // If we got that far then getters and setters can be defined !! if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 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; }; } // ES5 15.2.3.8 // http://es5.github.com/#x15.2.3.8 if (!Object.seal) { Object.seal = function seal(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.9 // http://es5.github.com/#x15.2.3.9 if (!Object.freeze) { Object.freeze = function freeze(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // detect a Rhino bug and patch it 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); } // ES5 15.2.3.10 // http://es5.github.com/#x15.2.3.10 if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.11 // http://es5.github.com/#x15.2.3.11 if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } // ES5 15.2.3.12 // http://es5.github.com/#x15.2.3.12 if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } // ES5 15.2.3.13 // http://es5.github.com/#x15.2.3.13 if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { // 1. If Type(O) is not Object throw a TypeError exception. if (Object(object) === object) { throw new TypeError(); // TODO message } // 2. Return the Boolean value of the [[Extensible]] internal property of O. var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation 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; }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) { Date.prototype.toISOString = function toISOString() { var result, length, value, year; if (!isFinite(this)) throw new RangeError; // the date time string format is specified in 15.9.1.15. result = [this.getUTCMonth() + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = this.getUTCFullYear(); year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two digits. if (value < 10) result[length] = "0" + value; } // pad milliseconds to have three digits. return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z"; } } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). if (!Date.prototype.toJSON) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be ToPrimitive(O, hint Number). // 3. If tv is a Number and is not finite, return null. // XXX // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof this.toISOString != "function") throw new TypeError(); // TODO message // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return this.toISOString(); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function(NativeDate) { // Date.length === 7 var Date = function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length == 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); }; // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:\\.(\\d{3}))?" + // milliseconds capture ")?" + "(?:" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) Date[key] = NativeDate[key]; // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { match.shift(); // kill match[0], the full match // parse months, days, hours, minutes, seconds, and milliseconds for (var i = 1; i < 7; i++) { // provide default values if necessary match[i] = +(match[i] || (i < 3 ? 1 : 0)); // match[1] is the month. Months are 0-11 in JavaScript // `Date` objects, but 1-12 in ISO notation, so we // decrement. if (i == 1) match[i]--; } // parse the UTC offset component var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop(); // compute the explicit time zone offset if specified var offset = 0; if (sign) { // detect invalid offsets and return early if (hourOffset > 23 || minuteOffset > 59) return NaN; // express the provided time zone offset in minutes. The offset is // negative for time zones west of UTC; positive otherwise. offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1); } // Date.UTC for years between 0 and 99 converts year to 1900 + year // The Gregorian calendar has a 400-year cycle, so // to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...), // where 12622780800000 - number of milliseconds in Gregorian calendar 400 years var year = +match[0]; if (0 <= year && year <= 99) { match[0] = year + 400; return NativeDate.UTC.apply(this, match) + offset - 12622780800000; } // compute a new UTC date value, accounting for the optional offset return NativeDate.UTC.apply(this, match) + offset; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // // String // ====== // // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 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()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ 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, ""); }; } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer var toInteger = function (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; }; var prepareString = "a"[0] != "a", // ES5 9.9 // http://es5.github.com/#x9.9 toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError(); // TODO message } // If the implementation doesn't support by-index access of // string characters (ex. IE < 7), split the string if (prepareString && typeof o == "string" && o) { return o.split(""); } return Object(o); }; }); define('ace/lib/dom', ['require', 'exports', 'module' ], function(require, exports, module) { var XHTML_NS = "http://www.w3.org/1999/xhtml"; exports.createElement = function(tag, ns) { return document.createElementNS ? document.createElementNS(ns || XHTML_NS, tag) : document.createElement(tag); }; exports.setText = function(elem, text) { if (elem.innerText !== undefined) { elem.innerText = text; } if (elem.textContent !== undefined) { elem.textContent = text; } }; 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 style is already imported return immediately. if (id && exports.hasCssString(id, doc)) return null; var style; if (doc.createStyleSheet) { style = doc.createStyleSheet(); style.cssText = cssText; if (id) style.owningElement.id = id; } else { style = doc.createElementNS ? doc.createElementNS(XHTML_NS, "style") : doc.createElement("style"); style.appendChild(doc.createTextNode(cssText)); if (id) style.id = id; var head = doc.getElementsByTagName("head")[0] || doc.documentElement; head.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; var head = doc.getElementsByTagName("head")[0] || doc.documentElement; head.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 ); }; 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.scrollbarWidth = function(document) { var inner = exports.createElement("p"); inner.style.width = "100%"; inner.style.minWidth = "0px"; inner.style.height = "200px"; var outer = exports.createElement("div"); var style = outer.style; style.position = "absolute"; style.left = "-10000px"; style.overflow = "hidden"; style.width = "200px"; style.minWidth = "0px"; style.height = "150px"; outer.appendChild(inner); var body = document.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; }; exports.setInnerHtml = function(el, innerHtml) { var element = el.cloneNode(false);//document.createElement("div"); element.innerHTML = innerHtml; el.parentNode.replaceChild(element, el); return element; }; exports.setInnerText = function(el, innerText) { var document = el.ownerDocument; if (document.body && "textContent" in document.body) el.textContent = innerText; else el.innerText = innerText; }; exports.getInnerText = function(el) { var document = el.ownerDocument; if (document.body && "textContent" in document.body) return el.textContent; else return el.innerText || el.textContent || ""; }; exports.getParentWindow = function(document) { return document.defaultView || document.parentWindow; }; }); define('ace/lib/event', ['require', 'exports', 'module' , 'ace/lib/keys', 'ace/lib/useragent', 'ace/lib/dom'], function(require, exports, module) { var keys = require("./keys"); var useragent = require("./useragent"); var dom = require("./dom"); exports.addListener = function(elem, type, callback) { if (elem.addEventListener) { return elem.addEventListener(type, callback, false); } if (elem.attachEvent) { var wrapper = function() { callback(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; else if (e.type == "contextmenu") return 2; // DOM Event if (e.preventDefault) { return e.button; } // old IE else { return {1:0, 2:2, 4:1}[e.button]; } }; if (document.documentElement.setCapture) { exports.capture = function(el, eventHandler, releaseCaptureHandler) { function onMouseMove(e) { eventHandler(e); return exports.stopPropagation(e); } var called = false; function onReleaseCapture(e) { eventHandler(e); if (!called) { called = true; releaseCaptureHandler(e); } exports.removeListener(el, "mousemove", eventHandler); exports.removeListener(el, "mouseup", onReleaseCapture); exports.removeListener(el, "losecapture", onReleaseCapture); el.releaseCapture(); } exports.addListener(el, "mousemove", eventHandler); exports.addListener(el, "mouseup", onReleaseCapture); exports.addListener(el, "losecapture", onReleaseCapture); el.setCapture(); }; } else { exports.capture = function(el, eventHandler, releaseCaptureHandler) { function onMouseMove(e) { eventHandler(e); e.stopPropagation(); } function onMouseUp(e) { eventHandler && eventHandler(e); releaseCaptureHandler && releaseCaptureHandler(e); document.removeEventListener("mousemove", onMouseMove, true); document.removeEventListener("mouseup", onMouseUp, true); e.stopPropagation(); } document.addEventListener("mousemove", onMouseMove, true); document.addEventListener("mouseup", onMouseUp, true); }; } exports.addMouseWheelListener = function(el, callback) { var factor = 8; var listener = function(e) { if (e.wheelDelta !== undefined) { if (e.wheelDeltaX !== undefined) { e.wheelX = -e.wheelDeltaX / factor; e.wheelY = -e.wheelDeltaY / factor; } else { e.wheelX = 0; e.wheelY = -e.wheelDelta / factor; } } else { 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.addListener(el, "DOMMouseScroll", listener); exports.addListener(el, "mousewheel", listener); }; exports.addMultiMouseDownListener = function(el, timeouts, eventHandler, callbackName) { var clicks = 0; var startX, startY, timer; var eventNames = { 2: "dblclick", 3: "tripleclick", 4: "quadclick" }; var listener = function(e) { if (exports.getButton(e) != 0) { clicks = 0; } else { var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5; if (!timer || isNewClick) clicks = 0; clicks += 1; if (timer) clearTimeout(timer) timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600); } if (clicks == 1) { startX = e.clientX; startY = e.clientY; } eventHandler[callbackName]("mousedown", e); if (clicks > 4) clicks = 0; else if (clicks > 1) return eventHandler[callbackName](eventNames[clicks], e); }; exports.addListener(el, "mousedown", listener); useragent.isOldIE && exports.addListener(el, "dblclick", listener); }; function normalizeCommandKeys(callback, e, keyCode) { var hashId = 0; if (useragent.isOpera && useragent.isMac) { hashId = 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0); } else { hashId = 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0); } if (keyCode in keys.MODIFIER_KEYS) { switch (keys.MODIFIER_KEYS[keyCode]) { case "Alt": hashId = 2; break; case "Shift": hashId = 4; break; case "Ctrl": hashId = 1; break; default: hashId = 8; break; } keyCode = 0; } if (hashId & 8 && (keyCode == 91 || keyCode == 93)) { keyCode = 0; } // If there is no hashID and the keyCode is not a function key, then // we don't call the callback as we don't handle a command key here // (it's a normal key/character input). 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) { // Old versions of Gecko aka. Firefox < 4.0 didn't repeat the keydown // event if the user pressed the key for a longer time. Instead, the // keydown event was fired once and later on only the keypress event. // To emulate the 'right' keydown behavior, the keyCode of the initial // keyDown event is stored and in the following keypress events the // stores keyCode is used to emulate a keyDown event. var lastKeyDownKeyCode = null; addListener(el, "keydown", function(e) { lastKeyDownKeyCode = e.keyCode; }); addListener(el, "keypress", function(e) { return normalizeCommandKeys(callback, e, lastKeyDownKeyCode); }); } else { var lastDown = null; addListener(el, "keydown", function(e) { lastDown = e.keyIdentifier || e.keyCode; return normalizeCommandKeys(callback, e, e.keyCode); }); } }; if (window.postMessage) { 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, "*"); }; } else { exports.nextTick = function(callback, win) { win = win || window; window.setTimeout(callback, 0); }; } }); // Most of the following code is taken from SproutCore with a few changes. define('ace/lib/keys', ['require', 'exports', 'module' , 'ace/lib/oop'], function(require, exports, module) { 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, "meta": 8, "command": 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", 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: '.', 188: ',', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' } }; // A reverse map of FUNCTION_KEYS for (var i in ret.FUNCTION_KEYS) { var name = ret.FUNCTION_KEYS[i].toUpperCase(); ret[name] = parseInt(i, 10); } // Add the MODIFIER_KEYS, FUNCTION_KEYS and PRINTABLE_KEYS to the KEY // variables as well. oop.mixin(ret, ret.MODIFIER_KEYS); oop.mixin(ret, ret.PRINTABLE_KEYS); oop.mixin(ret, ret.FUNCTION_KEYS); return ret; })(); oop.mixin(exports, Keys); exports.keyCodeToString = function(keyCode) { return (Keys[keyCode] || String.fromCharCode(keyCode)).toLowerCase(); } }); define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) { exports.inherits = (function() { var tempCtor = function() {}; return function(ctor, superCtor) { tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor.prototype; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }; }()); exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); define('ace/lib/useragent', ['require', 'exports', 'module' ], function(require, exports, module) { var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase(); var ua = navigator.userAgent; // Is the user using a browser that identifies itself as Windows exports.isWin = (os == "win"); // Is the user using a browser that identifies itself as Mac OS exports.isMac = (os == "mac"); // Is the user using a browser that identifies itself as Linux exports.isLinux = (os == "linux"); exports.isIE = navigator.appName == "Microsoft Internet Explorer" && parseFloat(navigator.userAgent.match(/MSIE ([0-9]+[\.0-9]+)/)[1]); exports.isOldIE = exports.isIE && exports.isIE < 9; // Is this Firefox or related? exports.isGecko = exports.isMozilla = window.controllers && window.navigator.product === "Gecko"; // oldGecko == rev < 2.0 exports.isOldGecko = exports.isGecko && parseInt((navigator.userAgent.match(/rv\:(\d+)/)||[])[1], 10) < 4; // Is this Opera exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]"; // Is the user using a browser that identifies itself as WebKit 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.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; } }; }); define('ace/editor', ['require', 'exports', 'module' , 'ace/lib/fixoldbrowsers', 'ace/lib/oop', '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'], function(require, exports, module) { require("./lib/fixoldbrowsers"); var oop = require("./lib/oop"); 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 TouchHandler = require("./touch_handler").TouchHandler; 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; /** * new Editor(renderer, session) * - renderer (VirtualRenderer): Associated `VirtualRenderer` that draws everything * - session (EditSession): The `EditSession` to refer to * * Creates a new `Editor` object. * **/ 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); // TODO detect touch event support if (useragent.isIPad) { //this.$mouseHandler = new TouchHandler(this); } else { this.$mouseHandler = new MouseHandler(this); new FoldHandler(this); } this.$blockScrolling = 0; this.$search = new Search().set({ wrap: true }); this.setSession(session || new EditSession("")); }; (function(){ oop.implement(this, EventEmitter); this.setKeyboardHandler = function(keyboardHandler) { this.keyBinding.setKeyboardHandler(keyboardHandler); }; this.getKeyboardHandler = function() { return this.keyBinding.getKeyboardHandler(); }; this.setSession = function(session) { if (this.session == session) return; if (this.session) { var oldSession = this.session; this.session.removeEventListener("change", this.$onDocumentChange); this.session.removeEventListener("changeMode", this.$onChangeMode); this.session.removeEventListener("tokenizerUpdate", this.$onTokenizerUpdate); this.session.removeEventListener("changeTabSize", this.$onChangeTabSize); this.session.removeEventListener("changeWrapLimit", this.$onChangeWrapLimit); this.session.removeEventListener("changeWrapMode", this.$onChangeWrapMode); this.session.removeEventListener("onChangeFold", this.$onChangeFold); this.session.removeEventListener("changeFrontMarker", this.$onChangeFrontMarker); this.session.removeEventListener("changeBackMarker", this.$onChangeBackMarker); this.session.removeEventListener("changeBreakpoint", this.$onChangeBreakpoint); this.session.removeEventListener("changeAnnotation", this.$onChangeAnnotation); this.session.removeEventListener("changeOverwrite", this.$onCursorChange); this.session.removeEventListener("changeScrollTop", this.$onScrollTopChange); this.session.removeEventListener("changeLeftTop", this.$onScrollLeftChange); var selection = this.session.getSelection(); selection.removeEventListener("changeCursor", this.$onCursorChange); selection.removeEventListener("changeSelection", this.$onSelectionChange); } this.session = session; this.$onDocumentChange = this.onDocumentChange.bind(this); session.addEventListener("change", this.$onDocumentChange); this.renderer.setSession(session); this.$onChangeMode = this.onChangeMode.bind(this); session.addEventListener("changeMode", this.$onChangeMode); this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this); session.addEventListener("tokenizerUpdate", this.$onTokenizerUpdate); this.$onChangeTabSize = this.renderer.updateText.bind(this.renderer); session.addEventListener("changeTabSize", this.$onChangeTabSize); this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this); session.addEventListener("changeWrapLimit", this.$onChangeWrapLimit); this.$onChangeWrapMode = this.onChangeWrapMode.bind(this); session.addEventListener("changeWrapMode", this.$onChangeWrapMode); this.$onChangeFold = this.onChangeFold.bind(this); session.addEventListener("changeFold", this.$onChangeFold); this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this); this.session.addEventListener("changeFrontMarker", this.$onChangeFrontMarker); this.$onChangeBackMarker = this.onChangeBackMarker.bind(this); this.session.addEventListener("changeBackMarker", this.$onChangeBackMarker); this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this); this.session.addEventListener("changeBreakpoint", this.$onChangeBreakpoint); this.$onChangeAnnotation = this.onChangeAnnotation.bind(this); this.session.addEventListener("changeAnnotation", this.$onChangeAnnotation); this.$onCursorChange = this.onCursorChange.bind(this); this.session.addEventListener("changeOverwrite", this.$onCursorChange); this.$onScrollTopChange = this.onScrollTopChange.bind(this); this.session.addEventListener("changeScrollTop", this.$onScrollTopChange); this.$onScrollLeftChange = this.onScrollLeftChange.bind(this); this.session.addEventListener("changeScrollLeft", this.$onScrollLeftChange); this.selection = session.getSelection(); this.selection.addEventListener("changeCursor", this.$onCursorChange); this.$onSelectionChange = this.onSelectionChange.bind(this); this.selection.addEventListener("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(); this._emit("changeSession", { session: session, oldSession: oldSession }); }; 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) { this.renderer.setTheme(theme); }; this.getTheme = function() { return this.renderer.getTheme(); }; this.setStyle = function(style) { this.renderer.setStyle(style); }; this.unsetStyle = function(style) { this.renderer.unsetStyle(style); }; this.setFontSize = function(size) { this.container.style.fontSize = size; this.renderer.updateFontSize(); }; this.$highlightBrackets = function() { if (this.session.$bracketHighlight) { this.session.removeMarker(this.session.$bracketHighlight); this.session.$bracketHighlight = null; } if (this.$highlightPending) { return; } // perform highlight async to not block the browser during navigation var self = this; this.$highlightPending = true; setTimeout(function() { self.$highlightPending = false; var pos = self.session.findMatchingBracket(self.getCursorPosition()); if (pos) { var range = new Range(pos.row, pos.column, pos.row, pos.column+1); self.session.$bracketHighlight = self.session.addMarker(range, "ace_bracket", "text"); } }, 10); }; this.focus = function() { // Safari needs the timeout // iOS and Firefox need it called immediately // to be on the save side we do both 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() { if (this.$isFocused) return; this.$isFocused = true; this.renderer.showCursor(); this.renderer.visualizeFocus(); this._emit("focus"); }; this.onBlur = function() { if (!this.$isFocused) return; this.$isFocused = false; this.renderer.hideCursor(); this.renderer.visualizeBlur(); this._emit("blur"); }; this.$cursorChange = function() { this.renderer.updateCursor(); }; this.onDocumentChange = function(e) { var delta = e.data; var range = delta.range; var lastRow; if (range.start.row == range.end.row && delta.action != "insertLines" && delta.action != "removeLines") lastRow = range.end.row; else lastRow = Infinity; this.renderer.updateLines(range.start.row, lastRow); this._emit("change", e); // update cursor because tab characters can influence the cursor position this.$cursorChange(); }; 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) { this.renderer.scrollCursorIntoView(); } this.$highlightBrackets(); this.$updateHighlightActiveLine(); }; this.$updateHighlightActiveLine = function() { var session = this.getSession(); if (session.$highlightLineMarker) session.removeMarker(session.$highlightLineMarker); session.$highlightLineMarker = null; if (this.$highlightActiveLine) { var cursor = this.getCursorPosition(); var foldLine = this.session.getFoldLine(cursor.row); if ((this.getSelectionStyle() != "line" || !this.selection.isMultiLine())) { var range; if (foldLine) { range = new Range(foldLine.start.row, 0, foldLine.end.row + 1, 0); } else { range = new Range(cursor.row, 0, cursor.row+1, 0); } session.$highlightLineMarker = session.addMarker(range, "ace_active_line", "background"); } } }; 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.$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)); // Make sure the outer characters are not part of the word. 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() { this.renderer.updateText(); }; this.onChangeWrapLimit = function() { this.renderer.updateFull(); }; this.onChangeWrapMode = function() { this.renderer.onResize(true); }; this.onChangeFold = function() { // Update the active line marker as due to folding changes the current // line range on the screen might have changed. this.$updateHighlightActiveLine(); // TODO: This might be too much updating. Okay for now. this.renderer.updateFull(); }; this.getCopyText = function() { var text = ""; if (!this.selection.isEmpty()) text = this.session.getTextRange(this.getSelectionRange()); this._emit("copy", text); return text; }; this.onCopy = function() { this.commands.exec("copy", this); }; this.onCut = function() { this.commands.exec("cut", this); }; this.onPaste = function(text) { this._emit("paste", text); this.insert(text); }; this.insert = function(text) { var session = this.session; var mode = session.getMode(); var cursor = this.getCursorPosition(); if (this.getBehavioursEnabled()) { // Get a transform if the current mode wants one. var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text); if (transform) text = transform.text; } text = text.replace("\t", this.session.getTabString()); // remove selected text if (!this.selection.isEmpty()) { cursor = this.session.remove(this.getSelectionRange()); this.clearSelection(); } else if (this.session.getOverwrite()) { var range = new Range.fromPoints(cursor, cursor); range.end.column += text.length; this.session.remove(range); } this.clearSelection(); var start = cursor.column; var lineState = session.getState(cursor.row); var shouldOutdent = mode.checkOutdent(lineState, session.getLine(cursor.row), text); var line = session.getLine(cursor.row); var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString()); 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])); } } var lineState = session.getState(cursor.row); // TODO disabled multiline auto indent // possibly doing the indent before inserting the text // if (cursor.row !== end.row) { if (session.getDocument().isNewLine(text)) { this.moveCursorTo(cursor.row+1, 0); var size = session.getTabSize(); var minIndent = Number.MAX_VALUE; for (var row = cursor.row + 1; row <= end.row; ++row) { var indent = 0; line = session.getLine(row); for (var i = 0; i < line.length; ++i) if (line.charAt(i) == '\t') indent += size; else if (line.charAt(i) == ' ') indent += 1; else break; if (/[^\s]/.test(line)) minIndent = Math.min(indent, minIndent); } for (var row = cursor.row + 1; row <= end.row; ++row) { var outdent = minIndent; line = session.getLine(row); for (var i = 0; i < line.length && outdent > 0; ++i) if (line.charAt(i) == '\t') outdent -= size; else if (line.charAt(i) == ' ') outdent -= 1; session.remove(new Range(row, 0, row, i)); } session.indentRows(cursor.row + 1, end.row, 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.$mouseHandler.setScrollSpeed(speed); }; this.getScrollSpeed = function() { return this.$mouseHandler.getScrollSpeed(); }; this.setDragDelay = function(dragDelay) { this.$mouseHandler.setDragDelay(dragDelay); }; this.getDragDelay = function() { return this.$mouseHandler.getDragDelay(); }; this.$selectionStyle = "line"; this.setSelectionStyle = function(style) { if (this.$selectionStyle == style) return; this.$selectionStyle = style; this.onSelectionChange(); this._emit("changeSelectionStyle", {data: style}); }; this.getSelectionStyle = function() { return this.$selectionStyle; }; this.$highlightActiveLine = true; this.setHighlightActiveLine = function(shouldHighlight) { if (this.$highlightActiveLine == shouldHighlight) return; this.$highlightActiveLine = shouldHighlight; this.$updateHighlightActiveLine(); }; this.getHighlightActiveLine = function() { return this.$highlightActiveLine; }; this.$highlightGutterLine = true; this.setHighlightGutterLine = function(shouldHighlight) { if (this.$highlightGutterLine == shouldHighlight) return; this.renderer.setHighlightGutterLine(shouldHighlight); this.$highlightGutterLine = shouldHighlight; }; this.getHighlightGutterLine = function() { return this.$highlightGutterLine; }; this.$highlightSelectedWord = true; this.setHighlightSelectedWord = function(shouldHighlight) { if (this.$highlightSelectedWord == shouldHighlight) return; this.$highlightSelectedWord = shouldHighlight; this.$onSelectionChange(); }; 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) { if (this.getShowInvisibles() == showInvisibles) return; this.renderer.setShowInvisibles(showInvisibles); }; this.getShowInvisibles = function() { return this.renderer.getShowInvisibles(); }; 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.$readOnly = false; this.setReadOnly = function(readOnly) { this.$readOnly = readOnly; }; this.getReadOnly = function() { return this.$readOnly; }; this.$modeBehaviours = true; this.setBehavioursEnabled = function (enabled) { this.$modeBehaviours = enabled; }; this.getBehavioursEnabled = function () { return this.$modeBehaviours; }; this.setShowFoldWidgets = function(show) { var gutter = this.renderer.$gutterLayer; if (gutter.getShowFoldWidgets() == show) return; this.renderer.$gutterLayer.setShowFoldWidgets(show); this.$showFoldWidgets = show; this.renderer.updateFull(); }; this.getShowFoldWidgets = function() { return this.renderer.$gutterLayer.getShowFoldWidgets(); }; this.setFadeFoldWidgets = function(show) { this.renderer.setFadeFoldWidgets(show); }; this.getFadeFoldWidgets = function() { return this.renderer.getFadeFoldWidgets(); }; 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 (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 || range.start.column < range.end.column) { var rows = this.$getSelectedRows(); session.indentRows(rows.first, rows.last, "\t"); } else { var indentString; if (this.session.getUseSoftTabs()) { var size = session.getTabSize(), position = this.getCursorPosition(), column = session.documentToScreenColumn(position.row, position.column), count = (size - column % size); indentString = lang.stringRepeat(" ", count); } else indentString = "\t"; return this.insert(indentString); } }; this.blockOutdent = function() { var selection = this.session.getSelection(); this.session.outdentRows(selection.getRange()); }; 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.removeLines = function() { var rows = this.$getSelectedRows(); var range; if (rows.first === 0 || rows.last+1 < this.session.getLength()) range = new Range(rows.first, 0, rows.last+1, 0); else range = new Range( rows.first-1, this.session.getLine(rows.first-1).length, rows.last, this.session.getLine(rows.last).length ); this.session.remove(range); this.clearSelection(); }; this.moveLinesDown = function() { this.$moveLines(function(firstRow, lastRow) { return this.session.moveLinesDown(firstRow, lastRow); }); }; this.moveLinesUp = function() { this.$moveLines(function(firstRow, lastRow) { return this.session.moveLinesUp(firstRow, lastRow); }); }; this.moveText = function(range, toPosition) { if (this.$readOnly) return null; return this.session.moveText(range, toPosition); }; this.copyLinesUp = function() { this.$moveLines(function(firstRow, lastRow) { this.session.duplicateLines(firstRow, lastRow); return 0; }); }; this.copyLinesDown = function() { this.$moveLines(function(firstRow, lastRow) { return this.session.duplicateLines(firstRow, lastRow); }); }; this.$moveLines = function(mover) { var rows = this.$getSelectedRows(); var selection = this.selection; if (!selection.isMultiLine()) { var range = selection.getRange(); var reverse = selection.isBackwards(); } var linesMoved = mover.call(this, rows.first, rows.last); if (range) { range.start.row += linesMoved; range.end.row += linesMoved; selection.setSelectionRange(range, reverse); } else { selection.setSelectionAnchor(rows.last+linesMoved+1, 0); selection.$moveSelection(function() { selection.moveCursorTo(rows.first+linesMoved, 0); }); } }; this.$getSelectedRows = function() { var range = this.getSelectionRange().collapseRows(); return { first: range.start.row, last: 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 line = Math.floor(range.start.row + (range.end.row - range.start.row) / 2); this.renderer.scrollToLine(line, true); }; 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() { var cursor = this.getCursorPosition(); var pos = this.session.findMatchingBracket(cursor); if (!pos) { cursor.column += 1; pos = this.session.findMatchingBracket(cursor); } if (!pos) { cursor.column -= 2; pos = this.session.findMatchingBracket(cursor); } if (pos) { this.clearSelection(); this.moveCursorTo(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.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.clearSelection(); this.moveCursorTo(row, column); }; this.navigateUp = function(times) { this.selection.clearSelection(); times = times || 1; this.selection.moveCursorBy(-times, 0); }; this.navigateDown = function(times) { this.selection.clearSelection(); times = times || 1; this.selection.moveCursorBy(times, 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() { var scrollTop = this.renderer.scrollTop; this.selection.moveCursorFileEnd(); this.clearSelection(); this.renderer.animateScrolling(scrollTop); }; this.navigateFileStart = function() { var scrollTop = this.renderer.scrollTop; this.selection.moveCursorFileStart(); this.clearSelection(); this.renderer.animateScrolling(scrollTop); }; 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.clearSelection(); this.selection.moveCursorTo(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; } // clear selection if nothing is found 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(); }; }).call(Editor.prototype); exports.Editor = Editor; }); define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) { exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { return new Array(count + 1).join(string); }; 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<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function (obj) { if (typeof obj != "object") { return obj; } var copy = obj.constructor(); for (var key in obj) { if (typeof obj[key] == "object") { copy[key] = this.deepCopy(obj[key]); } else { copy[key] = obj[key]; } } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; return deferred; }; }); define('ace/keyboard/textinput', ['require', 'exports', 'module' , 'ace/lib/event', 'ace/lib/useragent', 'ace/lib/dom'], function(require, exports, module) { var event = require("../lib/event"); var useragent = require("../lib/useragent"); var dom = require("../lib/dom"); var TextInput = function(parentNode, host) { var text = dom.createElement("textarea"); if (useragent.isTouchPad) text.setAttribute("x-palm-disable-auto-cap", true); text.setAttribute("wrap", "off"); text.style.top = "-2em"; parentNode.insertBefore(text, parentNode.firstChild); var PLACEHOLDER = useragent.isIE ? "\x01" : "\x01"; sendText(); var inCompostion = false; var copied = false; var pasted = false; var tempStyle = ''; function reset(full) { try { if (full) { text.value = PLACEHOLDER; text.selectionStart = 0; text.selectionEnd = 1; } else text.select(); } catch (e) {} } function sendText(valueToSend) { if (!copied) { var value = valueToSend || text.value; if (value) { if (value.length > 1) { if (value.charAt(0) == PLACEHOLDER) value = value.substr(1); else if (value.charAt(value.length - 1) == PLACEHOLDER) value = value.slice(0, -1); } if (value && value != PLACEHOLDER) { if (pasted) host.onPaste(value); else host.onTextInput(value); } } } copied = false; pasted = false; // Safari doesn't fire copy events if no text is selected reset(true); } var onTextInput = function(e) { if (!inCompostion) sendText(e.data); setTimeout(function () { if (!inCompostion) reset(true); }, 0); }; var onPropertyChange = function(e) { setTimeout(function() { if (!inCompostion) sendText(); }, 0); }; var onCompositionStart = function(e) { inCompostion = true; host.onCompositionStart(); setTimeout(onCompositionUpdate, 0); }; var onCompositionUpdate = function() { if (!inCompostion) return; host.onCompositionUpdate(text.value); }; var onCompositionEnd = function(e) { inCompostion = false; host.onCompositionEnd(); }; var onCopy = function(e) { copied = true; var copyText = host.getCopyText(); if(copyText) text.value = copyText; else e.preventDefault(); reset(); setTimeout(function () { sendText(); }, 0); }; var onCut = function(e) { copied = true; var copyText = host.getCopyText(); if(copyText) { text.value = copyText; host.onCut(); } else e.preventDefault(); reset(); setTimeout(function () { sendText(); }, 0); }; event.addCommandKeyListener(text, host.onCommandKey.bind(host)); event.addListener(text, "input", useragent.isIE ? onPropertyChange : onTextInput); event.addListener(text, "paste", function(e) { // Mark that the next input text comes from past. pasted = true; // Some browsers support the event.clipboardData API. Use this to get // the pasted content which increases speed if pasting a lot of lines. if (e.clipboardData && e.clipboardData.getData) { sendText(e.clipboardData.getData("text/plain")); e.preventDefault(); } else { // If a browser doesn't support any of the things above, use the regular // method to detect the pasted input. onPropertyChange(); } }); if ("onbeforecopy" in text && typeof clipboardData !== "undefined") { event.addListener(text, "beforecopy", function(e) { if (tempStyle) return; // without this text is copied when contextmenu is shown var copyText = host.getCopyText(); if (copyText) clipboardData.setData("Text", copyText); else e.preventDefault(); }); event.addListener(parentNode, "keydown", function(e) { if (e.ctrlKey && e.keyCode == 88) { var copyText = host.getCopyText(); if (copyText) { clipboardData.setData("Text", copyText); host.onCut(); } event.preventDefault(e); } }); event.addListener(text, "cut", onCut); // for ie9 context menu } else if (useragent.isOpera) { event.addListener(parentNode, "keydown", function(e) { if ((useragent.isMac && !e.metaKey) || !e.ctrlKey) return; if ((e.keyCode == 88 || e.keyCode == 67)) { var copyText = host.getCopyText(); if (copyText) { text.value = copyText; text.select(); if (e.keyCode == 88) host.onCut(); } } }); } else { event.addListener(text, "copy", onCopy); event.addListener(text, "cut", onCut); } event.addListener(text, "compositionstart", onCompositionStart); if (useragent.isGecko) { event.addListener(text, "text", onCompositionUpdate); } if (useragent.isWebKit) { event.addListener(text, "keyup", onCompositionUpdate); } event.addListener(text, "compositionend", onCompositionEnd); event.addListener(text, "blur", function() { host.onBlur(); }); event.addListener(text, "focus", function() { host.onFocus(); reset(); }); this.focus = function() { host.onFocus(); reset(); text.focus(); }; this.blur = function() { text.blur(); }; function isFocused() { return document.activeElement === text; } this.isFocused = isFocused; this.getElement = function() { return text; }; this.onContextMenu = function(e) { if (!tempStyle) tempStyle = text.style.cssText; text.style.cssText = "position:fixed; z-index:100000;" + //"background:rgba(250, 0, 0, 0.3); opacity:1;" + "left:" + (e.clientX - 2) + "px; top:" + (e.clientY - 2) + "px;"; if (host.selection.isEmpty()) text.value = ""; if (e.type != "mousedown") return; if (host.renderer.$keepTextAreaAtCursor) host.renderer.$keepTextAreaAtCursor = null; event.capture(host.container, function(e) { text.style.left = e.clientX - 2 + "px"; text.style.top = e.clientY - 2 + "px"; }, onContextMenuClose); }; function onContextMenuClose() { setTimeout(function () { if (tempStyle) { text.style.cssText = tempStyle; tempStyle = ''; } sendText(); if (host.renderer.$keepTextAreaAtCursor == null) { host.renderer.$keepTextAreaAtCursor = true; host.renderer.$moveTextAreaToCursor(); } }, 0); }; this.onContextMenuClose = onContextMenuClose; // firefox fires contextmenu event after opening it if (!useragent.isGecko) event.addListener(text, "contextmenu", function(e) { host.textInput.onContextMenu(e); onContextMenuClose() }); }; exports.TextInput = TextInput; }); define('ace/mouse/mouse_handler', ['require', 'exports', 'module' , 'ace/lib/event', 'ace/mouse/default_handlers', 'ace/mouse/default_gutter_handler', 'ace/mouse/mouse_event', 'ace/mouse/dragdrop'], function(require, exports, module) { var event = require("../lib/event"); var DefaultHandlers = require("./default_handlers").DefaultHandlers; var DefaultGutterHandler = require("./default_gutter_handler").GutterHandler; var MouseEvent = require("./mouse_event").MouseEvent; var DragdropHandler = require("./dragdrop").DragdropHandler; var MouseHandler = function(editor) { this.editor = editor; new DefaultHandlers(this); new DefaultGutterHandler(this); new DragdropHandler(this); event.addListener(editor.container, "mousedown", function(e) { editor.focus(); return event.preventDefault(e); }); var mouseTarget = editor.renderer.getMouseEventTarget(); event.addListener(mouseTarget, "click", this.onMouseEvent.bind(this, "click")); event.addListener(mouseTarget, "mousemove", this.onMouseMove.bind(this, "mousemove")); event.addMultiMouseDownListener(mouseTarget, [300, 300, 250], this, "onMouseEvent"); event.addMouseWheelListener(editor.container, this.onMouseWheel.bind(this, "mousewheel")); var gutterEl = editor.renderer.$gutter; event.addListener(gutterEl, "mousedown", this.onMouseEvent.bind(this, "guttermousedown")); event.addListener(gutterEl, "click", this.onMouseEvent.bind(this, "gutterclick")); event.addListener(gutterEl, "dblclick", this.onMouseEvent.bind(this, "gutterdblclick")); event.addListener(gutterEl, "mousemove", this.onMouseMove.bind(this, "gutter")); }; (function() { this.$scrollSpeed = 1; this.setScrollSpeed = function(speed) { this.$scrollSpeed = speed; }; this.getScrollSpeed = function() { return this.$scrollSpeed; }; this.onMouseEvent = function(name, e) { this.editor._emit(name, new MouseEvent(e, this.editor)); }; this.$dragDelay = 250; this.setDragDelay = function(dragDelay) { this.$dragDelay = dragDelay; }; this.getDragDelay = function() { return this.$dragDelay; }; this.onMouseMove = function(name, e) { // optimization, because mousemove doesn't have a default handler. var listeners = this.editor._eventRegistry && this.editor._eventRegistry.mousemove; if (!listeners || !listeners.length) return; this.editor._emit(name, new MouseEvent(e, this.editor)); }; this.onMouseWheel = function(name, e) { var mouseEvent = new MouseEvent(e, this.editor); mouseEvent.speed = this.$scrollSpeed * 2; mouseEvent.wheelX = e.wheelX; mouseEvent.wheelY = e.wheelY; this.editor._emit(name, mouseEvent); }; this.setState = function(state) { this.state = state; }; this.captureMouse = function(ev, state) { if (state) this.setState(state); this.x = ev.x; this.y = ev.y; // do not move textarea during selection var renderer = this.editor.renderer; if (renderer.$keepTextAreaAtCursor) renderer.$keepTextAreaAtCursor = null; var self = this; var onMouseSelection = function(e) { self.x = e.clientX; self.y = e.clientY; }; var onMouseSelectionEnd = function(e) { clearInterval(timerId); self[self.state + "End"] && self[self.state + "End"](e); self.$clickSelection = null; if (renderer.$keepTextAreaAtCursor == null) { renderer.$keepTextAreaAtCursor = true; renderer.$moveTextAreaToCursor(); } }; var onSelectionInterval = function() { self[self.state] && self[self.state](); } event.capture(this.editor.container, onMouseSelection, onMouseSelectionEnd); var timerId = setInterval(onSelectionInterval, 20); }; }).call(MouseHandler.prototype); exports.MouseHandler = MouseHandler; }); define('ace/mouse/default_handlers', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/useragent'], function(require, exports, module) { var dom = require("../lib/dom"); var useragent = require("../lib/useragent"); var DRAG_OFFSET = 5; // pixels function DefaultHandlers(mouseHandler) { mouseHandler.$clickSelection = null; var editor = mouseHandler.editor; editor.setDefaultHandler("mousedown", this.onMouseDown.bind(mouseHandler)); editor.setDefaultHandler("dblclick", this.onDoubleClick.bind(mouseHandler)); editor.setDefaultHandler("tripleclick", this.onTripleClick.bind(mouseHandler)); editor.setDefaultHandler("quadclick", this.onQuadClick.bind(mouseHandler)); editor.setDefaultHandler("mousewheel", this.onScroll.bind(mouseHandler)); var exports = ["select", "startSelect", "drag", "dragEnd", "dragWait", "dragWaitEnd", "startDrag", "focusWait"]; exports.forEach(function(x) { mouseHandler[x] = this[x]; }, this); mouseHandler.selectByLines = this.extendSelectionBy.bind(mouseHandler, "getLineRange"); mouseHandler.selectByWords = this.extendSelectionBy.bind(mouseHandler, "getWordRange"); mouseHandler.$focusWaitTimout = 250; } (function() { this.onMouseDown = function(ev) { var inSelection = ev.inSelection(); var pos = ev.getDocumentPosition(); this.mousedownEvent = ev; var editor = this.editor; var _self = this; var button = ev.getButton(); if (button !== 0) { var selectionRange = editor.getSelectionRange(); var selectionEmpty = selectionRange.isEmpty(); if (selectionEmpty) { editor.moveCursorToPosition(pos); editor.selection.clearSelection(); } // 2: contextmenu, 1: linux paste editor.textInput.onContextMenu(ev.domEvent); return ev.stop(); } // if this click caused the editor to be focused should not clear the // selection if (inSelection && !editor.isFocused()) { editor.focus(); if (this.$focusWaitTimout && !this.$clickSelection) { this.setState("focusWait"); this.captureMouse(ev); return ev.preventDefault(); } } if (!inSelection || this.$clickSelection || ev.getShiftKey()) { // Directly pick STATE_SELECT, since the user is not clicking inside // a selection. this.startSelect(pos); } else if (inSelection) { var e = ev.domEvent; if ((e.ctrlKey || e.altKey)) { this.startDrag(); } else { this.mousedownEvent.time = (new Date()).getTime(); this.setState("dragWait"); } } this.captureMouse(ev); return ev.preventDefault(); }; this.startSelect = function(pos) { pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y); if (this.mousedownEvent.getShiftKey()) { this.editor.selection.selectToPosition(pos); } else if (!this.$clickSelection) { this.editor.moveCursorToPosition(pos); this.editor.selection.clearSelection(); } this.setState("select"); } this.select = function() { var anchor, editor = this.editor; var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); 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 { cursor = this.$clickSelection.end; anchor = this.$clickSelection.start; } editor.selection.setSelectionAnchor(anchor.row, anchor.column); } editor.selection.selectToPosition(cursor); 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); 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; cursor = range.start; } else if (cmpEnd == 1 && cmpStart >= 0) { anchor = this.$clickSelection.start; cursor = range.end; } else if (cmpStart == -1 && cmpEnd == 1) { cursor = range.end; anchor = range.start; } else { cursor = this.$clickSelection.end; anchor = this.$clickSelection.start; } editor.selection.setSelectionAnchor(anchor.row, anchor.column); } editor.selection.selectToPosition(cursor); editor.renderer.scrollCursorIntoView(); }; this.startDrag = function() { var editor = this.editor; this.setState("drag"); this.dragRange = editor.getSelectionRange(); var style = editor.getSelectionStyle(); this.dragSelectionMarker = editor.session.addMarker(this.dragRange, "ace_selection", style); editor.clearSelection(); dom.addCssClass(editor.container, "ace_dragging"); if (!this.$dragKeybinding) { this.$dragKeybinding = { handleKeyboard: function(data, hashId, keyString, keyCode) { if (keyString == "esc") return {command: this.command}; }, command: { exec: function(editor) { var self = editor.$mouseHandler; self.dragCursor = null self.dragEnd(); self.startSelect(); } } } } editor.keyBinding.addKeyboardHandler(this.$dragKeybinding); }; this.focusWait = function() { var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); var time = (new Date()).getTime(); if (distance > DRAG_OFFSET ||time - this.mousedownEvent.time > this.$focusWaitTimout) this.startSelect(); }; this.dragWait = function() { var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); var time = (new Date()).getTime(); var editor = this.editor; if (distance > DRAG_OFFSET) { this.startSelect(); } else if (time - this.mousedownEvent.time > editor.getDragDelay()) { this.startDrag() } }; this.dragWaitEnd = function(e) { this.mousedownEvent.domEvent = e; this.startSelect(); }; this.drag = function() { var editor = this.editor; this.dragCursor = editor.renderer.screenToTextCoordinates(this.x, this.y); editor.moveCursorToPosition(this.dragCursor); editor.renderer.scrollCursorIntoView(); }; this.dragEnd = function(e) { var editor = this.editor; var dragCursor = this.dragCursor; var dragRange = this.dragRange; dom.removeCssClass(editor.container, "ace_dragging"); editor.session.removeMarker(this.dragSelectionMarker); editor.keyBinding.removeKeyboardHandler(this.$dragKeybinding); if (!dragCursor) return; editor.clearSelection(); if (e && (e.ctrlKey || e.altKey)) { var session = editor.session; var newRange = dragRange; newRange.end = session.insert(dragCursor, session.getTextRange(dragRange)); newRange.start = dragCursor; } else if (dragRange.contains(dragCursor.row, dragCursor.column)) { return; } else { var newRange = editor.moveText(dragRange, dragCursor); } if (!newRange) return; editor.selection.setSelectionRange(newRange); }; this.onDoubleClick = function(ev) { var pos = ev.getDocumentPosition(); var editor = this.editor; this.setState("selectByWords"); editor.moveCursorToPosition(pos); editor.selection.selectWord(); this.$clickSelection = editor.getSelectionRange(); }; this.onTripleClick = function(ev) { var pos = ev.getDocumentPosition(); var editor = this.editor; this.setState("selectByLines"); editor.moveCursorToPosition(pos); editor.selection.selectLine(); this.$clickSelection = editor.getSelectionRange(); }; this.onQuadClick = function(ev) { var editor = this.editor; editor.selectAll(); this.$clickSelection = editor.getSelectionRange(); this.setState("null"); }; this.onScroll = function(ev) { var editor = this.editor; var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); if (isScrolable) { this.$passScrollEvent = false; } else { if (this.$passScrollEvent) return; if (!this.$scrollStopTimeout) { var self = this; this.$scrollStopTimeout = setTimeout(function() { self.$passScrollEvent = true; self.$scrollStopTimeout = null; }, 200); } } editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); return ev.preventDefault(); }; }).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)); } }); define('ace/mouse/default_gutter_handler', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) { var dom = require("../lib/dom"); function GutterHandler(mouseHandler) { var editor = mouseHandler.editor; mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) { var target = e.domEvent.target; if (target.className.indexOf("ace_gutter-cell") == -1) return; if (!editor.isFocused()) return; var padding = parseInt(dom.computedStyle(target).paddingLeft); if (e.x < padding + target.getBoundingClientRect().left + 1) return; var row = e.getDocumentPosition().row; var selection = editor.session.selection; if (e.getShiftKey()) { selection.selectTo(row, 0); } else { selection.moveCursorTo(row, 0); selection.selectLine(); mouseHandler.$clickSelection = selection.getRange(); } mouseHandler.captureMouse(e, "selectByLines"); return e.preventDefault(); }); } exports.GutterHandler = GutterHandler; }); define('ace/mouse/mouse_event', ['require', 'exports', 'module' , 'ace/lib/event'], function(require, exports, module) { var event = require("../lib/event"); 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; if (editor.getReadOnly()) { this.$inSelection = false; } else { 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 = function() { return this.domEvent.ctrlKey || this.domEvent.metaKey ; }; }).call(MouseEvent.prototype); }); define('ace/mouse/dragdrop', ['require', 'exports', 'module' , 'ace/lib/event'], function(require, exports, module) { var event = require("../lib/event"); var DragdropHandler = function(mouseHandler) { var editor = mouseHandler.editor; var dragSelectionMarker, x, y; var timerId, range, isBackwards; var dragCursor, counter = 0; var mouseTarget = editor.container; event.addListener(mouseTarget, "dragenter", function(e) {console.log(e.type, counter,e.target); counter++; if (!dragSelectionMarker) { range = editor.getSelectionRange(); isBackwards = editor.selection.isBackwards(); var style = editor.getSelectionStyle(); dragSelectionMarker = editor.session.addMarker(range, "ace_selection", style); editor.clearSelection(); clearInterval(timerId); timerId = setInterval(onDragInterval, 20); } return event.preventDefault(e); }); event.addListener(mouseTarget, "dragover", function(e) { x = e.clientX; y = e.clientY; return event.preventDefault(e); }); var onDragInterval = function() { dragCursor = editor.renderer.screenToTextCoordinates(x, y); editor.moveCursorToPosition(dragCursor); editor.renderer.scrollCursorIntoView(); }; event.addListener(mouseTarget, "dragleave", function(e) {console.log(e.type, counter,e.target); counter--; if (counter > 0) return; console.log(e.type, counter,e.target); clearInterval(timerId); editor.session.removeMarker(dragSelectionMarker); dragSelectionMarker = null; editor.selection.setSelectionRange(range, isBackwards); return event.preventDefault(e); }); event.addListener(mouseTarget, "drop", function(e) { console.log(e.type, counter,e.target); counter = 0; clearInterval(timerId); editor.session.removeMarker(dragSelectionMarker); dragSelectionMarker = null; range.end = editor.session.insert(dragCursor, e.dataTransfer.getData('Text')); range.start = dragCursor; editor.focus(); editor.selection.setSelectionRange(range); return event.preventDefault(e); }); }; exports.DragdropHandler = DragdropHandler; }); define('ace/mouse/fold_handler', ['require', 'exports', 'module' ], function(require, exports, module) { function FoldHandler(editor) { editor.on("click", function(e) { var position = e.getDocumentPosition(); var session = editor.session; // If the user clicked on a fold, then expand it. var fold = session.getFoldAt(position.row, position.column, 1); if (fold) { if (e.getAccelKey()) session.removeFold(fold); else session.expandFold(fold); e.stop(); } }); editor.on("gutterclick", function(e) { if (e.domEvent.target.className.indexOf("ace_fold-widget") != -1) { var row = e.getDocumentPosition().row; editor.session.onFoldWidgetClick(row, e.domEvent); e.stop(); } }); } exports.FoldHandler = FoldHandler; }); define('ace/keyboard/keybinding', ['require', 'exports', 'module' , 'ace/lib/keys', 'ace/lib/event'], function(require, exports, module) { var keyUtil = require("../lib/keys"); var event = require("../lib/event"); var KeyBinding = function(editor) { this.$editor = editor; this.$data = { }; this.$handlers = []; this.setDefaultHandler(editor.commands); }; (function() { this.setDefaultHandler = function(kb) { this.removeKeyboardHandler(this.$defaultHandler); this.$defaultHandler = kb; this.addKeyboardHandler(kb, 0); this.$data = {editor: this.$editor}; }; this.setKeyboardHandler = function(kb) { if (this.$handlers[this.$handlers.length - 1] == kb) return; while (this.$handlers[1]) this.removeKeyboardHandler(this.$handlers[1]); this.addKeyboardHandler(kb, 1); }; this.addKeyboardHandler = function(kb, pos) { if (!kb) return; var i = this.$handlers.indexOf(kb); if (i != -1) this.$handlers.splice(i, 1); if (pos == undefined) this.$handlers.push(kb); else this.$handlers.splice(pos, 0, kb); if (i == -1 && kb.attach) kb.attach(this.$editor); }; this.removeKeyboardHandler = function(kb) { var i = this.$handlers.indexOf(kb); if (i == -1) return false; this.$handlers.splice(i, 1); kb.detach && kb.detach(this.$editor); return true; }; this.getKeyboardHandler = function() { return this.$handlers[this.$handlers.length - 1]; }; this.$callKeyboardHandlers = function (hashId, keyString, keyCode, e) { var toExecute; for (var i = this.$handlers.length; i--;) { toExecute = this.$handlers[i].handleKeyboard( this.$data, hashId, keyString, keyCode, e ); if (toExecute && toExecute.command) break; } if (!toExecute || !toExecute.command) return false; var success = false; var commands = this.$editor.commands; // allow keyboardHandler to consume keys if (toExecute.command != "null") success = commands.exec(toExecute.command, this.$editor, toExecute.args, e); else success = toExecute.passEvent != true; // do not stop input events to not break repeating if (success && e && hashId != -1) event.stopEvent(e); return success; }; this.onCommandKey = function(e, hashId, keyCode) { var keyString = keyUtil.keyCodeToString(keyCode); this.$callKeyboardHandlers(hashId, keyString, keyCode, e); }; this.onTextInput = function(text) { var success = this.$callKeyboardHandlers(-1, text); if (!success) this.$editor.commands.exec("insertstring", this.$editor, text); }; }).call(KeyBinding.prototype); exports.KeyBinding = KeyBinding; }); define('ace/edit_session', ['require', 'exports', 'module' , 'ace/config', 'ace/lib/oop', 'ace/lib/lang', 'ace/lib/net', '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) { var config = require("./config"); var oop = require("./lib/oop"); var lang = require("./lib/lang"); var net = require("./lib/net"); 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; /** * new EditSession(text, mode) * - text (Document | String): If `text` is a `Document`, it associates the `EditSession` with it. Otherwise, a new `Document` is created, with the initial text * - mode (TextMode): The inital language mode to use for the document * * Sets up a new `EditSession` and associates it with the given `Document` and `TextMode`. * **/ var EditSession = function(text, mode) { this.$modified = true; this.$breakpoints = []; this.$frontMarkers = {}; this.$backMarkers = {}; this.$markerId = 1; this.$resetRowCache(0); this.$wrapData = []; this.$foldData = []; this.$rowLengthCache = []; this.$undoSelect = true; this.$foldData.toString = function() { var str = ""; this.forEach(function(foldLine) { str += "\n" + foldLine.toString(); }); return str; } if (typeof text == "object" && text.getLine) { this.setDocument(text); } else { this.setDocument(new Document(text)); } this.selection = new Selection(this); this.setMode(mode); }; (function() { oop.implement(this, EventEmitter); this.setDocument = function(doc) { if (this.doc) throw new Error("Document is already set"); this.doc = doc; doc.on("change", this.onChange.bind(this)); this.on("changeFold", this.onChangeFold.bind(this)); if (this.bgTokenizer) { this.bgTokenizer.setDocument(this.getDocument()); this.bgTokenizer.start(0); } }; this.getDocument = function() { return this.doc; }; this.$resetRowCache = function(docRrow) { if (!docRrow) { this.$docRowCache = []; this.$screenRowCache = []; return; } var i = this.$getRowCacheIndex(this.$docRowCache, docRrow) + 1; var l = this.$docRowCache.length; 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 && low -1; }; this.onChangeFold = function(e) { var fold = e.data; this.$resetRowCache(fold.start.row); }; this.onChange = function(e) { var delta = e.data; this.$modified = true; this.$resetRowCache(delta.range.start.row); var removedFolds = this.$updateInternalDataOnChange(e); 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.$updateOnChange(delta); this._emit("change", e); }; this.setValue = function(text) { this.doc.setValue(text); this.selection.moveCursorTo(0, 0); this.selection.clearSelection(); this.$resetRowCache(0); this.$deltas = []; this.$deltasDoc = []; this.$deltasFold = []; this.getUndoManager().reset(); }; /** alias of: EditSession.getValue * EditSession.toString() -> String * * Returns the current [[Document `Document`]] as a string. * **/ 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.highlight = function(re) { if (!this.$searchHighlight) { var highlight = new SearchHighlight(null, "ace_selected_word", "text"); this.$searchHighlight = this.addDynamicMarker(highlight); } this.$searchHighlight.setRegexp(re); } /** * EditSession.setUndoManager(undoManager) * - undoManager (UndoManager): The new undo manager * * Sets the undo manager. **/ 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] }); } self.$deltas = []; } this.$informUndoManager = lang.deferredCall(this.$syncInformUndoManager); } }; this.$defaultUndoManager = { undo: function() {}, redo: function() {}, reset: function() {} }; this.getUndoManager = function() { return this.$undoManager || this.$defaultUndoManager; }, /** * EditSession.getTabString() -> String * * Returns the current value for tabs. If the user is using soft tabs, this will be a series of spaces (defined by [[EditSession.getTabSize `getTabSize()`]]); otherwise it's simply `'\t'`. **/ this.getTabString = function() { if (this.getUseSoftTabs()) { return lang.stringRepeat(" ", this.getTabSize()); } else { return "\t"; } }; this.$useSoftTabs = true; this.setUseSoftTabs = function(useSoftTabs) { if (this.$useSoftTabs === useSoftTabs) return; this.$useSoftTabs = useSoftTabs; }; this.getUseSoftTabs = function() { return this.$useSoftTabs; }; this.$tabSize = 4; this.setTabSize = function(tabSize) { if (isNaN(tabSize) || this.$tabSize === tabSize) return; this.$modified = true; this.$rowLengthCache = []; this.$tabSize = tabSize; this._emit("changeTabSize"); }; 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) { if (this.$overwrite == overwrite) return; this.$overwrite = overwrite; this._emit("changeOverwrite"); }; this.getOverwrite = function() { return this.$overwrite; }; this.toggleOverwrite = function() { this.setOverwrite(!this.$overwrite); }; this.getBreakpoints = function() { return this.$breakpoints; }; this.setBreakpoints = function(rows) { this.$breakpoints = []; for (var i=0; i<rows.length; i++) { this.$breakpoints[rows[i]] = true; } this._emit("changeBreakpoint", {}); }; this.clearBreakpoints = function() { this.$breakpoints = []; this._emit("changeBreakpoint", {}); }; this.setBreakpoint = function(row) { this.$breakpoints[row] = true; this._emit("changeBreakpoint", {}); }; this.clearBreakpoint = function(row) { delete this.$breakpoints[row]; this._emit("changeBreakpoint", {}); }; this.addMarker = function(range, clazz, type, inFront) { var id = this.$markerId++; var marker = { range : range, type : type || "line", renderer: typeof type == "function" ? type : null, clazz : clazz, inFront: !!inFront, id: id } if (inFront) { this.$frontMarkers[id] = marker; this._emit("changeFrontMarker") } else { this.$backMarkers[id] = marker; this._emit("changeBackMarker") } return id; }; this.addDynamicMarker = function(marker, inFront) { if (!marker.update) return; var id = this.$markerId++; marker.id = id; marker.inFront = !!inFront; if (inFront) { this.$frontMarkers[id] = marker; this._emit("changeFrontMarker") } else { this.$backMarkers[id] = marker; this._emit("changeBackMarker") } return marker; }; this.removeMarker = function(markerId) { var marker = this.$frontMarkers[markerId] || this.$backMarkers[markerId]; if (!marker) return; var markers = marker.inFront ? this.$frontMarkers : this.$backMarkers; if (marker) { delete (markers[markerId]); this._emit(marker.inFront ? "changeFrontMarker" : "changeBackMarker"); } }; this.getMarkers = function(inFront) { return inFront ? this.$frontMarkers : this.$backMarkers; }; /** * EditSession.setAnnotations(annotations) * - annotations (Array): A list of annotations * * Sets annotations for the `EditSession`. This functions emits the `'changeAnnotation'` event. **/ this.setAnnotations = function(annotations) { this.$annotations = {}; for (var i=0; i<annotations.length; i++) { var annotation = annotations[i]; var row = annotation.row; if (this.$annotations[row]) this.$annotations[row].push(annotation); else this.$annotations[row] = [annotation]; } this._emit("changeAnnotation", {}); }; this.getAnnotations = function() { return this.$annotations || {}; }; this.clearAnnotations = function() { this.$annotations = {}; this._emit("changeAnnotation", {}); }; this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r?\n)/m); if (match) { this.$autoNewLine = match[1]; } else { this.$autoNewLine = "\n"; } }; this.getWordRange = function(row, column) { var line = this.getLine(row); var inToken = false; if (column > 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.$useWorker = true; this.setUseWorker = function(useWorker) { if (this.$useWorker == useWorker) return; this.$useWorker = useWorker; this.$stopWorker(); if (useWorker) this.$startWorker(); }; this.getUseWorker = function() { return this.$useWorker; }; this.onReloadTokenizer = function(e) { var rows = e.data; this.bgTokenizer.start(rows.first); this._emit("tokenizerUpdate", e); }; this.$modes = {}; this._loadMode = function(mode, callback) { if (!this.$modes["null"]) this.$modes["null"] = this.$modes["ace/mode/text"] = new TextMode(); if (this.$modes[mode]) return callback(this.$modes[mode]); var _self = this; var module; try { module = require(mode); } catch (e) {}; if (module) return done(module); // set mode to text until loading is finished if (!this.$mode) this.$setModePlaceholder(); fetch(function() { require([mode], done); }); function done(module) { if (_self.$modes[mode]) return callback(_self.$modes[mode]); _self.$modes[mode] = new module.Mode(); _self.$modes[mode].$id = mode; _self._emit("loadmode", { name: mode, mode: _self.$modes[mode] }); callback(_self.$modes[mode]); } function fetch(callback) { if (!config.get("packaged")) return callback(); var base = mode.split("/").pop(); var filename = config.get("modePath") + "/mode-" + base + ".js"; net.loadScript(filename, callback); } }; this.$setModePlaceholder = function() { this.$mode = this.$modes["null"]; var tokenizer = this.$mode.getTokenizer(); if (!this.bgTokenizer) { this.bgTokenizer = new BackgroundTokenizer(tokenizer); var _self = this; this.bgTokenizer.addEventListener("update", function(e) { _self._emit("tokenizerUpdate", e); }); } else { this.bgTokenizer.setTokenizer(tokenizer); } this.bgTokenizer.setDocument(this.getDocument()); this.tokenRe = this.$mode.tokenRe; this.nonTokenRe = this.$mode.nonTokenRe; }; this.$mode = null; this.$modeId = null; this.setMode = function(mode) { mode = mode || "null"; // load on demand if (typeof mode === "string") { if (this.$modeId == mode) return; this.$modeId = mode; var _self = this; this._loadMode(mode, function(module) { if (_self.$modeId !== mode) return; _self.setMode(module); }); return; } if (this.$mode === mode) return; this.$mode = mode; this.$modeId = mode.$id; 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._emit("tokenizerUpdate", e); }); } else { this.bgTokenizer.setTokenizer(tokenizer); } this.bgTokenizer.setDocument(this.getDocument()); this.bgTokenizer.start(0); this.tokenRe = mode.tokenRe; this.nonTokenRe = mode.nonTokenRe; this.$setFolding(mode.foldingRules); this._emit("changeMode"); }; this.$stopWorker = function() { if (this.$worker) this.$worker.terminate(); this.$worker = null; }; this.$startWorker = function() { if (typeof Worker !== "undefined" && !require.noWorker) { try { this.$worker = this.$mode.createWorker(this); } catch (e) { console.log("Could not load worker"); console.log(e); this.$worker = null; } } else this.$worker = null; }; this.getMode = function() { return this.$mode; }; this.$scrollTop = 0; this.setScrollTop = function(scrollTop) { scrollTop = Math.round(Math.max(0, scrollTop)); if (this.$scrollTop === scrollTop) return; this.$scrollTop = scrollTop; this._emit("changeScrollTop", scrollTop); }; this.getScrollTop = function() { return this.$scrollTop; }; this.$scrollLeft = 0; this.setScrollLeft = function(scrollLeft) { scrollLeft = Math.round(Math.max(0, scrollLeft)); if (this.$scrollLeft === scrollLeft) return; this.$scrollLeft = scrollLeft; this._emit("changeScrollLeft", scrollLeft); }; this.getScrollLeft = function() { return this.$scrollLeft; }; this.getScreenWidth = function() { this.$computeWidth(); return this.screenWidth; }; 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.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) { var insert = delta.action == "insertText" || delta.action == "insertLines"; return isUndo ? !insert : insert; } var delta = deltas[0]; var range, point; var lastDeltaIsInsert = false; if (isInsert(delta)) { range = delta.range.clone(); lastDeltaIsInsert = true; } else { range = Range.fromPoints(delta.range.start, delta.range.start); lastDeltaIsInsert = false; } for (var i = 1; i < deltas.length; i++) { delta = deltas[i]; if (isInsert(delta)) { point = delta.range.start; if (range.compare(point.row, point.column) == -1) { range.setStart(delta.range.start); } point = delta.range.end; if (range.compare(point.row, point.column) == 1) { range.setEnd(delta.range.end); } lastDeltaIsInsert = true; } else { point = delta.range.start; if (range.compare(point.row, point.column) == -1) { range = Range.fromPoints(delta.range.start, delta.range.start); } lastDeltaIsInsert = false; } } // Check if this range and the last undo range has something in common. // If true, merge the ranges. if (lastUndoRange != null) { var cmp = lastUndoRange.compareRange(range); if (cmp == 1) { range.setStart(lastUndoRange.start); } else if (cmp == -1) { range.setEnd(lastUndoRange.end); } } return range; }, /** related to: Document.replace * EditSession.replace(range, text) -> Object * - range (Range): A specified Range to replace * - text (String): The new text to use as a replacement * + (Object): Returns an object containing the final row and column, like this:<br/> * ```{row: endRow, column: 0}```<br/> * If the text and range are empty, this function returns an object containing the current `range.start` value.<br/> * If the text is the exact same as what currently exists, this function returns an object containing the current `range.end` value. * * Replaces a range in the document with the new `text`. * * * **/ this.replace = function(range, text) { return this.doc.replace(range, text); }; this.moveText = function(fromRange, toPosition) { var text = this.getTextRange(fromRange); this.remove(fromRange); var toRow = toPosition.row; var toColumn = toPosition.column; // Make sure to update the insert location, when text is removed in // front of the chosen point of insertion. if (!fromRange.isMultiLine() && fromRange.start.row == toRow && fromRange.end.column < toColumn) toColumn -= text.length; if (fromRange.isMultiLine() && fromRange.end.row < toRow) { var lines = this.doc.$split(text); toRow -= lines.length - 1; } var endRow = toRow + fromRange.end.row - fromRange.start.row; var endColumn = fromRange.isMultiLine() ? fromRange.end.column : toColumn + fromRange.end.column - fromRange.start.column; var toRange = new Range(toRow, toColumn, endRow, endColumn); this.insert(toRange.start, text); return toRange; }; this.indentRows = function(startRow, endRow, indentString) { indentString = indentString.replace(/\t/g, this.getTabString()); for (var row=startRow; row<=endRow; row++) this.insert({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.moveLinesUp = function(firstRow, lastRow) { if (firstRow <= 0) return 0; var removed = this.doc.removeLines(firstRow, lastRow); this.doc.insertLines(firstRow - 1, removed); return -1; }; this.moveLinesDown = function(firstRow, lastRow) { if (lastRow >= this.doc.getLength()-1) return 0; var removed = this.doc.removeLines(firstRow, lastRow); this.doc.insertLines(firstRow+1, removed); return 1; }; this.duplicateLines = function(firstRow, lastRow) { var firstRow = this.$clipRowToDocument(firstRow); var lastRow = this.$clipRowToDocument(lastRow); var lines = this.getLines(firstRow, lastRow); this.doc.insertLines(firstRow, lines); var addedRows = lastRow - firstRow + 1; return addedRows; }; 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; }; // WRAPMODE 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 wrapMode is activaed, the wrapData array has to be initialized. if (useWrapMode) { var len = this.getLength(); this.$wrapData = []; for (var i = 0; i < len; i++) { this.$wrapData.push([]); } this.$updateWrapData(0, len - 1); } this._emit("changeWrapMode"); } }; this.getUseWrapMode = function() { return this.$useWrapMode; }; // Allow the wrap limit to move freely between min and max. Either // parameter can be null to allow the wrap limit to be unconstrained // in that direction. Or set both parameters to the same number to pin // the limit to that value. /** * EditSession.setWrapLimitRange(min, max) * - min (Number): The minimum wrap value (the left side wrap) * - max (Number): The maximum wrap value (the right side wrap) * * Sets the boundaries of wrap. Either value can be `null` to have an unconstrained wrap, or, they can be the same number to pin the limit. If the wrap limits for `min` or `max` are different, this method also emits the `'changeWrapMode'` event. **/ this.setWrapLimitRange = function(min, max) { if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) { this.$wrapLimitRange.min = min; this.$wrapLimitRange.max = max; this.$modified = true; // This will force a recalculation of the wrap limit this._emit("changeWrapMode"); } }; this.adjustWrapLimit = function(desiredLimit) { var wrapLimit = this.$constrainWrapLimit(desiredLimit); if (wrapLimit != this.$wrapLimit && wrapLimit > 0) { this.$wrapLimit = wrapLimit; this.$modified = true; if (this.$useWrapMode) { this.$updateWrapData(0, this.getLength() - 1); this.$resetRowCache(0) this._emit("changeWrapLimit"); } return true; } return false; }; this.$constrainWrapLimit = function(wrapLimit) { var min = this.$wrapLimitRange.min; if (min) wrapLimit = Math.max(min, wrapLimit); var max = this.$wrapLimitRange.max; if (max) wrapLimit = Math.min(max, wrapLimit); // What would a limit of 0 even mean? return Math.max(1, wrapLimit); }; this.getWrapLimit = function() { return this.$wrapLimit; }; this.getWrapLimitRange = function() { // Avoid unexpected mutation by returning a copy return { min : this.$wrapLimitRange.min, max : this.$wrapLimitRange.max }; }; this.$updateInternalDataOnChange = function(e) { var useWrapMode = this.$useWrapMode; var len; var action = e.data.action; var firstRow = e.data.range.start.row; var lastRow = e.data.range.end.row; var start = e.data.range.start; var end = e.data.range.end; var removedFolds = null; if (action.indexOf("Lines") != -1) { if (action == "insertLines") { lastRow = firstRow + (e.data.lines.length); } else { lastRow = firstRow; } len = e.data.lines ? e.data.lines.length : lastRow - firstRow; } else { len = lastRow - firstRow; } if (len != 0) { if (action.indexOf("remove") != -1) { this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len); var foldLines = this.$foldData; removedFolds = this.getFoldsInRange(e.data.range); 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; if (useWrapMode) { args = [firstRow, 0]; for (var i = 0; i < len; i++) args.push([]); this.$wrapData.splice.apply(this.$wrapData, args); } else { args = Array(len); args.unshift(firstRow, 0); this.$rowLengthCache.splice.apply(this.$rowLengthCache, args); } // If some new line is added inside of a foldLine, then split // the fold line up. var foldLines = this.$foldData; var foldLine = this.getFoldLine(firstRow); var idx = 0; if (foldLine) { var cmp = foldLine.range.compareInside(start.row, start.column) // Inside of the foldLine range. Need to split stuff up. if (cmp == 0) { foldLine = foldLine.split(start.row, start.column); foldLine.shiftRow(len); foldLine.addRemoveChars( lastRow, 0, end.column - start.column); } else // Infront of the foldLine but same row. Need to shift column. if (cmp == -1) { foldLine.addRemoveChars(firstRow, 0, end.column - start.column); foldLine.shiftRow(len); } // Nothing to do if the insert is after the foldLine. idx = foldLines.indexOf(foldLine) + 1; } for (idx; idx < foldLines.length; idx++) { var foldLine = foldLines[idx]; if (foldLine.start.row >= firstRow) { foldLine.shiftRow(len); } } } } else { // Realign folds. E.g. if you add some new chars before a fold, the // fold should "move" to the right. len = Math.abs(e.data.range.start.column - e.data.range.end.column); if (action.indexOf("remove") != -1) { // Get all the folds in the change range and remove them. removedFolds = this.getFoldsInRange(e.data.range); 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!"); } if (useWrapMode) this.$updateWrapData(firstRow, lastRow); else this.$updateRowLengthCache(firstRow, lastRow); return removedFolds; }; this.$updateRowLengthCache = function(firstRow, lastRow, b) { //console.log(firstRow, lastRow, b) this.$rowLengthCache[firstRow] = null; this.$rowLengthCache[lastRow] = null; //console.log(this.$rowLengthCache) }; 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(lang.stringTrimRight(lines[row])); wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); row ++; } else { tokens = []; foldLine.walk( function(placeholder, row, column, lastColumn) { var walkTokens; if (placeholder) { 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 ); // Remove spaces/tabs from the back of the token array. while (tokens.length != 0 && tokens[tokens.length - 1] >= SPACE) tokens.pop(); wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); row = foldLine.end.row + 1; } } }; // "Tokens" 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) { if (tokens.length == 0) { return []; } var splits = []; var displayLength = tokens.length; var lastSplit = 0, lastDocSplit = 0; function addSplit(screenPos) { var displayed = tokens.slice(lastSplit, screenPos); // The document size is the current size - the extra width for tabs // and multipleWidth characters. var len = displayed.length; displayed.join(""). // Get all the TAB_SPACEs. replace(/12/g, function() { len -= 1; }). // Get all the CHAR_EXT/multipleWidth characters. replace(/2/g, function() { len -= 1; }); lastDocSplit += len; splits.push(lastDocSplit); lastSplit = screenPos; } while (displayLength - lastSplit > wrapLimit) { // This is, where the split should be. var split = lastSplit + wrapLimit; // If there is a space or tab at this split position, then making // a split is simple. if (tokens[split] >= SPACE) { // Include all following spaces + tabs in this split as well. while (tokens[split] >= SPACE) { split ++; } addSplit(split); continue; } // === ELSE === // Check if split is inside of a placeholder. Placeholder are // not splitable. Therefore, seek the beginning of the placeholder // and try to place the split beofre the placeholder's start. if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) { // Seek the start of the placeholder and do the split // before the placeholder. By definition there always // a PLACEHOLDER_START between split and lastSplit. for (split; split != lastSplit - 1; split--) { if (tokens[split] == PLACEHOLDER_START) { // split++; << No incremental here as we want to // have the position before the Placeholder. break; } } // If the PLACEHOLDER_START is not the index of the // last split, then we can do the split if (split > lastSplit) { addSplit(split); continue; } // If the PLACEHOLDER_START IS the index of the last // split, then we have to place the split after the // placeholder. So, let's seek for the end of the placeholder. split = lastSplit + wrapLimit; for (split; split < tokens.length; split++) { if (tokens[split] != PLACEHOLDER_BODY) { break; } } // If spilt == tokens.length, then the placeholder is the last // thing in the line and adding a new split doesn't make sense. if (split == tokens.length) { break; // Breaks the while-loop. } // Finally, add the split... addSplit(split); continue; } // === ELSE === // Search for the first non space/tab/placeholder/punctuation token backwards. var minSplit = Math.max(split - 10, lastSplit - 1); while (split > minSplit && tokens[split] < PLACEHOLDER_START) { split --; } while (split > minSplit && tokens[split] == PUNCTUATION) { split --; } // If we found one, then add the split. if (split > minSplit) { addSplit(++split); continue; } // === ELSE === split = lastSplit + wrapLimit; // The split is inside of a CHAR or CHAR_EXT token and no space // around -> force a split. addSplit(split); } return splits; } /** internal, hide * EditSession.$getDisplayTokens(str, offset) -> Array * - str (String): The string to check * - offset (Number): The value to start at * * Given a string, returns an array of the display characters, including tabs and spaces. **/ 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); // Tab if (c == 9) { tabSize = this.getScreenTabSize(arr.length + offset); arr.push(TAB); for (var n = 1; n < tabSize; n++) { arr.push(TAB_SPACE); } } // Space else if (c == 32) { arr.push(SPACE); } else if((c > 39 && c < 48) || (c > 57 && c < 64)) { arr.push(PUNCTUATION); } // full width characters else if (c >= 0x1100 && isFullWidth(c)) { arr.push(CHAR, CHAR_EXT); } else { arr.push(CHAR); } } return arr; } /** internal, hide * EditSession.$getStringScreenWidth(str, maxScreenColumn, screenColumn) -> [Number] * - str (String): The string to calculate the screen width of * - maxScreenColumn (Number): * - screenColumn (Number): * + ([Number]): Returns an `int[]` array with two elements:<br/> * The first position indicates the number of columns for `str` on screen.<br/> * The second value contains the position of the document column that this function read until. * * Calculates the width of the string `str` on the screen while assuming that the string starts at the first column on the screen. * * **/ 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); // tab if (c == 9) { screenColumn += this.getScreenTabSize(screenColumn); } // full width characters else if (c >= 0x1100 && isFullWidth(c)) { screenColumn += 2; } else { screenColumn += 1; } if (screenColumn > maxScreenColumn) { break } } return [screenColumn, column]; } /** * EditSession.getRowLength(row) -> Number * - row (Number): The row number to check * * * Returns the length of the indicated row. **/ this.getRowLength = function(row) { if (!this.$useWrapMode || !this.$wrapData[row]) { return 1; } else { return this.$wrapData[row].length + 1; } } /** * EditSession.getRowHeight(config, row) -> Number * - config (Object): An object containing a parameter indicating the `lineHeight`. * - row (Number): The row number to check * * Returns the height of the indicated row. This is mostly relevant for situations where wrapping occurs, and a single line spans across multiple rows. * **/ this.getRowHeight = function(config, row) { return this.getRowLength(row) * config.lineHeight; } /** internal, hide, related to: EditSession.documentToScreenColumn * EditSession.getScreenLastRowColumn(screenRow) -> Number * - screenRow (Number): The screen row to check * * Returns the column position (on screen) for the last character in the provided row. **/ 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 row1 = rowCache[i]; var docRow1 = this.$docRowCache[i]; if (0 < i && i < rowCache.length) { var row = rowCache[i]; var docRow = this.$docRowCache[i]; var doCache = screenRow > row || (screenRow == row && i == rowCache.length - 1); } else { var doCache = true; } 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 - 1 >= 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) { // clip at the end of the document return { row: maxRow, column: this.getLine(maxRow).length } } else { line = this.getLine(docRow); foldLine = null; } if (this.$useWrapMode) { var splits = this.$wrapData[docRow]; if (splits) { column = splits[screenRow - row]; if(screenRow > row && splits.length) { docColumn = splits[screenRow - row - 1] || splits[splits.length - 1]; line = line.substring(docColumn); } } } docColumn += this.$getStringScreenWidth(line, screenColumn)[1]; // We remove one character at the end so that the docColumn // position returned is not associated to the next row on the screen. if (this.$useWrapMode && docColumn >= column) docColumn = column - 1; if (foldLine) return foldLine.idxToPosition(docColumn); return {row: docRow, column: docColumn}; }; this.documentToScreenPosition = function(docRow, docColumn) { // Normalize the passed in arguments. 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; // Clamp the docRow position in case it's inside of a folded block. 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); if (0 < i && i < rowCache.length) { var row = rowCache[i]; var screenRow = this.$screenRowCache[i]; var doCache = docRow > row || (docRow == row && i == rowCache.length - 1); } else { var doCache = true; } 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); } } // Calculate the text line that is displayed in docRow on the screen. var textLine = ""; // Check if the final row we want to reach is inside of a fold. if (foldLine && row >= foldStart) { textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn); foldStartRow = foldLine.start.row; } else { textLine = this.getLine(docRow).substring(0, docColumn); foldStartRow = docRow; } // Clamp textLine if in wrapMode. if (this.$useWrapMode) { var wrapRow = this.$wrapData[foldStartRow]; var screenRowOffset = 0; while (textLine.length >= wrapRow[screenRowOffset]) { screenRow ++; screenRowOffset++; } textLine = textLine.substring( wrapRow[screenRowOffset - 1] || 0, textLine.length ); } return { row: screenRow, column: 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(); // Remove the folded lines again. 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) { screenRows += this.$wrapData[row].length + 1; row ++; if (row > foldStart) { row = fold.end.row+1; fold = this.$foldData[i++]; foldStart = fold ?fold.start.row :Infinity; } } } return screenRows; } // For every keystroke this gets called once per char in the whole doc!! // Wouldn't hurt to make it a bit faster for c >= 0x1100 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); exports.EditSession = EditSession; }); define('ace/config', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { "no use strict"; var lang = require("./lib/lang"); var global = (function() { return this; })(); var options = { packaged: false, workerPath: "", modePath: "", themePath: "", suffix: ".js" }; exports.get = function(key) { if (!options.hasOwnProperty(key)) throw new Error("Unknown config key: " + key); return options[key]; }; exports.set = function(key, value) { if (!options.hasOwnProperty(key)) throw new Error("Unknown config key: " + key); options[key] = value; }; exports.all = function() { return lang.copyObject(options); }; exports.init = function() { options.packaged = require.packaged || module.packaged || (global.define && define.packaged); if (!global.document) return ""; var scriptOptions = {}; var scriptUrl = ""; var scripts = document.getElementsByTagName("script"); for (var i=0; i<scripts.length; i++) { var script = scripts[i]; var src = script.src || script.getAttribute("src"); if (!src) { continue; } var attributes = script.attributes; for (var j=0, l=attributes.length; j < l; j++) { var attr = attributes[j]; if (attr.name.indexOf("data-ace-") === 0) { scriptOptions[deHyphenate(attr.name.replace(/^data-ace-/, ""))] = attr.value; } } var m = src.match(/^(?:(.*\/)ace\.js)(?:\?|$)/); if (m) { scriptUrl = m[1] || m[2]; } } if (scriptUrl) { scriptOptions.base = scriptOptions.base || scriptUrl; scriptOptions.packaged = true; } scriptOptions.workerPath = scriptOptions.workerPath || scriptOptions.base; scriptOptions.modePath = scriptOptions.modePath || scriptOptions.base; scriptOptions.themePath = scriptOptions.themePath || scriptOptions.base; delete scriptOptions.base; for (var key in scriptOptions) if (typeof scriptOptions[key] !== "undefined") exports.set(key, scriptOptions[key]); }; function deHyphenate(str) { return str.replace(/-(.)/g, function(m, m1) { return m1.toUpperCase(); }); } }); define('ace/lib/net', ['require', 'exports', 'module' ], function(require, exports, module) { exports.get = function (url, callback) { var xhr = exports.createXhr(); xhr.open('GET', url, true); xhr.onreadystatechange = function (evt) { //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { callback(xhr.responseText); } }; xhr.send(null); }; var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0']; exports.createXhr = function() { //Would love to dump the ActiveX crap in here. Need IE 6 to die first. var xhr, i, progId; if (typeof XMLHttpRequest !== "undefined") { return new XMLHttpRequest(); } else { for (i = 0; i < 3; i++) { progId = progIds[i]; try { xhr = new ActiveXObject(progId); } catch (e) {} if (xhr) { progIds = [progId]; // so faster next time break; } } } if (!xhr) { throw new Error("createXhr(): XMLHttpRequest not available"); } return xhr; }; exports.loadScript = function(path, callback) { var head = document.getElementsByTagName('head')[0]; var s = document.createElement('script'); s.src = path; head.appendChild(s); s.onload = callback; }; }); define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) { var EventEmitter = {}; 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; e = e || {}; e.type = eventName; if (!e.stopPropagation) { e.stopPropagation = function() { this.propagationStopped = true; }; } if (!e.preventDefault) { e.preventDefault = function() { this.defaultPrevented = true; }; } for (var i=0; i<listeners.length; i++) { listeners[i](e); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e); }; EventEmitter.setDefaultHandler = function(eventName, callback) { this._defaultHandlers = this._defaultHandlers || {}; if (this._defaultHandlers[eventName]) throw new Error("The default handler for '" + eventName + "' is already set"); this._defaultHandlers[eventName] = callback; }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) var listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners.push(callback); }; EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); define('ace/selection', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/lib/event_emitter', 'ace/range'], function(require, exports, module) { var oop = require("./lib/oop"); var lang = require("./lib/lang"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; /** * new Selection(session) * - session (EditSession): The session to use * * Creates a new `Selection` object. * **/ 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); } 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.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) 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) { // cursor is a line (start 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); // Determ the doc-position of the first character at the screen line. var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0); // Determ the line var beforeCursor = this.session.getDisplayLine( row, null, firstColumnPosition.row, firstColumnPosition.column ); var leadingSpace = beforeCursor.match(/^\s*/); if (leadingSpace[0].length == column) { this.moveCursorTo( firstColumnPosition.row, firstColumnPosition.column ); } else { this.moveCursorTo( firstColumnPosition.row, firstColumnPosition.column + leadingSpace[0].length ); } }; this.moveCursorLineEnd = function() { var lead = this.lead; var lastRowColumnPosition = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column); this.moveCursorTo( lastRowColumnPosition.row, lastRowColumnPosition.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; // skip folds var fold = this.session.getFoldAt(row, column, 1); if (fold) { this.moveCursorTo(fold.end.row, fold.end.column); return; } // first skip space if (match = this.session.nonTokenRe.exec(rightOfCursor)) { column += this.session.nonTokenRe.lastIndex; this.session.nonTokenRe.lastIndex = 0; rightOfCursor = line.substring(column); } // if at line end proceed with next line if (column >= line.length) { this.moveCursorTo(row, line.length); this.moveCursorRight(); if (row < this.doc.getLength() - 1) this.moveCursorWordRight(); return; } // advance to the end of the next token 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; // skip folds 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; // skip whitespace 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 at begin of the line proceed in line above if (column <= 0) { this.moveCursorTo(row, 0); this.moveCursorLeft(); if (row > 0) this.moveCursorWordLeft(); return; } // move to the begin of the word 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); // move the cursor and update the desired column 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) { // Ensure the row/column is not inside of a fold. 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); }; // remove listeners from document 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; } }).call(Selection.prototype); exports.Selection = Selection; }); define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class Range * * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. * **/ /** * new Range(startRow, startColumn, endRow, endColumn) * - startRow (Number): The starting row * - startColumn (Number): The starting column * - endRow (Number): The ending row * - endColumn (Number): The ending column * * Creates a new `Range` object with the given starting and ending row and column points. * **/ var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { /** * Range.isEqual(range) -> Boolean * - range (Range): A range to check against * * Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`. * **/ 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; } } } /** related to: Range.compare * Range.comparePoint(p) -> Number * - p (Range): A point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1<br/> * * Checks the row and column points of `p` with the row and column points of the calling range. * * * **/ this.comparePoint = function(p) { return this.compare(p.row, p.column); } /** related to: Range.comparePoint * Range.containsRange(range) -> Boolean * - range (Range): A range to compare with * * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. * **/ this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } /** * Range.intersects(range) -> Boolean * - range (Range): A range to compare with * * Returns `true` if passed in `range` intersects with the one calling this method. * **/ this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); } /** * Range.isEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. * **/ this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } /** * Range.isStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. * **/ this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; } /** * Range.setStart(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** * Range.setEnd(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** related to: Range.compare * Range.inside(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range. * **/ 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; } /** related to: Range.compare * Range.insideStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's starting points. * **/ this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; } /** related to: Range.compare * Range.insideEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's ending points. * **/ this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; } /** * Range.compare(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal <br/> * * `-1` if `p.row` is less then the calling range <br/> * * `1` if `p.row` is greater than the calling range <br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> * <br/> * If the ending row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0` <br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ 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); } } /** * Range.compareEnd(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } } /** * Range.compareInside(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`<br/> * * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`<br/> * <br/> * Otherwise, it returns the value after calling [[Range.compare `compare()`]]. * * Checks the row and column points with the row and column points of the calling range. * * * **/ 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); } } /** * Range.clipRows(firstRow, lastRow) -> Range * - firstRow (Number): The starting row * - lastRow (Number): The ending row * * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. * **/ this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) { var end = { row: lastRow+1, column: 0 }; } if (this.start.row > lastRow) { var start = { row: lastRow+1, column: 0 }; } if (this.start.row < firstRow) { var start = { row: firstRow, column: 0 }; } if (this.end.row < firstRow) { var end = { 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 ); }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; exports.Range = Range; }); define('ace/mode/text', ['require', 'exports', 'module' , 'ace/tokenizer', 'ace/mode/text_highlight_rules', 'ace/mode/behaviour', 'ace/unicode'], function(require, exports, module) { var Tokenizer = require("../tokenizer").Tokenizer; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var Behaviour = require("./behaviour").Behaviour; var unicode = require("../unicode"); var Mode = function() { this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules()); 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() { return this.$tokenizer; }; this.toggleCommentLines = function(state, doc, startRow, endRow) { }; this.getNextLineIndent = function(state, line, tab) { return ""; }; this.checkOutdent = function(state, line, input) { return false; }; this.autoOutdent = function(state, doc, row) { }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; this.createWorker = function(session) { return null; }; this.createModeDelegates = function (mapping) { if (!this.$embeds) { return; } this.$modes = {}; for (var i = 0; i < this.$embeds.length; i++) { if (mapping[this.$embeds[i]]) { this.$modes[this.$embeds[i]] = new mapping[this.$embeds[i]](); } } var delegations = ['toggleCommentLines', 'getNextLineIndent', 'checkOutdent', 'autoOutdent', 'transformAction']; 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]; 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; } } } } } }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/tokenizer', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class Tokenizer * * This class takes a set of highlighting rules, and creates a tokenizer out of them. For more information, see [the wiki on extending highlighters](https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode#wiki-extendingTheHighlighter). * **/ /** * new Tokenizer(rules, flag) * - rules (Object): The highlighting rules * - flag (String): Any additional regular expression flags to pass (like "i" for case insensitive) * * Constructs a new tokenizer based on the given rules and flags. * **/ var Tokenizer = function(rules, flag) { flag = flag ? "g" + flag : "g"; this.rules = rules; this.regExps = {}; this.matchMappings = {}; for ( var key in this.rules) { var rule = this.rules[key]; var state = rule; var ruleRegExps = []; var matchTotal = 0; var mapping = this.matchMappings[key] = {}; for ( var i = 0; i < state.length; i++) { if (state[i].regex instanceof RegExp) state[i].regex = state[i].regex.toString().slice(1, -1); // Count number of matching groups. 2 extra groups from the full match // And the catch-all on the end (used to force a match); var matchcount = new RegExp("(?:(" + state[i].regex + ")|(.))").exec("a").length - 2; // Replace any backreferences and offset appropriately. var adjustedregex = state[i].regex.replace(/\\([0-9]+)/g, function (match, digit) { return "\\" + (parseInt(digit, 10) + matchTotal + 1); }); if (matchcount > 1 && state[i].token.length !== matchcount-1) throw new Error("Matching groups and length of the token array don't match in rule #" + i + " of state " + key); mapping[matchTotal] = { rule: i, len: matchcount }; matchTotal += matchcount; ruleRegExps.push(adjustedregex); } this.regExps[key] = new RegExp("(?:(" + ruleRegExps.join(")|(") + ")|(.))", flag); } }; (function() { /** * Tokenizer.getLineTokens() -> Object * * Returns an object containing two properties: `tokens`, which contains all the tokens; and `state`, the current state. **/ this.getLineTokens = function(line, startState) { var currentState = startState || "start"; var state = this.rules[currentState]; var mapping = this.matchMappings[currentState]; var re = this.regExps[currentState]; re.lastIndex = 0; var match, tokens = []; var lastIndex = 0; var token = { type: null, value: "" }; while (match = re.exec(line)) { var type = "text"; var rule = null; var value = [match[0]]; for (var i = 0; i < match.length-2; i++) { if (match[i + 1] === undefined) continue; rule = state[mapping[i].rule]; if (mapping[i].len > 1) value = match.slice(i+2, i+1+mapping[i].len); // compute token type if (typeof rule.token == "function") type = rule.token.apply(this, value); else type = rule.token; if (rule.next) { currentState = rule.next; state = this.rules[currentState]; mapping = this.matchMappings[currentState]; lastIndex = re.lastIndex; re = this.regExps[currentState]; re.lastIndex = lastIndex; } break; } if (value[0]) { if (typeof type == "string") { value = [value.join("")]; type = [type]; } for (var i = 0; i < value.length; i++) { if (!value[i]) continue; if ((!rule || rule.merge || type[i] === "text") && token.type === type[i]) { token.value += value[i]; } else { if (token.type) tokens.push(token); token = { type: type[i], value: value[i] }; } } } if (lastIndex == line.length) break; lastIndex = re.lastIndex; } if (token.type) tokens.push(token); return { tokens : tokens, state : currentState }; }; }).call(Tokenizer.prototype); exports.Tokenizer = Tokenizer; }); define('ace/mode/text_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var TextHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { "start" : [{ token : "empty_line", regex : '^$' }, { token : "text", regex : ".+" }] }; }; (function() { this.addRules = function(rules, prefix) { 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.next = prefix + rule.next; } } this.$rules[prefix + key] = state; } }; this.getRules = function() { return this.$rules; }; this.embedRules = function (HighlightRules, prefix, escapeRules, states) { var embedRules = new HighlightRules().getRules(); 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); for (var i = 0; i < states.length; i++) { Array.prototype.unshift.apply(this.$rules[states[i]], lang.deepCopy(escapeRules)); } if (!this.$embeds) { this.$embeds = []; } this.$embeds.push(prefix); } this.getEmbeds = function() { return this.$embeds; } }).call(TextHighlightRules.prototype); exports.TextHighlightRules = TextHighlightRules; }); define('ace/mode/behaviour', ['require', 'exports', 'module' ], function(require, exports, module) { 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; }); define('ace/unicode', ['require', 'exports', 'module' ], function(require, exports, module) { /* XRegExp Unicode plugin pack: Categories 1.0 (c) 2010 Steven Levithan MIT License <http://xregexp.com> Uses the Unicode 5.2 character database This package for the XRegExp Unicode plugin enables the following Unicode categories (aka properties): L - Letter (the top-level Letter category is included in the Unicode plugin base script) Ll - Lowercase letter Lu - Uppercase letter Lt - Titlecase letter Lm - Modifier letter Lo - Letter without case M - Mark Mn - Non-spacing mark Mc - Spacing combining mark Me - Enclosing mark N - Number Nd - Decimal digit Nl - Letter number No - Other number P - Punctuation Pd - Dash punctuation Ps - Open punctuation Pe - Close punctuation Pi - Initial punctuation Pf - Final punctuation Pc - Connector punctuation Po - Other punctuation S - Symbol Sm - Math symbol Sc - Currency symbol Sk - Modifier symbol So - Other symbol Z - Separator Zs - Space separator Zl - Line separator Zp - Paragraph separator C - Other Cc - Control Cf - Format Co - Private use Cs - Surrogate Cn - Unassigned Example usage: \p{N} \p{Cn} */ // will be populated by addUnicodePackage 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$&"); }; }); define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; /** * new Document([text]) * - text (String | Array): The starting text * * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * **/ var Document = function(text) { this.$lines = []; // There has to be one line at least in the document. If you pass an empty // string to the insert function, nothing will happen. Workaround. if (text.length == 0) { this.$lines = [""]; } else if (Array.isArray(text)) { this.insertLines(0, text); } else { this.insert({row: 0, column:0}, text); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength(); this.remove(new Range(0, 0, len, this.getLine(len-1).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); }; // check for IE split bug 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); if (match) { this.$autoNewLine = match[1]; } else { this.$autoNewLine = "\n"; } }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; case "auto": return this.$autoNewLine; } }; this.$autoNewLine = "\n"; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; }; 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) { if (range.start.row == range.end.row) { return this.$lines[range.start.row].substring(range.start.column, range.end.column); } else { var lines = this.getLines(range.start.row+1, range.end.row-1); lines.unshift((this.$lines[range.start.row] || "").substring(range.start.column)); lines.push((this.$lines[range.end.row] || "").substring(0, range.end.column)); return lines.join(this.getNewLineCharacter()); } }; 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; } return position; }; this.insert = function(position, text) { if (!text || text.length === 0) return position; position = this.$clipPosition(position); // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); var lines = this.$split(text); var firstLine = lines.splice(0, 1)[0]; var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0]; position = this.insertInLine(position, firstLine); if (lastLine !== null) { position = this.insertNewLine(position); // terminate first line position = this.insertLines(position.row, lines); position = this.insertInLine(position, lastLine || ""); } return position; }; this.insertLines = function(row, lines) { if (lines.length == 0) return {row: row, column: 0}; // apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF) // to circumvent that we have to break huge inserts into smaller chunks here if (lines.length > 0xFFFF) { var end = this.insertLines(row, lines.slice(0xFFFF)); lines = lines.slice(0, 0xFFFF); } var args = [row, 0]; args.push.apply(args, lines); this.$lines.splice.apply(this.$lines, args); var range = new Range(row, 0, row + lines.length, 0); var delta = { action: "insertLines", range: range, lines: lines }; this._emit("change", { data: delta }); return end || range.end; }; this.insertNewLine = function(position) { position = this.$clipPosition(position); var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column); this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length)); var end = { row : position.row + 1, column : 0 }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); return end; }; this.insertInLine = function(position, text) { if (text.length == 0) return position; var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column) + text + line.substring(position.column); var end = { row : position.row, column : position.column + text.length }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: text }; this._emit("change", { data: delta }); return end; }; this.remove = function(range) { // clip to document range.start = this.$clipPosition(range.start); range.end = this.$clipPosition(range.end); if (range.isEmpty()) return range.start; var firstRow = range.start.row; var lastRow = range.end.row; if (range.isMultiLine()) { var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1; var lastFullRow = lastRow - 1; if (range.end.column > 0) this.removeInLine(lastRow, 0, range.end.column); if (lastFullRow >= firstFullRow) this.removeLines(firstFullRow, lastFullRow); if (firstFullRow != firstRow) { this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length); this.removeNewLine(range.start.row); } } else { this.removeInLine(firstRow, range.start.column, range.end.column); } return range.start; }; this.removeInLine = function(row, startColumn, endColumn) { if (startColumn == endColumn) return; var range = new Range(row, startColumn, row, endColumn); var line = this.getLine(row); var removed = line.substring(startColumn, endColumn); var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length); this.$lines.splice(row, 1, newLine); var delta = { action: "removeText", range: range, text: removed }; this._emit("change", { data: delta }); return range.start; }; this.removeLines = function(firstRow, lastRow) { var range = new Range(firstRow, 0, lastRow + 1, 0); var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1); var delta = { action: "removeLines", range: range, nl: this.getNewLineCharacter(), lines: removed }; this._emit("change", { data: delta }); return removed; }; this.removeNewLine = function(row) { var firstLine = this.getLine(row); var secondLine = this.getLine(row+1); var range = new Range(row, firstLine.length, row+1, 0); var line = firstLine + secondLine; this.$lines.splice(row, 2, line); var delta = { action: "removeText", range: range, text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); }; this.replace = function(range, text) { if (text.length == 0 && range.isEmpty()) return range.start; // Shortcut: If the text we want to insert is the same as it is already // in the document, we don't have to replace anything. if (text == this.getTextRange(range)) return range.end; this.remove(range); if (text) { var end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "insertText") this.insert(range.start, delta.text); else if (delta.action == "removeLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "removeText") this.remove(range); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "insertText") this.remove(range); else if (delta.action == "removeLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "removeText") this.insert(range.start, delta.text); } }; }).call(Document.prototype); exports.Document = Document; }); define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; /** * new Anchor(doc, row, column) * - doc (Document): The document to associate with the anchor * - row (Number): The starting row position * - column (Number): The starting column position * * Creates a new `Anchor` and associates it with a document. * **/ var Anchor = exports.Anchor = function(doc, row, column) { this.document = doc; if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); this.$onChange = this.onChange.bind(this); doc.on("change", this.$onChange); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.onChange = function(e) { var delta = e.data; var range = delta.range; if (range.start.row == range.end.row && range.start.row != this.row) return; if (range.start.row > this.row) return; if (range.start.row == this.row && range.start.column > this.column) return; var row = this.row; var column = this.column; if (delta.action === "insertText") { if (range.start.row === row && range.start.column <= column) { if (range.start.row === range.end.row) { column += range.end.column - range.start.column; } else { column -= range.start.column; row += range.end.row - range.start.row; } } else if (range.start.row !== range.end.row && range.start.row < row) { row += range.end.row - range.start.row; } } else if (delta.action === "insertLines") { if (range.start.row <= row) { row += range.end.row - range.start.row; } } else if (delta.action == "removeText") { if (range.start.row == row && range.start.column < column) { if (range.end.column >= column) column = range.start.column; else column = Math.max(0, column - (range.end.column - range.start.column)); } else if (range.start.row !== range.end.row && range.start.row < row) { if (range.end.row == row) { column = Math.max(0, column - range.end.column) + range.start.column; } row -= (range.end.row - range.start.row); } else if (range.end.row == row) { row -= range.end.row - range.start.row; column = Math.max(0, column - range.end.column) + range.start.column; } } else if (delta.action == "removeLines") { if (range.start.row <= row) { if (range.end.row <= row) row -= range.end.row - range.start.row; else { row = range.start.row; column = 0; } } } this.setPosition(row, column, true); }; 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._emit("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("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); }); define('ace/background_tokenizer', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; // tokenizing lines longer than this makes editor very slow var MAX_LINE_LENGTH = 5000; /** * new BackgroundTokenizer(tokenizer, editor) * - tokenizer (Tokenizer): The tokenizer to use * - editor (Editor): The editor to associate with * * Creates a new `BackgroundTokenizer` object. * * **/ 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 startLine = self.currentLine; var doc = self.doc; var processedLines = 0; var len = doc.getLength(); while (self.currentLine < len) { self.$tokenizeRow(self.currentLine); while (self.lines[self.currentLine]) self.currentLine++; // only check every 5 lines processedLines ++; if ((processedLines % 5 == 0) && (new Date() - workerStart) > 20) { self.fireUpdateEvent(startLine, self.currentLine-1); self.running = setTimeout(self.$worker, 20); return; } } self.running = false; self.fireUpdateEvent(startLine, len - 1); }; }; (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._emit("update", {data: data}); }; this.start = function(startRow) { this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength()); // remove all cached items below this line this.lines.splice(this.currentLine, this.lines.length); this.states.splice(this.currentLine, this.states.length); this.stop(); // pretty long delay to prevent the tokenizer from interfering with the user this.running = setTimeout(this.$worker, 700); }; this.$updateOnChange = function(delta) { var range = delta.range; var startRow = range.start.row; var len = range.end.row - startRow; if (len === 0) { this.lines[startRow] = null; } else if (delta.action == "removeText" || delta.action == "removeLines") { 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(); // pretty long delay to prevent the tokenizer from interfering with the user this.running = setTimeout(this.$worker, 700); }; 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]; if (line.length > MAX_LINE_LENGTH) { var overflow = {value: line.substr(MAX_LINE_LENGTH), type: "text"}; line = line.slice(0, MAX_LINE_LENGTH); } var data = this.tokenizer.getLineTokens(line, state); if (overflow) { data.tokens.push(overflow); data.state = "start"; } 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; }); define('ace/search_highlight', ['require', 'exports', 'module' , 'ace/lib/lang', 'ace/lib/oop', 'ace/range'], function(require, exports, module) { 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.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); 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, null, this.type ); } } }; }).call(SearchHighlight.prototype); exports.SearchHighlight = SearchHighlight; }); 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) { var Range = require("../range").Range; var FoldLine = require("./fold_line").FoldLine; var Fold = require("./fold").Fold; var TokenIterator = require("../token_iterator").TokenIterator; function Folding() { /* * Looks up a fold at a given row/column. Possible values for side: * -1: ignore a fold if fold.start = row/column * +1: ignore a fold if fold.end = row/column */ 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) { range = range.clone(); 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) { // Range is before foldLine. No intersection. This means, // there might be other foldLines that intersect. continue; } else if (cmp == -2) { // Range is after foldLine. There can't be any other foldLines then, // so let's give up. 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 // WTF-state: Can happen due to -1/+1 to start/end column. if (cmp == 42) { break; } foundFolds.push(fold); } } return foundFolds; }; this.getAllFolds = function() { var folds = []; var foldLines = this.$foldData; function addFold(fold) { folds.push(fold); if (!fold.subFolds) return; for (var i = 0; i < fold.subFolds.length; i++) addFold(fold.subFolds[i]); } for (var i = 0; i < foldLines.length; i++) for (var j = 0; j < foldLines[i].folds.length; j++) addFold(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 } }; // TODO: Refactor to use getNextFoldTo function. 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; }; // returns the fold which starts after or contains docRow 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); this.$clipRangeToDocument(fold.range); var startRow = fold.start.row; var startColumn = fold.start.column; var endRow = fold.end.row; var endColumn = fold.end.column; // --- Some checking --- if (fold.placeholder.length < 2) throw "Placeholder has to be at least 2 characters"; if (startRow == endRow && endColumn - startColumn < 2) throw "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)) || (endFold && !endFold.range.isEnd(endRow, endColumn)) ) { throw "A fold can't intersect already existing fold" + fold.range + startFold.range; } // Check if there are folds in the range we create the new fold for. var folds = this.getFoldsInRange(fold.range); if (folds.length > 0) { // Remove the folds from fold data. this.removeFolds(folds); // Add the removed folds as subfolds on the new fold. fold.subFolds = folds; } 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) { // Check if we might have to merge two FoldLines. var foldLineNext = foldData[i + 1]; if (foldLineNext && foldLineNext.start.row == endRow) { // We need to merge! 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); // Notify that fold data has changed. this.$modified = true; this._emit("changeFold", { data: fold }); 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; // Simple case where there is only one fold in the FoldLine such that // the entire fold line can get removed directly. if (folds.length == 1) { foldLines.splice(foldLines.indexOf(foldLine), 1); } else // If the fold is the last fold of the foldLine, just remove it. 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 the fold is the first fold of the foldLine, just remove it. 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 // We know there are more then 2 folds and the fold is not at the edge. // This means, the fold is somewhere in between. // // If the fold is in one row, we just can remove it. if (fold.sameRow) { folds.splice(folds.indexOf(fold), 1); } else // The fold goes over more then one row. This means remvoing this fold // will cause the fold line to get splitted up. newFoldLine is the second part { 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.$useWrapMode) this.$updateWrapData(startRow, endRow); else this.$updateRowLengthCache(startRow, endRow); // Notify that fold data has changed. this.$modified = true; this._emit("changeFold", { data: fold }); }; this.removeFolds = function(folds) { // We need to clone the folds array passed in as it might be the folds // array of a fold line and as we call this.removeFold(fold), folds // are removed from folds and changes the current index. 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(fold) { this.addFold(fold); }, this); 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); 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.getFoldsInRange(range); if (expandInner) { this.removeFolds(folds); } else { // TODO: might need to remove and add folds in one go instead of using // expandFolds several times. while (folds.length) { this.expandFolds(folds); folds = this.getFoldsInRange(range); } } }; 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.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) { if (startRow == null) { startRow = foldLine.start.row; startColumn = 0; } if (endRow == null) { endRow = foldLine.end.row; endColumn = this.getLine(endRow).length; } // Build the textline using the FoldLine walker. var doc = this.doc; var textLine = ""; foldLine.walk(function(placeholder, row, column, lastColumn) { if (row < startRow) { return; } else if (row == startRow) { if (column < startColumn) { return; } lastColumn = Math.max(startColumn, lastColumn); } if (placeholder) { textLine += placeholder; } else { textLine += doc.getLine(row).substring(lastColumn, column); } }.bind(this), 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) { 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(/\..*/, "\\.")); 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); do { token = iterator.stepForward(); } while(token && re.test(token.type)); token = iterator.stepBackward(); range.end.row = iterator.getCurrentTokenRow(); range.end.column = iterator.getCurrentTokenColumn() + token.value.length; return range; } }; this.foldAll = function(startRow, endRow) { var foldWidgets = this.foldWidgets; endRow = endRow || this.getLength(); for (var row = startRow || 0; row < endRow; row++) { if (foldWidgets[row] == null) foldWidgets[row] = this.getFoldWidget(row); if (foldWidgets[row] != "start") continue; var range = this.getFoldWidgetRange(row); // sometimes range can be incompatible with existing fold // wouldn't it be better for addFold to return null istead of throwing? if (range && range.end.row < endRow) try { this.addFold("...", range); } 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(); // reset folding var mode = this.$foldMode; this.$setFolding(null); this.$setFolding(mode); }; // structured folding this.$setFolding = function(foldMode) { if (this.$foldMode == foldMode) return; this.$foldMode = foldMode; this.removeListener('change', this.$updateFoldWidgets); this._emit("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.on('change', this.$updateFoldWidgets); }; this.onFoldWidgetClick = function(row, e) { var type = this.getFoldWidget(row); var line = this.getLine(row); var onlySubfolds = e.shiftKey; var addSubfolds = onlySubfolds || e.ctrlKey || e.altKey || e.metaKey; var fold; if (type == "end") fold = this.getFoldAt(row, 0, -1); else fold = this.getFoldAt(row, line.length, 1); if (fold) { if (addSubfolds) this.removeFold(fold); else this.expandFold(fold); return; } var range = this.getFoldWidgetRange(row); if (range) { // sometimes singleline folds can be missed by the code above if (!range.isMultiLine()) { fold = this.getFoldAt(range.start.row, range.start.column, 1); if (fold && range.isEqual(fold.range)) { this.removeFold(fold); return; } } if (!onlySubfolds) this.addFold("...", range); if (addSubfolds) this.foldAll(range.start.row + 1, range.end.row); } else { if (addSubfolds) this.foldAll(row + 1, this.getLength()); e.target.className += " invalid" } }; this.updateFoldWidgets = function(e) { var delta = e.data; var range = delta.range; var firstRow = range.start.row; var len = range.end.row - firstRow; if (len === 0) { this.foldWidgets[firstRow] = null; } else if (delta.action == "removeText" || delta.action == "removeLines") { this.foldWidgets.splice(firstRow, len + 1, null); } else { var args = Array(len + 1); args.unshift(firstRow, 1); this.foldWidgets.splice.apply(this.foldWidgets, args); } }; } exports.Folding = Folding; }); define('ace/edit_session/fold_line', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { 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() { /* * Note: This doesn't update wrapData! */ 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 "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 "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, comp, 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]; comp = fold.range.compareStart(endRow, endColumn); // This fold is after the endRow/Column. if (comp == -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 the user requested to stop the walk or endRow/endColumn is // inside of this fold (comp == 0), then end here. if (stop || comp == 0) { return; } // Note the new lastEnd might not be on the same line. However, // it's the callback's job to recognize this. 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) { //throwing here breaks whole editor //@todo properly handle this 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 fold = this.getNextFoldTo(row, column).fold, folds = this.folds; var foldData = this.foldData; if (!fold) { return null; } var i = folds.indexOf(fold); var foldBefore = folds[i - 1]; this.end.row = foldBefore.end.row; this.end.column = foldBefore.end.column; // Remove the folds after row/column and create a new FoldLine // containing these removed folds. 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]); } // Remove the foldLineNext - no longer needed, as // it's merged now with foldLineNext. 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; var fold; 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; }); define('ace/edit_session/fold', ['require', 'exports', 'module' ], function(require, exports, module) { /* * Simple fold-data struct. **/ 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 = []; }; (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()); }); return fold; }; this.addSubFold = function(fold) { if (this.range.isEqual(fold)) return this; if (!this.range.containsRange(fold)) throw "A fold can't intersect already existing fold" + fold.range + this.range; var row = fold.range.start.row, column = fold.range.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) // cmp == -1 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 "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; } }).call(Fold.prototype); }); define('ace/token_iterator', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class TokenIterator * * This class provides an essay way to treat the document as a stream of tokens, and provides methods to iterate over these tokens. * **/ /** * new TokenIterator(session, initialRow, initialColumn) * - session (EditSession): The session to associate with * - initialRow (Number): The row to start the tokenizing at * - initialColumn (Number): The column to start the tokenizing at * * Creates a new token iterator object. The inital token index is set to the provided row and column coordinates. * **/ 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() { /** * TokenIterator.stepBackward() -> [String] * + (String): If the current point is not at the top of the file, this function returns `null`. Otherwise, it returns an array of the tokenized strings. * * Tokenizes all the items from the current point to the row prior in the document. **/ 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() { var rowCount = this.$session.getLength(); this.$tokenIndex += 1; while (this.$tokenIndex >= this.$rowTokens.length) { this.$row += 1; 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; // If a column was cached by EditSession.getTokenAt, then use it var column = rowTokens[tokenIndex].start; if (column !== undefined) return column; column = 0; while (tokenIndex > 0) { tokenIndex -= 1; column += rowTokens[tokenIndex].value.length; } return column; }; }).call(TokenIterator.prototype); exports.TokenIterator = TokenIterator; }); define('ace/edit_session/bracket_match', ['require', 'exports', 'module' , 'ace/token_iterator'], function(require, exports, module) { var TokenIterator = require("../token_iterator").TokenIterator; /** * new BracketMatch(position) * - platform (String): Identifier for the platform; must be either `'mac'` or `'win'` * - commands (Array): A list of commands * * TODO * * **/ function BracketMatch() { /** * new findMatchingBracket(position) * - position (Number): Identifier for the platform; must be either `'mac'` or `'win'` * - commands (Array): A list of commands * * TODO * * **/ this.findMatchingBracket = function(position) { if (position.column == 0) return null; var charBeforeCursor = 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.$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") + ")+" ); } // Start searching in token, just before the character at position.column 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; } // Scan backward through the document, looking for the next token // whose type matches typeRe 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, allowBlankLine) { 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") + ")+" ); } // Start searching in token, after the character at position.column 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; } // Scan forward through the document, looking for the next token // whose type matches typeRe do { token = iterator.stepForward(); if (allowBlankLine) { // if you've reached the doc end, or, you match a new content line if (token === null || token.type == "string") { return {row: iterator.getCurrentTokenRow() + (token === null ? 1 : -1), column: 0}; } } } while (token && !typeRe.test(token.type)); if (token == null) break; valueIndex = 0; } return null; }; } exports.BracketMatch = BracketMatch; }); define('ace/search', ['require', 'exports', 'module' , 'ace/lib/lang', 'ace/lib/oop', 'ace/range'], function(require, exports, module) { var lang = require("./lib/lang"); var oop = require("./lib/oop"); var Range = require("./range").Range; /** * new Search() * * Creates a new `Search` object. The following search options are avaliable: * * * needle: string or regular expression * * backwards: false * * wrap: false * * caseSensitive: false * * wholeWord: false * * range: Range or null for whole document * * regExp: false * * start: Range or position * * skipCurrent: false * **/ var Search = function() { this.$options = {}; }; (function() { /** * Search.set(options) -> Search * - options (Object): An object containing all the new search properties * * Sets the search options via the `options` parameter. * **/ 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 iterator = this.$matchIterator(session, this.$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); } else firstRange = range; return true; }); return firstRange; }; this.findAll = function(session) { var options = this.$options; if (!options.needle) return []; this.$assembleRegExp(options); if (options.range) { var range = options.range; var lines = session.getLines(range.start.row, range.end.row); } else var lines = session.doc.getAllLines(); var ranges = []; var re = options.re; if (options.$isMultiLine) { var len = re.length; var maxRow = lines.length - len; for (var row = re.offset || 0; row < maxRow; row++) { for (var j = 0; j < re.length; j++) if (lines[row + j].search(re[j]) == -1) break; var startIndex = lines[row + j].match(re[0])[0].length; var endIndex = line.match(re[len - 1])[0].length; ranges.push(new Range( row, startLine.length - startIndex, row + len - 1, endIndex )); } } 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 (options.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--; return ranges.slice(i, j + 1); } 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 self = this, callback, backwards = options.backwards; 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 (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; } } return { forEach: function(_callback) { callback = _callback; self.$lineIterator(session, options).forEach(matchIterator); } }; }; this.$assembleRegExp = function(options) { 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 ? "g" : "gi"; options.$isMultiLine = /[\n\r]/.test(needle); if (options.$isMultiLine) return options.re = this.$assembleMultilineRegExp(needle, modifier); try { var re = new RegExp(needle, modifier); } catch(e) { var 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 range = options.range; 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 firstColumn = range ? range.start.column : 0; var lastRow = range ? range.end.row : session.getLength() - 1; if (!backwards) { var forEach = 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; } } else { var forEach = 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; } } return {forEach: forEach}; }; }).call(Search.prototype); exports.Search = Search; }); define('ace/commands/command_manager', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/keyboard/hash_handler', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("../lib/oop"); var HashHandler = require("../keyboard/hash_handler").HashHandler; var EventEmitter = require("../lib/event_emitter").EventEmitter; /** * new CommandManager(platform, commands) * - platform (String): Identifier for the platform; must be either `'mac'` or `'win'` * - commands (Array): A list of commands * * TODO * * **/ var CommandManager = function(platform, commands) { this.platform = platform; this.commands = {}; this.commmandKeyBinding = {}; this.addCommands(commands); this.setDefaultHandler("exec", function(e) { return e.command.exec(e.editor, e.args || {}); }); }; oop.inherits(CommandManager, HashHandler); (function() { oop.implement(this, EventEmitter); this.exec = function(command, editor, args) { if (typeof command === 'string') command = this.commands[command]; if (!command) return false; if (editor && editor.$readOnly && !command.readOnly) return false; var retvalue = this._emit("exec", { editor: editor, command: command, args: args }); return retvalue === false ? false : true; }; this.toggleRecording = function() { if (this.$inReplay) return; 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(); 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; }); define('ace/keyboard/hash_handler', ['require', 'exports', 'module' , 'ace/lib/keys'], function(require, exports, module) { var keyUtil = require("../lib/keys"); function HashHandler(config, platform) { this.platform = platform; this.commands = {}; this.commmandKeyBinding = {}; this.addCommands(config); }; (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) { var name = (typeof command === 'string' ? command : command.name); command = this.commands[name]; delete this.commands[name]; // exhaustive search is brute force but since removeCommand is // not a performance critical operation this should be OK var ckb = this.commmandKeyBinding; for (var hashId in ckb) { for (var key in ckb[hashId]) { if (ckb[hashId][key] == command) delete ckb[hashId][key]; } } }; this.bindKey = function(key, command) { if(!key) return; if (typeof command == "function") { this.addCommand({exec: command, bindKey: key, name: key}); return; } var ckb = this.commmandKeyBinding; key.split("|").forEach(function(keyPart) { var binding = this.parseKeys(keyPart, command); var hashId = binding.hashId; (ckb[hashId] || (ckb[hashId] = {}))[binding.key] = command; }, this); }; this.addCommands = function(commands) { commands && Object.keys(commands).forEach(function(name) { var command = commands[name]; if (typeof command === "string") return this.bindKey(command, name); if (typeof command === "function") command = { exec: command }; 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) { var binding = command.bindKey; if (!binding) return; var key = typeof binding == "string" ? binding: binding[this.platform]; this.bindKey(key, command); }; this.parseKeys = function(keys) { var key; var hashId = 0; var parts = keys.toLowerCase().trim().split(/\s*\-\s*/); for (var i = 0, l = parts.length; i < l; i++) { if (keyUtil.KEY_MODS[parts[i]]) hashId = hashId | keyUtil.KEY_MODS[parts[i]]; else key = parts[i] || "-"; //when empty, the splitSafe removed a '-' } if (parts[0] == "text" && parts.length == 2) { hashId = -1; key = parts[1]; } return { key: key, hashId: hashId }; }; this.findKeyCommand = function findKeyCommand(hashId, keyString) { var ckbr = this.commmandKeyBinding; return ckbr[hashId] && ckbr[hashId][keyString.toLowerCase()]; }; this.handleKeyboard = function(data, hashId, keyString, keyCode) { return { command: this.findKeyCommand(hashId, keyString) }; }; }).call(HashHandler.prototype) exports.HashHandler = HashHandler; }); define('ace/commands/default_commands', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); function bindKey(win, mac) { return { win: win, mac: mac }; } exports.commands = [{ 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", "Alt-L"), exec: function(editor) { editor.session.toggleFold(false); }, readOnly: true }, { name: "unfold", bindKey: bindKey("Alt-Shift-L", "Alt-Shift-L"), exec: function(editor) { editor.session.toggleFold(true); }, readOnly: true }, { name: "foldall", bindKey: bindKey("Alt-0", "Alt-0"), exec: function(editor) { editor.session.foldAll(); }, readOnly: true }, { name: "unfoldall", bindKey: bindKey("Alt-Shift-0", "Alt-Shift-0"), exec: function(editor) { editor.session.unfold(); }, readOnly: true }, { name: "findnext", bindKey: bindKey("Ctrl-K", "Command-G"), exec: function(editor) { editor.findNext(); }, readOnly: true }, { name: "findprevious", bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"), exec: function(editor) { editor.findPrevious(); }, readOnly: true }, { name: "find", bindKey: bindKey("Ctrl-F", "Command-F"), exec: function(editor) { var needle = prompt("Find:", editor.getCopyText()); editor.find(needle); }, readOnly: true }, { name: "overwrite", bindKey: bindKey("Insert", "Insert"), exec: function(editor) { editor.toggleOverwrite(); }, readOnly: true }, { name: "selecttostart", bindKey: bindKey("Ctrl-Shift-Home|Alt-Shift-Up", "Command-Shift-Up"), exec: function(editor) { editor.getSelection().selectFileStart(); }, readOnly: true }, { name: "gotostart", bindKey: bindKey("Ctrl-Home|Ctrl-Up", "Command-Home|Command-Up"), exec: function(editor) { editor.navigateFileStart(); }, readOnly: true }, { name: "selectup", bindKey: bindKey("Shift-Up", "Shift-Up"), exec: function(editor) { editor.getSelection().selectUp(); }, multiSelectAction: "forEach", readOnly: true }, { name: "golineup", bindKey: bindKey("Up", "Up|Ctrl-P"), exec: function(editor, args) { editor.navigateUp(args.times); }, multiSelectAction: "forEach", readOnly: true }, { name: "selecttoend", bindKey: bindKey("Ctrl-Shift-End|Alt-Shift-Down", "Command-Shift-Down"), exec: function(editor) { editor.getSelection().selectFileEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotoend", bindKey: bindKey("Ctrl-End|Ctrl-Down", "Command-End|Command-Down"), exec: function(editor) { editor.navigateFileEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectdown", bindKey: bindKey("Shift-Down", "Shift-Down"), exec: function(editor) { editor.getSelection().selectDown(); }, multiSelectAction: "forEach", readOnly: true }, { name: "golinedown", bindKey: bindKey("Down", "Down|Ctrl-N"), exec: function(editor, args) { editor.navigateDown(args.times); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectwordleft", bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"), exec: function(editor) { editor.getSelection().selectWordLeft(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotowordleft", bindKey: bindKey("Ctrl-Left", "Option-Left"), exec: function(editor) { editor.navigateWordLeft(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selecttolinestart", bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left"), exec: function(editor) { editor.getSelection().selectLineStart(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotolinestart", bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"), exec: function(editor) { editor.navigateLineStart(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectleft", bindKey: bindKey("Shift-Left", "Shift-Left"), exec: function(editor) { editor.getSelection().selectLeft(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotoleft", bindKey: bindKey("Left", "Left|Ctrl-B"), exec: function(editor, args) { editor.navigateLeft(args.times); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectwordright", bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"), exec: function(editor) { editor.getSelection().selectWordRight(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotowordright", bindKey: bindKey("Ctrl-Right", "Option-Right"), exec: function(editor) { editor.navigateWordRight(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selecttolineend", bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right"), exec: function(editor) { editor.getSelection().selectLineEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotolineend", bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"), exec: function(editor) { editor.navigateLineEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectright", bindKey: bindKey("Shift-Right", "Shift-Right"), exec: function(editor) { editor.getSelection().selectRight(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotoright", bindKey: bindKey("Right", "Right|Ctrl-F"), exec: function(editor, args) { editor.navigateRight(args.times); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectpagedown", bindKey: bindKey("Shift-PageDown", "Shift-PageDown"), exec: function(editor) { editor.selectPageDown(); }, readOnly: true }, { name: "pagedown", bindKey: bindKey(null, "PageDown"), exec: function(editor) { editor.scrollPageDown(); }, readOnly: true }, { name: "gotopagedown", bindKey: bindKey("PageDown", "Option-PageDown|Ctrl-V"), exec: function(editor) { editor.gotoPageDown(); }, readOnly: true }, { name: "selectpageup", bindKey: bindKey("Shift-PageUp", "Shift-PageUp"), exec: function(editor) { editor.selectPageUp(); }, readOnly: true }, { name: "pageup", bindKey: bindKey(null, "PageUp"), exec: function(editor) { editor.scrollPageUp(); }, readOnly: true }, { name: "gotopageup", bindKey: bindKey("PageUp", "Option-PageUp"), exec: function(editor) { editor.gotoPageUp(); }, readOnly: true }, { name: "selectlinestart", bindKey: bindKey("Shift-Home", "Shift-Home"), exec: function(editor) { editor.getSelection().selectLineStart(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectlineend", bindKey: bindKey("Shift-End", "Shift-End"), exec: function(editor) { editor.getSelection().selectLineEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "togglerecording", bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"), exec: function(editor) { editor.commands.toggleRecording(); }, 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-Shift-P", "Ctrl-Shift-P"), exec: function(editor) { editor.jumpToMatching(); }, multiSelectAction: "forEach", readOnly: true }, // commands disabled in readOnly mode { name: "cut", exec: function(editor) { var range = editor.getSelectionRange(); editor._emit("cut", range); if (!editor.selection.isEmpty()) { editor.session.remove(range); editor.clearSelection(); } }, multiSelectAction: "forEach" }, { name: "removeline", bindKey: bindKey("Ctrl-D", "Command-D"), exec: function(editor) { editor.removeLines(); }, multiSelectAction: "forEach" }, { name: "togglecomment", bindKey: bindKey("Ctrl-/", "Command-/"), exec: function(editor) { editor.toggleCommentLines(); }, multiSelectAction: "forEach" }, { name: "replace", bindKey: bindKey("Ctrl-R", "Command-Option-F"), exec: function(editor) { var needle = prompt("Find:", editor.getCopyText()); if (!needle) return; var replacement = prompt("Replacement:"); if (!replacement) return; editor.replace(replacement, {needle: needle}); } }, { name: "replaceall", bindKey: bindKey("Ctrl-Shift-R", "Command-Shift-Option-F"), exec: function(editor) { var needle = prompt("Find:"); if (!needle) return; var replacement = prompt("Replacement:"); if (!replacement) return; editor.replaceAll(replacement, {needle: needle}); } }, { 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("Ctrl-Alt-Up", "Command-Option-Up"), exec: function(editor) { editor.copyLinesUp(); } }, { name: "movelinesup", bindKey: bindKey("Alt-Up", "Option-Up"), exec: function(editor) { editor.moveLinesUp(); } }, { name: "copylinesdown", bindKey: bindKey("Ctrl-Alt-Down", "Command-Option-Down"), exec: function(editor) { editor.copyLinesDown(); } }, { name: "movelinesdown", bindKey: bindKey("Alt-Down", "Option-Down"), exec: function(editor) { editor.moveLinesDown(); } }, { name: "del", bindKey: bindKey("Delete", "Delete|Ctrl-D"), exec: function(editor) { editor.remove("right"); }, multiSelectAction: "forEach" }, { name: "backspace", bindKey: bindKey( "Command-Backspace|Option-Backspace|Shift-Backspace|Backspace", "Ctrl-Backspace|Command-Backspace|Shift-Backspace|Backspace|Ctrl-H" ), exec: function(editor) { editor.remove("left"); }, multiSelectAction: "forEach" }, { name: "removetolinestart", bindKey: bindKey("Alt-Backspace", "Command-Backspace"), exec: function(editor) { editor.removeToLineStart(); }, multiSelectAction: "forEach" }, { name: "removetolineend", bindKey: bindKey("Alt-Delete", "Ctrl-K"), exec: function(editor) { editor.removeToLineEnd(); }, multiSelectAction: "forEach" }, { name: "removewordleft", bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"), exec: function(editor) { editor.removeWordLeft(); }, multiSelectAction: "forEach" }, { name: "removewordright", bindKey: bindKey("Ctrl-Delete", "Alt-Delete"), exec: function(editor) { editor.removeWordRight(); }, multiSelectAction: "forEach" }, { name: "outdent", bindKey: bindKey("Shift-Tab", "Shift-Tab"), exec: function(editor) { editor.blockOutdent(); }, multiSelectAction: "forEach" }, { name: "indent", bindKey: bindKey("Tab", "Tab"), exec: function(editor) { editor.indent(); }, multiSelectAction: "forEach" }, { name: "insertstring", exec: function(editor, str) { editor.insert(str); }, multiSelectAction: "forEach" }, { name: "inserttext", exec: function(editor, args) { editor.insert(lang.stringRepeat(args.text || "", args.times || 1)); }, multiSelectAction: "forEach" }, { name: "splitline", bindKey: bindKey(null, "Ctrl-O"), exec: function(editor) { editor.splitLine(); }, multiSelectAction: "forEach" }, { name: "transposeletters", bindKey: bindKey("Ctrl-T", "Ctrl-T"), exec: function(editor) { editor.transposeLetters(); }, multiSelectAction: function(editor) {editor.transposeSelections(1); } }, { name: "touppercase", bindKey: bindKey("Ctrl-U", "Ctrl-U"), exec: function(editor) { editor.toUpperCase(); }, multiSelectAction: "forEach" }, { name: "tolowercase", bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"), exec: function(editor) { editor.toLowerCase(); }, multiSelectAction: "forEach" }]; }); define('ace/undomanager', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class UndoManager * * This object maintains the undo stack for an [[EditSession `EditSession`]]. * **/ /** * new UndoManager() * * Resets the current undo state and creates a new `UndoManager`. **/ var UndoManager = function() { this.reset(); }; (function() { /** * UndoManager.execute(options) -> Void * - options (Object): Contains additional properties * * Provides a means for implementing your own undo manager. `options` has one property, `args`, an [[Array `Array`]], with two elements: * * `args[0]` is an array of deltas * * `args[1]` is the document to associate with * **/ this.execute = function(options) { var deltas = options.args[0]; this.$doc = options.args[1]; this.$undoStack.push(deltas); this.$redoStack = []; }; this.undo = function(dontSelect) { var deltas = this.$undoStack.pop(); var undoSelectionRange = null; if (deltas) { undoSelectionRange = this.$doc.undoChanges(deltas, dontSelect); this.$redoStack.push(deltas); } return undoSelectionRange; }; this.redo = function(dontSelect) { var deltas = this.$redoStack.pop(); var redoSelectionRange = null; if (deltas) { redoSelectionRange = this.$doc.redoChanges(deltas, dontSelect); this.$undoStack.push(deltas); } return redoSelectionRange; }; this.reset = function() { this.$undoStack = []; this.$redoStack = []; }; this.hasUndo = function() { return this.$undoStack.length > 0; }; this.hasRedo = function() { return this.$redoStack.length > 0; }; }).call(UndoManager.prototype); exports.UndoManager = UndoManager; }); define('ace/virtual_renderer', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/dom', 'ace/lib/event', 'ace/lib/useragent', 'ace/config', 'ace/lib/net', 'ace/layer/gutter', 'ace/layer/marker', 'ace/layer/text', 'ace/layer/cursor', 'ace/scrollbar', 'ace/renderloop', 'ace/lib/event_emitter', 'text!ace/css/editor.css'], function(require, exports, module) { var oop = require("./lib/oop"); var dom = require("./lib/dom"); var event = require("./lib/event"); var useragent = require("./lib/useragent"); var config = require("./config"); var net = require("./lib/net"); 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 ScrollBar = require("./scrollbar").ScrollBar; var RenderLoop = require("./renderloop").RenderLoop; var EventEmitter = require("./lib/event_emitter").EventEmitter; var editorCss = require("text!./css/editor.css"); dom.importCssString(editorCss, "ace_editor"); /** * new VirtualRenderer(container, theme) * - container (DOMElement): The root element of the editor * - theme (String): The starting theme * * Constructs a new `VirtualRenderer` within the `container` specified, applying the given `theme`. * **/ var VirtualRenderer = function(container, theme) { var _self = this; this.container = container; // TODO: this breaks rendering in Cloud9 with multiple ace instances // // Imports CSS once per DOM document ('ace_editor' serves as an identifier). // dom.importCssString(editorCss, "ace_editor", container.ownerDocument); // in IE <= 9 the native cursor always shines through this.$keepTextAreaAtCursor = !useragent.isIE; dom.addCssClass(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.onResize.bind(this, true)); this.setFadeFoldWidgets(true); 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.characterWidth = textLayer.getCharacterWidth(); this.lineHeight = textLayer.getLineHeight(); this.$cursorLayer = new CursorLayer(this.content); this.$cursorPadding = 8; // Indicates whether the horizontal scrollbar is visible this.$horizScroll = false; this.$horizScrollAlwaysVisible = false; this.$animatedScroll = false; this.scrollBar = new ScrollBar(container); this.scrollBar.addEventListener("scroll", function(e) { if (!_self.$inScrollAnimation) _self.session.setScrollTop(e.data); }); this.scrollTop = 0; this.scrollLeft = 0; event.addListener(this.scroller, "scroll", function() { var scrollLeft = _self.scroller.scrollLeft; _self.scrollLeft = scrollLeft; _self.session.setScrollLeft(scrollLeft); }); this.cursorPos = { row : 0, column : 0 }; this.$textLayer.addEventListener("changeCharacterSize", function() { _self.characterWidth = textLayer.getCharacterWidth(); _self.lineHeight = textLayer.getLineHeight(); _self.$updatePrintMargin(); _self.onResize(true); _self.$loop.schedule(_self.CHANGE_FULL); }); this.$size = { width: 0, height: 0, scrollerHeight: 0, scrollerWidth: 0 }; this.layerConfig = { width : 1, padding : 0, firstRow : 0, firstRowScreen: 0, lastRow : 0, lineHeight : 1, characterWidth : 1, minHeight : 1, maxHeight : 1, offset : 0, height : 1 }; this.$loop = new RenderLoop( this.$renderChanges.bind(this), this.container.ownerDocument.defaultView ); this.$loop.schedule(this.CHANGE_FULL); this.setPadding(4); this.$updatePrintMargin(); }; (function() { this.showGutter = true; 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.setSession = function(session) { this.session = session; this.scroller.className = "ace_scroller"; this.$cursorLayer.setSession(session); this.$markerBack.setSession(session); this.$markerFront.setSession(session); this.$gutterLayer.setSession(session); this.$textLayer.setSession(session); this.$loop.schedule(this.CHANGE_FULL); }; this.updateLines = function(firstRow, lastRow) { 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; } this.$loop.schedule(this.CHANGE_LINES); }; this.updateText = function() { this.$loop.schedule(this.CHANGE_TEXT); }; this.updateFull = function() { this.$loop.schedule(this.CHANGE_FULL); }; this.updateFontSize = function() { this.$textLayer.checkForSizeChanges(); }; this.onResize = function(force) { var changes = this.CHANGE_SIZE; var size = this.$size; var height = dom.getInnerHeight(this.container); if (force || size.height != height) { size.height = height; this.scroller.style.height = height + "px"; size.scrollerHeight = this.scroller.clientHeight; this.scrollBar.setHeight(size.scrollerHeight); if (this.session) { this.session.setScrollTop(this.getScrollTop()); changes = changes | this.CHANGE_FULL; } } var width = dom.getInnerWidth(this.container); if (force || size.width != width) { size.width = width; var gutterWidth = this.showGutter ? this.$gutter.offsetWidth : 0; this.scroller.style.left = gutterWidth + "px"; size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBar.getWidth()); this.scroller.style.width = size.scrollerWidth + "px"; if (this.session.getUseWrapMode() && this.adjustWrapLimit() || force) changes = changes | this.CHANGE_FULL; } this.$loop.schedule(changes); }; this.adjustWrapLimit = function() { var availableWidth = this.$size.scrollerWidth - this.$padding * 2; var limit = Math.floor(availableWidth / this.characterWidth); return this.session.adjustWrapLimit(limit); }; this.setAnimatedScroll = function(shouldAnimate){ this.$animatedScroll = shouldAnimate; }; this.getAnimatedScroll = function() { return this.$animatedScroll; }; this.setShowInvisibles = function(showInvisibles) { if (this.$textLayer.setShowInvisibles(showInvisibles)) this.$loop.schedule(this.CHANGE_TEXT); }; this.getShowInvisibles = function() { return this.$textLayer.showInvisibles; }; this.$showPrintMargin = true; this.setShowPrintMargin = function(showPrintMargin) { this.$showPrintMargin = showPrintMargin; this.$updatePrintMargin(); }; this.getShowPrintMargin = function() { return this.$showPrintMargin; }; this.$printMarginColumn = 80; this.setPrintMarginColumn = function(showPrintMargin) { this.$printMarginColumn = showPrintMargin; this.$updatePrintMargin(); }; this.getPrintMarginColumn = function() { return this.$printMarginColumn; }; this.getShowGutter = function(){ return this.showGutter; }; this.setShowGutter = function(show){ if(this.showGutter === show) return; this.$gutter.style.display = show ? "block" : "none"; this.showGutter = show; this.onResize(true); }; this.getFadeFoldWidgets = function(){ return dom.hasCssClass(this.$gutter, "ace_fade-fold-widgets"); }; this.setFadeFoldWidgets = function(show) { if (show) dom.addCssClass(this.$gutter, "ace_fade-fold-widgets"); else dom.removeCssClass(this.$gutter, "ace_fade-fold-widgets"); }; this.$highlightGutterLine = true; this.setHighlightGutterLine = function(shouldHighlight) { if (this.$highlightGutterLine == shouldHighlight) return; this.$highlightGutterLine = shouldHighlight; this.$loop.schedule(this.CHANGE_GUTTER); }; this.getHighlightGutterLine = function() { return this.$highlightGutterLine; }; this.$updateGutterLineHighlight = function(gutterReady) { var i = this.session.selection.lead.row; if (i == this.$gutterLineHighlight) return; if (!gutterReady) { var ch = this.$gutterLayer.element.children var oldEl = ch[this.$gutterLineHighlight - this.layerConfig.firstRow]; if (oldEl) dom.removeCssClass(oldEl, "ace_gutter_active_line"); var newEl = ch[i - this.layerConfig.firstRow]; if (newEl) dom.addCssClass(newEl, "ace_gutter_active_line"); } this.$gutterLayer.removeGutterDecoration(this.$gutterLineHighlight, "ace_gutter_active_line"); this.$gutterLayer.addGutterDecoration(i, "ace_gutter_active_line"); this.$gutterLineHighlight = i; }; this.$updatePrintMargin = function() { var containerEl; if (!this.$showPrintMargin && !this.$printMarginEl) return; if (!this.$printMarginEl) { containerEl = dom.createElement("div"); containerEl.className = "ace_print_margin_layer"; this.$printMarginEl = dom.createElement("div"); this.$printMarginEl.className = "ace_print_margin"; containerEl.appendChild(this.$printMarginEl); this.content.insertBefore(containerEl, this.$textLayer.element); } var style = this.$printMarginEl.style; style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px"; style.visibility = this.$showPrintMargin ? "visible" : "hidden"; }; this.getContainerElement = function() { return this.container; }; this.getMouseEventTarget = function() { return this.content; }; this.getTextAreaContainer = function() { return this.container; }; // move text input over the cursor // this is required for iOS and IME this.$moveTextAreaToCursor = function() { if (!this.$keepTextAreaAtCursor) return; var posTop = this.$cursorLayer.$pixelPos.top; var posLeft = this.$cursorLayer.$pixelPos.left; posTop -= this.layerConfig.offset; if (posTop < 0 || posTop > this.layerConfig.height - this.lineHeight) return; var w = this.characterWidth; if (this.$composition) w += this.textarea.scrollWidth; posLeft -= this.scrollLeft; if (posLeft > this.$size.scrollerWidth - w) posLeft = this.$size.scrollerWidth - w; if (this.showGutter) posLeft += this.$gutterLayer.gutterWidth; this.textarea.style.height = this.lineHeight + "px"; this.textarea.style.width = w + "px"; this.textarea.style.left = posLeft + "px"; this.textarea.style.top = posTop - 1 + "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 flint = Math.floor((this.layerConfig.height + this.layerConfig.offset) / this.layerConfig.lineHeight); return this.layerConfig.firstRow - 1 + flint; }; 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.getHScrollBarAlwaysVisible = function() { return this.$horizScrollAlwaysVisible; }; this.setHScrollBarAlwaysVisible = function(alwaysVisible) { if (this.$horizScrollAlwaysVisible != alwaysVisible) { this.$horizScrollAlwaysVisible = alwaysVisible; if (!this.$horizScrollAlwaysVisible || !this.$horizScroll) this.$loop.schedule(this.CHANGE_SCROLL); } }; this.$updateScrollBar = function() { this.scrollBar.setInnerHeight(this.layerConfig.maxHeight); this.scrollBar.setScrollTop(this.scrollTop); }; this.$renderChanges = function(changes) { if (!changes || !this.session || !this.container.offsetWidth) return; // text, scrolling and resize changes can cause the view port size to change if (changes & this.CHANGE_FULL || changes & this.CHANGE_SIZE || changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES || changes & this.CHANGE_SCROLL ) this.$computeLayerConfig(); // horizontal scrolling if (changes & this.CHANGE_H_SCROLL) { this.scroller.scrollLeft = this.scrollLeft; // read the value after writing it since the value might get clipped var scrollLeft = this.scroller.scrollLeft; this.scrollLeft = scrollLeft; this.session.setScrollLeft(scrollLeft); this.scroller.className = this.scrollLeft == 0 ? "ace_scroller" : "ace_scroller horscroll"; } // full if (changes & this.CHANGE_FULL) { this.$textLayer.checkForSizeChanges(); // update scrollbar first to not lose scroll position when gutter calls resize this.$updateScrollBar(); this.$textLayer.update(this.layerConfig); if (this.showGutter) { if (this.$highlightGutterLine) this.$updateGutterLineHighlight(true); this.$gutterLayer.update(this.layerConfig); } this.$markerBack.update(this.layerConfig); this.$markerFront.update(this.layerConfig); this.$cursorLayer.update(this.layerConfig); this.$moveTextAreaToCursor(); return; } // scrolling if (changes & this.CHANGE_SCROLL) { this.$updateScrollBar(); if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES) this.$textLayer.update(this.layerConfig); else this.$textLayer.scrollLines(this.layerConfig); if (this.showGutter) { if (this.$highlightGutterLine) this.$updateGutterLineHighlight(true); this.$gutterLayer.update(this.layerConfig); } this.$markerBack.update(this.layerConfig); this.$markerFront.update(this.layerConfig); this.$cursorLayer.update(this.layerConfig); this.$moveTextAreaToCursor(); return; } if (changes & this.CHANGE_TEXT) { this.$textLayer.update(this.layerConfig); if (this.showGutter) this.$gutterLayer.update(this.layerConfig); } else if (changes & this.CHANGE_LINES) { if (this.$updateLines()) { this.$updateScrollBar(); if (this.showGutter) this.$gutterLayer.update(this.layerConfig); } } else if (changes & this.CHANGE_GUTTER) { if (this.showGutter) this.$gutterLayer.update(this.layerConfig); } if (changes & this.CHANGE_CURSOR) { this.$cursorLayer.update(this.layerConfig); this.$moveTextAreaToCursor(); this.$highlightGutterLine && this.$updateGutterLineHighlight(false); } if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) { this.$markerFront.update(this.layerConfig); } if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) { this.$markerBack.update(this.layerConfig); } if (changes & this.CHANGE_SIZE) this.$updateScrollBar(); }; this.$computeLayerConfig = function() { var session = this.session; var offset = this.scrollTop % this.lineHeight; var minHeight = this.$size.scrollerHeight + this.lineHeight; var longestLine = this.$getLongestLine(); var horizScroll = this.$horizScrollAlwaysVisible || this.$size.scrollerWidth - longestLine < 0; var horizScrollChanged = this.$horizScroll !== horizScroll; this.$horizScroll = horizScroll; if (horizScrollChanged) { this.scroller.style.overflowX = horizScroll ? "scroll" : "hidden"; // when we hide scrollbar scroll event isn't emited // leaving session with wrong scrollLeft value if (!horizScroll) this.session.setScrollLeft(0); } var maxHeight = this.session.getScreenLength() * this.lineHeight; this.session.setScrollTop(Math.max(0, Math.min(this.scrollTop, maxHeight - this.$size.scrollerHeight))); var lineCount = Math.ceil(minHeight / this.lineHeight) - 1; var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight)); var lastRow = firstRow + lineCount; // Map lines on the screen to lines in the document. var firstRowScreen, firstRowHeight; var lineHeight = { lineHeight: this.lineHeight }; firstRow = session.screenToDocumentRow(firstRow, 0); // Check if firstRow is inside of a foldLine. If true, then use the first // row of the foldLine. var foldLine = session.getFoldLine(firstRow); if (foldLine) { firstRow = foldLine.start.row; } firstRowScreen = session.documentToScreenRow(firstRow, 0); firstRowHeight = session.getRowHeight(lineHeight, firstRow); lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1); minHeight = this.$size.scrollerHeight + session.getRowHeight(lineHeight, lastRow)+ firstRowHeight; offset = this.scrollTop - firstRowScreen * this.lineHeight; this.layerConfig = { width : longestLine, padding : this.$padding, firstRow : firstRow, firstRowScreen: firstRowScreen, lastRow : lastRow, lineHeight : this.lineHeight, characterWidth : this.characterWidth, minHeight : minHeight, maxHeight : maxHeight, offset : offset, height : this.$size.scrollerHeight }; // For debugging. // console.log(JSON.stringify(this.layerConfig)); this.$gutterLayer.element.style.marginTop = (-offset) + "px"; this.content.style.marginTop = (-offset) + "px"; this.content.style.width = longestLine + 2 * this.$padding + "px"; this.content.style.height = minHeight + "px"; // Horizontal scrollbar visibility may have changed, which changes // the client height of the scroller if (horizScrollChanged) this.onResize(true); }; 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 the last row is unknown -> redraw everything if (lastRow === Infinity) { if (this.showGutter) this.$gutterLayer.update(layerConfig); this.$textLayer.update(layerConfig); return; } // else update only the changed rows this.$textLayer.updateLines(layerConfig, firstRow, lastRow); return true; }; this.$getLongestLine = function() { var charCount = this.session.getScreenWidth(); if (this.$textLayer.showInvisibles) 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.$loop.schedule(this.CHANGE_GUTTER); }; this.removeGutterDecoration = function(row, className){ this.$gutterLayer.removeGutterDecoration(row, className); this.$loop.schedule(this.CHANGE_GUTTER); }; 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) { // first scroll anchor into view then scroll lead into view this.scrollCursorIntoView(anchor, offset); this.scrollCursorIntoView(lead, offset); }; this.scrollCursorIntoView = function(cursor, offset) { // the editor is not visible if (this.$size.scrollerHeight === 0) return; var pos = this.$cursorLayer.getPixelPosition(cursor); var left = pos.left; var top = pos.top; if (this.scrollTop > top) { if (offset) top -= offset * this.$size.scrollerHeight; this.session.setScrollTop(top); } else if (this.scrollTop + this.$size.scrollerHeight < top + this.lineHeight) { if (offset) 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 = 0; this.session.setScrollLeft(left); } else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) { this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth)); } }; 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 offset = pos.top - this.$size.scrollerHeight * (alignment || 0); this.session.setScrollTop(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 && Math.abs(fromValue - toValue) < 100000) { var _self = this; var steps = _self.$calcSteps(fromValue, toValue); this.$inScrollAnimation = true; clearInterval(this.$timer); _self.session.setScrollTop(steps.shift()); this.$timer = setInterval(function() { if (steps.length) { _self.session.setScrollTop(steps.shift()); // trick session to think it's already scrolled to not loose toValue _self.session.$scrollTop = toValue; } else if (toValue != null) { _self.session.$scrollTop = -1; _self.session.setScrollTop(toValue); toValue = null; } else { // do this on separate step to not get spurious scroll event from scrollbar _self.$timer = clearInterval(_self.$timer); _self.$inScrollAnimation = false; callback && callback(); } }, 10); } }; this.scrollToY = function(scrollTop) { // after calling scrollBar.setScrollTop // scrollbar sends us event with same scrollTop. ignore it if (this.scrollTop !== scrollTop) { this.$loop.schedule(this.CHANGE_SCROLL); this.scrollTop = scrollTop; } }; this.scrollToX = function(scrollLeft) { if (scrollLeft < 0) scrollLeft = 0; if (this.scrollLeft !== scrollLeft) this.scrollLeft = scrollLeft; this.$loop.schedule(this.CHANGE_H_SCROLL); }; 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() > 0) return true; if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight < this.layerConfig.maxHeight) return true; // todo: handle horizontal scrolling }; 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 = Math.floor( (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._loadTheme = function(name, callback) { if (!config.get("packaged")) return callback(); var base = name.split("/").pop(); var filename = config.get("themePath") + "/theme-" + base + config.get("suffix"); net.loadScript(filename, callback); }; this.setTheme = function(theme) { var _self = this; this.$themeValue = theme; if (!theme || typeof theme == "string") { var moduleName = theme || "ace/theme/textmate"; var module; try { module = require(moduleName); } catch (e) {}; if (module) return afterLoad(module); _self._loadTheme(moduleName, function() { require([moduleName], function(module) { if (_self.$themeValue !== theme) return; afterLoad(module); }); }); } else { afterLoad(theme); } function afterLoad(theme) { dom.importCssString( theme.cssText, theme.cssClass, _self.container.ownerDocument ); if (_self.$theme) dom.removeCssClass(_self.container, _self.$theme); _self.$theme = theme ? theme.cssClass : null; if (_self.$theme) dom.addCssClass(_self.container, _self.$theme); if (theme && theme.isDark) dom.addCssClass(_self.container, "ace_dark"); else dom.removeCssClass(_self.container, "ace_dark"); // force re-measure of the gutter width if (_self.$size) { _self.$size.width = 0; _self.onResize(); } } }; this.getTheme = function() { return this.$themeValue; }; // Methods allows to add / remove CSS classnames to the editor element. // This feature can be used by plug-ins to provide a visual indication of // a certain mode that editor is in. /** * VirtualRenderer.setStyle(style) -> Void * - style (String): A class name * * [Adds a new class, `style`, to the editor.]{: #VirtualRenderer.setStyle} **/ this.setStyle = function setStyle(style) { dom.addCssClass(this.container, style); }; this.unsetStyle = function unsetStyle(style) { dom.removeCssClass(this.container, style); }; this.destroy = function() { this.$textLayer.destroy(); this.$cursorLayer.destroy(); }; }).call(VirtualRenderer.prototype); exports.VirtualRenderer = VirtualRenderer; }); define('ace/layer/gutter', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var dom = require("../lib/dom"); var oop = require("../lib/oop"); 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.$breakpoints = []; this.$annotations = []; this.$decorations = []; }; (function() { oop.implement(this, EventEmitter); this.setSession = function(session) { this.session = session; }; this.addGutterDecoration = function(row, className){ if (!this.$decorations[row]) this.$decorations[row] = ""; this.$decorations[row] += " " + className; }; this.removeGutterDecoration = function(row, className){ this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, ""); }; this.setAnnotations = function(annotations) { // iterate over sparse array this.$annotations = []; for (var row in annotations) if (annotations.hasOwnProperty(row)) { var rowAnnotations = annotations[row]; if (!rowAnnotations) continue; var rowInfo = this.$annotations[row] = { text: [] }; for (var i=0; i<rowAnnotations.length; i++) { var annotation = rowAnnotations[i]; var annoText = annotation.text.replace(/"/g, "&quot;").replace(/'/g, "&#8217;").replace(/</, "&lt;"); 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.update = function(config) { this.$config = config; var emptyAnno = {className: "", text: []}; var html = []; var i = config.firstRow; var lastRow = config.lastRow; var fold = this.session.getNextFoldLine(i); var foldStart = fold ? fold.start.row : Infinity; var foldWidgets = this.$showFoldWidgets && this.session.foldWidgets; var breakpoints = this.session.$breakpoints; while (true) { if(i > foldStart) { i = fold.end.row + 1; fold = this.session.getNextFoldLine(i, fold); foldStart = fold ?fold.start.row :Infinity; } if(i > lastRow) break; var annotation = this.$annotations[i] || emptyAnno; html.push("<div class='ace_gutter-cell", this.$decorations[i] || "", breakpoints[i] ? " ace_breakpoint " : " ", annotation.className, "' title='", annotation.text.join("\n"), "' style='height:", this.session.getRowLength(i) * config.lineHeight, "px;'>", (i+1)); if (foldWidgets) { var c = foldWidgets[i]; // check if cached value is invalidated and we need to recompute if (c == null) c = foldWidgets[i] = this.session.getFoldWidget(i); if (c) html.push( "<span class='ace_fold-widget ", c, c == "start" && i == foldStart && i < fold.end.row ? " closed" : " open", "'></span>" ); } html.push("</div>"); i++; } if (this.session.$useWrapMode) html.push( "<div class='ace_gutter-cell' style='pointer-events:none;opacity:0'>", this.session.getLength() - 1, "</div>" ); this.element = dom.setInnerHtml(this.element, html.join("")); this.element.style.height = config.minHeight + "px"; var gutterWidth = this.element.offsetWidth; if (gutterWidth !== this.gutterWidth) { this.gutterWidth = gutterWidth; this._emit("changeGutterWidth", gutterWidth); } }; 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.getShowFoldWidgets = function() { return this.$showFoldWidgets; }; }).call(Gutter.prototype); exports.Gutter = Gutter; }); define('ace/layer/marker', ['require', 'exports', 'module' , 'ace/range', 'ace/lib/dom'], function(require, exports, module) { 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 = Math.round( this.$padding + range.start.column * config.characterWidth ); marker.renderer(html, range, left, top, config); } else if (range.isMultiLine()) { if (marker.type == "text") { this.drawTextMarker(html, range, marker.clazz, config); } else { this.drawMultiLineMarker( html, range, marker.clazz, config, marker.type ); } } else { this.drawSingleLineMarker( html, range, marker.clazz + " start", config, null, marker.type ); } } this.element = dom.setInnerHtml(this.element, html.join("")); }; this.$getTop = function(row, layerConfig) { return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight; }; // Draws a marker, which spans a range of text on multiple lines this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig) { // selection start var row = range.start.row; var lineRange = new Range( row, range.start.column, row, this.session.getScreenLastRowColumn(row) ); this.drawSingleLineMarker(stringBuilder, lineRange, clazz + " start", layerConfig, 1, "text"); // selection end row = range.end.row; lineRange = new Range(row, 0, row, range.end.column); this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 0, "text"); for (row = range.start.row + 1; row < range.end.row; row++) { lineRange.start.row = row; lineRange.end.row = row; lineRange.end.column = this.session.getScreenLastRowColumn(row); this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 1, "text"); } }; // Draws a multi line marker, where lines span the full width this.drawMultiLineMarker = function(stringBuilder, range, clazz, layerConfig, type) { var padding = type === "background" ? 0 : this.$padding; var layerWidth = layerConfig.width + 2 * this.$padding - padding; // from selection start to the end of the line var height = layerConfig.lineHeight; var width = Math.round(layerWidth - (range.start.column * layerConfig.characterWidth)); var top = this.$getTop(range.start.row, layerConfig); var left = Math.round( padding + range.start.column * layerConfig.characterWidth ); stringBuilder.push( "<div class='", clazz, " start' style='", "height:", height, "px;", "width:", width, "px;", "top:", top, "px;", "left:", left, "px;'></div>" ); // from start of the last line to the selection end top = this.$getTop(range.end.row, layerConfig); width = Math.round(range.end.column * layerConfig.characterWidth); stringBuilder.push( "<div class='", clazz, "' style='", "height:", height, "px;", "width:", width, "px;", "top:", top, "px;", "left:", padding, "px;'></div>" ); // all the complete lines height = (range.end.row - range.start.row - 1) * layerConfig.lineHeight; if (height < 0) return; top = this.$getTop(range.start.row + 1, layerConfig); stringBuilder.push( "<div class='", clazz, "' style='", "height:", height, "px;", "width:", layerWidth, "px;", "top:", top, "px;", "left:", padding, "px;'></div>" ); }; // Draws a marker which covers part or whole width of a single screen line this.drawSingleLineMarker = function(stringBuilder, range, clazz, layerConfig, extraLength, type) { var padding = type === "background" ? 0 : this.$padding; var height = layerConfig.lineHeight; if (type === "background") var width = layerConfig.width; else width = Math.round((range.end.column + (extraLength || 0) - range.start.column) * layerConfig.characterWidth); var top = this.$getTop(range.start.row, layerConfig); var left = Math.round( padding + range.start.column * layerConfig.characterWidth ); stringBuilder.push( "<div class='", clazz, "' style='", "height:", height, "px;", "width:", width, "px;", "top:", top, "px;", "left:", left,"px;'></div>" ); }; }).call(Marker.prototype); exports.Marker = Marker; }); 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) { 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.$characterSize = this.$measureSizes() || {width: 0, height: 0}; this.$pollSizeChanges(); }; (function() { oop.implement(this, EventEmitter); this.EOF_CHAR = "\xB6"; //"&para;"; this.EOL_CHAR = "\xAC"; //"&not;"; this.TAB_CHAR = "\u2192"; //"&rarr;" "\u21E5"; this.SPACE_CHAR = "\xB7"; //"&middot;"; this.$padding = 0; this.setPadding = function(padding) { this.$padding = padding; this.element.style.padding = "0 " + padding + "px"; }; this.getLineHeight = function() { return this.$characterSize.height || 1; }; this.getCharacterWidth = function() { return this.$characterSize.width || 1; }; this.checkForSizeChanges = function() { var size = this.$measureSizes(); if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) { this.$characterSize = size; this._emit("changeCharacterSize", {data: size}); } }; this.$pollSizeChanges = function() { var self = this; this.$pollSizeChangesTimer = setInterval(function() { self.checkForSizeChanges(); }, 500); }; this.$fontStyles = { fontFamily : 1, fontSize : 1, fontWeight : 1, fontStyle : 1, lineHeight : 1 }; this.$measureSizes = useragent.isIE || useragent.isOldGecko ? function() { var n = 1000; if (!this.$measureNode) { var measureNode = this.$measureNode = dom.createElement("div"); var style = measureNode.style; style.width = style.height = "auto"; style.left = style.top = (-n * 40) + "px"; style.visibility = "hidden"; style.position = "fixed"; style.overflow = "visible"; style.whiteSpace = "nowrap"; // in FF 3.6 monospace fonts can have a fixed sub pixel width. // that's why we have to measure many characters // Note: characterWidth can be a float! measureNode.innerHTML = lang.stringRepeat("Xy", n); if (this.element.ownerDocument.body) { this.element.ownerDocument.body.appendChild(measureNode); } else { var container = this.element.parentNode; while (!dom.hasCssClass(container, "ace_editor")) container = container.parentNode; container.appendChild(measureNode); } } // Size and width can be null if the editor is not visible or // detached from the document if (!this.element.offsetWidth) return null; var style = this.$measureNode.style; var computedStyle = dom.computedStyle(this.element); for (var prop in this.$fontStyles) style[prop] = computedStyle[prop]; var size = { height: this.$measureNode.offsetHeight, width: this.$measureNode.offsetWidth / (n * 2) }; // Size and width can be null if the editor is not visible or // detached from the document if (size.width == 0 || size.height == 0) return null; return size; } : function() { if (!this.$measureNode) { var measureNode = this.$measureNode = dom.createElement("div"); var style = measureNode.style; style.width = style.height = "auto"; style.left = style.top = -100 + "px"; style.visibility = "hidden"; style.position = "fixed"; style.overflow = "visible"; style.whiteSpace = "nowrap"; measureNode.innerHTML = "X"; var container = this.element.parentNode; while (container && !dom.hasCssClass(container, "ace_editor")) container = container.parentNode; if (!container) return this.$measureNode = null; container.appendChild(measureNode); } var rect = this.$measureNode.getBoundingClientRect(); var size = { height: rect.height, width: rect.width }; // Size and width can be null if the editor is not visible or // detached from the document if (size.width == 0 || size.height == 0) return null; return size; }; this.setSession = function(session) { this.session = session; }; this.showInvisibles = false; this.setShowInvisibles = function(showInvisibles) { if (this.showInvisibles == showInvisibles) return false; this.showInvisibles = showInvisibles; return true; }; this.$tabStrings = []; this.$computeTabString = function() { var tabSize = this.session.getTabSize(); var tabStr = this.$tabStrings = [0]; for (var i = 1; i < tabSize + 1; i++) { if (this.showInvisibles) { tabStr.push("<span class='ace_invisible'>" + this.TAB_CHAR + new Array(i).join("&#160;") + "</span>"); } else { tabStr.push(new Array(i+1).join("&#160;")); } } }; this.updateLines = function(config, firstRow, lastRow) { this.$computeTabString(); // Due to wrap line changes there can be new lines if e.g. // the line to updated wrapped in the meantime. 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 ++; } for (var i=first; i<=last; i++) { var lineElement = lineElements[lineElementsIdx++]; if (!lineElement) continue; var html = []; var tokens = this.session.getTokens(i); this.$renderLine(html, i, tokens, !this.$useLineGroups()); lineElement = dom.setInnerHtml(lineElement, html.join("")); i = this.session.getRowFoldEnd(i); } }; this.scrollLines = function(config) { this.$computeTabString(); 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 = []; // Get the tokens per line as there might be some lines in between // beeing folded. var tokens = this.session.getTokens(row); this.$renderLine(html, row, tokens, false); // don't use setInnerHtml since we are working with an empty DIV container.innerHTML = html.join(""); if (this.$useLineGroups()) { container.className = 'ace_line_group'; fragment.appendChild(container); } else { var lines = container.childNodes while(lines.length) fragment.appendChild(lines[0]); } row++; } return fragment; }; this.update = function(config) { this.$computeTabString(); 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("<div class='ace_line_group'>") // Get the tokens per line as there might be some lines in between // beeing folded. var tokens = this.session.getTokens(row); this.$renderLine(html, row, tokens, false); if (this.$useLineGroups()) html.push("</div>"); // end the line group row++; } this.element = dom.setInnerHtml(this.element, html.join("")); }; this.$textToken = { "text": true, "rparen": true, "lparen": true }; this.$renderToken = function(stringBuilder, screenColumn, token, value) { var self = this; var replaceReg = /\t|&|<|( +)|([\u0000-\u0019\u00a0\u1680\u180E\u2000-\u200b\u2028\u2029\u202F\u205F\u3000\uFEFF])|[\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 new Array(c.length+1).join("&#160;"); } else if (c == "&") { return "&#38;"; } else if (c == "<") { return "&#60;"; } else if (c == "\t") { var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx); screenColumn += tabSize - 1; return self.$tabStrings[tabSize]; } else if (c == "\u3000") { // U+3000 is both invisible AND full-width, so must be handled uniquely var classToUse = self.showInvisibles ? "ace_cjk ace_invisible" : "ace_cjk"; var space = self.showInvisibles ? self.SPACE_CHAR : ""; screenColumn += 1; return "<span class='" + classToUse + "' style='width:" + (self.config.characterWidth * 2) + "px'>" + space + "</span>"; } else if (b) { return "<span class='ace_invisible ace_invalid'>" + self.SPACE_CHAR + "</span>"; } else { screenColumn += 1; return "<span class='ace_cjk' style='width:" + (self.config.characterWidth * 2) + "px'>" + c + "</span>"; } }; 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("<span class='", classes, "'", style, ">", output, "</span>"); } else { stringBuilder.push(output); } return screenColumn + value.length; }; this.$renderLineCore = function(stringBuilder, lastRow, tokens, splits, onlyContents) { var chars = 0; var split = 0; var splitChars; var screenColumn = 0; var self = this; if (!splits || splits.length == 0) splitChars = Number.MAX_VALUE; else splitChars = splits[0]; if (!onlyContents) { stringBuilder.push("<div class='ace_line' style='height:", this.config.lineHeight, "px", "'>" ); } for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; var value = token.value; if (chars + value.length < splitChars) { screenColumn = self.$renderToken( stringBuilder, screenColumn, token, value ); chars += value.length; } else { while (chars + value.length >= splitChars) { screenColumn = self.$renderToken( stringBuilder, screenColumn, token, value.substring(0, splitChars - chars) ); value = value.substring(splitChars - chars); chars = splitChars; if (!onlyContents) { stringBuilder.push("</div>", "<div class='ace_line' style='height:", this.config.lineHeight, "px", "'>" ); } split ++; screenColumn = 0; splitChars = splits[split] || Number.MAX_VALUE; } if (value.length != 0) { chars += value.length; screenColumn = self.$renderToken( stringBuilder, screenColumn, token, value ); } } } if (this.showInvisibles) { if (lastRow !== this.session.getLength() - 1) stringBuilder.push("<span class='ace_invisible'>" + this.EOL_CHAR + "</span>"); else stringBuilder.push("<span class='ace_invisible'>" + this.EOF_CHAR + "</span>"); } if (!onlyContents) stringBuilder.push("</div>"); }; this.$renderLine = function(stringBuilder, row, tokens, onlyContents) { // Check if the line to render is folded or not. If not, things are // simple, otherwise, we need to fake some things... if (!this.session.isRowFolded(row)) { var splits = this.session.getRowSplitData(row); this.$renderLineCore(stringBuilder, row, tokens, splits, onlyContents); } else { this.$renderFoldLine(stringBuilder, row, tokens, onlyContents); } }; this.$renderFoldLine = function(stringBuilder, row, tokens, onlyContents) { var session = this.session, foldLine = session.getFoldLine(row), 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); // Check if the token value is longer then the from...to spacing. 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) { var value = tokens[idx].value; if (value.length + col > to) { value = value.substring(0, to - col); } renderTokens.push({ type: tokens[idx].type, value: value }); col += value.length; idx += 1; } } foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) { if (placeholder) { renderTokens.push({ type: "fold", value: placeholder }); } else { if (isNewRow) tokens = this.session.getTokens(row); if (tokens.length) addTokens(tokens, lastColumn, column); } }.bind(this), foldLine.end.row, this.session.getLine(foldLine.end.row).length); // TODO: Build a fake splits array! var splits = this.session.$useWrapMode?this.session.$wrapData[row]:null; this.$renderLineCore(stringBuilder, row, renderTokens, splits, onlyContents); }; this.$useLineGroups = function() { // For the updateLines function to work correctly, it's important that the // child nodes of this.element correspond on a 1-to-1 basis to rows in the // document (as distinct from lines on the screen). For sessions that are // wrapped, this means we need to add a layer to the node hierarchy (tagged // with the class name ace_line_group). 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; }); define('ace/layer/cursor', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) { var dom = require("../lib/dom"); var Cursor = function(parentEl) { this.element = dom.createElement("div"); this.element.className = "ace_layer ace_cursor-layer"; parentEl.appendChild(this.element); this.isVisible = false; this.cursors = []; this.cursor = this.addCursor(); }; (function() { this.$padding = 0; this.setPadding = function(padding) { this.$padding = padding; }; this.setSession = function(session) { this.session = session; }; this.addCursor = function() { var el = dom.createElement("div"); var className = "ace_cursor"; if (!this.isVisible) className += " ace_hidden"; if (this.overwrite) className += " ace_overwrite"; el.className = className; 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; for (var i = this.cursors.length; i--; ) dom.addCssClass(this.cursors[i], "ace_hidden"); clearInterval(this.blinkId); }; this.showCursor = function() { this.isVisible = true; for (var i = this.cursors.length; i--; ) dom.removeCssClass(this.cursors[i], "ace_hidden"); this.element.style.visibility = ""; this.restartTimer(); }; this.restartTimer = function() { clearInterval(this.blinkId); if (!this.isVisible) return; var element = this.cursors.length == 1 ? this.cursor : this.element; this.blinkId = setInterval(function() { element.style.visibility = "hidden"; setTimeout(function() { element.style.visibility = ""; }, 400); }, 1000); }; 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 = Math.round(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; if (this.session.selectionMarkerCount > 0) { var selections = this.session.$selectionMarkers; var i = 0, sel, cursorIndex = 0; for (var i = selections.length; i--; ) { sel = selections[i]; var pixelPos = this.getPixelPosition(sel.cursor, true); var style = (this.cursors[cursorIndex++] || this.addCursor()).style; style.left = pixelPos.left + "px"; style.top = pixelPos.top + "px"; style.width = config.characterWidth + "px"; style.height = config.lineHeight + "px"; } if (cursorIndex > 1) while (this.cursors.length > cursorIndex) this.removeCursor(); } else { var pixelPos = this.getPixelPosition(null, true); var style = this.cursor.style; style.left = pixelPos.left + "px"; style.top = pixelPos.top + "px"; style.width = config.characterWidth + "px"; style.height = config.lineHeight + "px"; while (this.cursors.length > 1) this.removeCursor(); } var overwrite = this.session.getOverwrite(); if (overwrite != this.overwrite) this.$setOverite(overwrite); // cache for textarea and gutter highlight this.$pixelPos = pixelPos; this.restartTimer(); }; this.$setOverite = function(overwrite) { this.overwrite = overwrite; for (var i = this.cursors.length; i--; ) { if (overwrite) dom.addCssClass(this.cursors[i], "ace_overwrite"); else dom.removeCssClass(this.cursors[i], "ace_overwrite"); } }; this.destroy = function() { clearInterval(this.blinkId); } }).call(Cursor.prototype); exports.Cursor = Cursor; }); define('ace/scrollbar', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/dom', 'ace/lib/event', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var dom = require("./lib/dom"); var event = require("./lib/event"); var EventEmitter = require("./lib/event_emitter").EventEmitter; /** * new ScrollBar(parent) * - parent (DOMElement): A DOM element * * Creates a new `ScrollBar`. `parent` is the owner of the scroll bar. * **/ var ScrollBar = function(parent) { this.element = dom.createElement("div"); this.element.className = "ace_sb"; this.inner = dom.createElement("div"); this.element.appendChild(this.inner); parent.appendChild(this.element); // in OSX lion the scrollbars appear to have no width. In this case resize // the to show the scrollbar but still pretend that the scrollbar has a width // of 0px // in Firefox 6+ scrollbar is hidden if element has the same width as scrollbar // make element a little bit wider to retain scrollbar when page is zoomed this.width = dom.scrollbarWidth(parent.ownerDocument); this.element.style.width = (this.width || 15) + 5 + "px"; event.addListener(this.element, "scroll", this.onScroll.bind(this)); }; (function() { oop.implement(this, EventEmitter); this.onScroll = function() { this._emit("scroll", {data: this.element.scrollTop}); }; this.getWidth = function() { return this.width; }; this.setHeight = function(height) { this.element.style.height = height + "px"; }; this.setInnerHeight = function(height) { this.inner.style.height = height + "px"; }; // TODO: on chrome 17+ after for small zoom levels after this function // this.element.scrollTop != scrollTop which makes page to scroll up. this.setScrollTop = function(scrollTop) { this.element.scrollTop = scrollTop; }; }).call(ScrollBar.prototype); exports.ScrollBar = ScrollBar; }); define('ace/renderloop', ['require', 'exports', 'module' , 'ace/lib/event'], function(require, exports, module) { var event = require("./lib/event"); /** internal, hide * new RenderLoop(onRender, win) * * * **/ var RenderLoop = function(onRender, win) { this.onRender = onRender; this.pending = false; this.changes = 0; this.window = win || window; }; (function() { /** internal, hide * RenderLoop.schedule(change) * - change (Array): * * **/ this.schedule = function(change) { //this.onRender(change); //return; this.changes = this.changes | change; if (!this.pending) { this.pending = true; var _self = this; event.nextTick(function() { _self.pending = false; var changes; while (changes = _self.changes) { _self.changes = 0; _self.onRender(changes); } }, this.window); } }; }).call(RenderLoop.prototype); exports.RenderLoop = RenderLoop; }); define("text!ace/css/editor.css", [], ".ace_editor {\n" + " position: absolute;\n" + " overflow: hidden;\n" + " font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Droid Sans Mono', 'Consolas', monospace;\n" + " font-size: 12px;\n" + "}\n" + "\n" + ".ace_scroller {\n" + " position: absolute;\n" + " overflow: hidden;\n" + "}\n" + "\n" + ".ace_content {\n" + " position: absolute;\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + " cursor: text;\n" + "}\n" + "\n" + ".ace_gutter {\n" + " position: absolute;\n" + " overflow : hidden;\n" + " height: 100%;\n" + " width: auto;\n" + " cursor: default;\n" + " z-index: 4;\n" + "}\n" + "\n" + ".ace_scroller.horscroll {\n" + " box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\n" + "}\n" + "\n" + ".ace_gutter-cell {\n" + " padding-left: 19px;\n" + " padding-right: 6px;\n" + "}\n" + "\n" + ".ace_gutter-cell.ace_error {\n" + " background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QUM2OEZDQTQ4RTU0MTFFMUEzM0VFRTM2RUY1M0RBMjYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QUM2OEZDQTU4RTU0MTFFMUEzM0VFRTM2RUY1M0RBMjYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBQzY4RkNBMjhFNTQxMUUxQTMzRUVFMzZFRjUzREEyNiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBQzY4RkNBMzhFNTQxMUUxQTMzRUVFMzZFRjUzREEyNiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PkgXxbAAAAJbSURBVHjapFNNaBNBFH4zs5vdZLP5sQmNpT82QY209heh1ioWisaDRcSKF0WKJ0GQnrzrxasHsR6EnlrwD0TagxJabaVEpFYxLWlLSS822tr87m66ccfd2GKyVhA6MMybgfe97/vmPUQphd0sZjto9XIn9OOsvlu2nkqRzVU+6vvlzPf8W6bk8dxQ0NPbxAALgCgg2JkaQuhzQau/El0zbmUA7U0Es8v2CiYmKQJHGO1QICCLoqilMhkmurDAyapKgqItezi/USRdJqEYY4D5jCy03ht2yMkkvL91jTTX10qzyyu2hruPRN7jgbH+EOsXcMLgYiThEgAMhABW85oqy1DXdRIdvP1AHJ2acQXvDIrVHcdQNrEKNYSVMSZGMjEzIIAwDXIo+6G/FxcGnzkC3T2oMhLjre49sBB+RRcHLqdafK6sYdE/GGBwU1VpFNj0aN8pJbe+BkZyevUrvLl6Xmm0W9IuTc0DxrDNAJd5oEvI/KRsNC3bQyNjPO9yQ1YHcfj2QvfQc/5TUhJTBc2iM0U7AWDQtc1nJHvD/cfO2s7jaGkiTEfa/Ep8coLu7zmNmh8+dc5lZDuUeFAGUNA/OY6JVaypQ0vjr7XYjUvJM37vt+j1vuTK5DgVfVUoTjVe+y3/LxMxY2GgU+CSLy4cpfsYorRXuXIOi0Vt40h67uZFTdIo6nLaZcwUJWAzwNS0tBnqqKzQDnjdG/iPyZxo46HaKUpbvYkj8qYRTZsBhge+JHhZyh0x9b95JqjVJkT084kZIPwu/mPWqPgfQ5jXh2+92Ay7HedfAgwA6KDWafb4w3cAAAAASUVORK5CYII=\");\n" + " background-repeat: no-repeat;\n" + " background-position: 2px center;\n" + "}\n" + "\n" + ".ace_gutter-cell.ace_warning {\n" + " background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QUM2OEZDQTg4RTU0MTFFMUEzM0VFRTM2RUY1M0RBMjYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QUM2OEZDQTk4RTU0MTFFMUEzM0VFRTM2RUY1M0RBMjYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBQzY4RkNBNjhFNTQxMUUxQTMzRUVFMzZFRjUzREEyNiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBQzY4RkNBNzhFNTQxMUUxQTMzRUVFMzZFRjUzREEyNiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pgd7PfIAAAGmSURBVHjaYvr//z8DJZiJgUIANoCRkREb9gLiSVAaQx4OQM7AAkwd7XU2/v++/rOttdYGEB9dASEvOMydGKfH8Gv/p4XTkvRBfLxeQAP+1cUhXopyvzhP7P/IoSj7g7Mw09cNKO6J1QQ0L4gICPIv/veg/8W+JdFvQNLHVsW9/nmn9zk7B+cCkDwhL7gt6knSZnx9/LuCEOcvkIAMP+cvto9nfqyZmmUAksfnBUtbM60gX/3/kgyv3/xSFOL5DZT+L8vP+Yfh5cvfPvp/xUHyQHXGyAYwgpwBjZYFT3Y1OEl/OfCH4ffv3wzc4iwMvNIsDJ+f/mH4+vIPAxsb631WW0Yln6ZpQLXdMK/DXGDflh+sIv37EivD5x//Gb7+YWT4y86sl7BCCkSD+Z++/1dkvsFRl+HnD1Rvje4F8whjMXmGj58YGf5zsDMwcnAwfPvKcml62DsQDeaDxN+/Y0qwlpEHqrdB94IRNIDUgfgfKJChGK4OikEW3gTiXUB950ASLFAF54AC94A0G9QAfOnmF9DCDzABFqS08IHYDIScdijOjQABBgC+/9awBH96jwAAAABJRU5ErkJggg==\");\n" + " background-repeat: no-repeat;\n" + " background-position: 2px center;\n" + "}\n" + "\n" + ".ace_gutter-cell.ace_info {\n" + " background-image: url(\"data:image/gif;base64,R0lGODlhEAAQAMQAAAAAAEFBQVJSUl5eXmRkZGtra39/f4WFhYmJiZGRkaampry8vMPDw8zMzNXV1dzc3OTk5Orq6vDw8P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABQALAAAAAAQABAAAAUuICWOZGmeaBml5XGwFCQSBGyXRSAwtqQIiRuiwIM5BoYVbEFIyGCQoeJGrVptIQA7\");\n" + " background-repeat: no-repeat;\n" + " background-position: 2px center;\n" + "}\n" + "\n" + ".ace_editor .ace_sb {\n" + " position: absolute;\n" + " overflow-x: hidden;\n" + " overflow-y: scroll;\n" + " right: 0;\n" + "}\n" + "\n" + ".ace_editor .ace_sb div {\n" + " position: absolute;\n" + " width: 1px;\n" + " left: 0;\n" + "}\n" + "\n" + ".ace_editor .ace_print_margin_layer {\n" + " z-index: 0;\n" + " position: absolute;\n" + " overflow: hidden;\n" + " margin: 0;\n" + " left: 0;\n" + " height: 100%;\n" + " width: 100%;\n" + "}\n" + "\n" + ".ace_editor .ace_print_margin {\n" + " position: absolute;\n" + " height: 100%;\n" + "}\n" + "\n" + ".ace_editor > textarea {\n" + " position: absolute;\n" + " z-index: 0;\n" + " width: 0.5em;\n" + " height: 1em;\n" + " opacity: 0;\n" + " background: transparent;\n" + " appearance: none;\n" + " -moz-appearance: none;\n" + " border: none;\n" + " resize: none;\n" + " outline: none;\n" + " overflow: hidden;\n" + "}\n" + "\n" + ".ace_editor > textarea.ace_composition {\n" + " background: #fff;\n" + " color: #000;\n" + " z-index: 1000;\n" + " opacity: 1;\n" + " border: solid lightgray 1px;\n" + " margin: -1px\n" + "}\n" + "\n" + ".ace_layer {\n" + " z-index: 1;\n" + " position: absolute;\n" + " overflow: hidden;\n" + " white-space: nowrap;\n" + " height: 100%;\n" + " width: 100%;\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + " /* setting pointer-events: auto; on node under the mouse, which changes\n" + " during scroll, will break mouse wheel scrolling in Safari */\n" + " pointer-events: none;\n" + "}\n" + "\n" + ".ace_gutter .ace_layer {\n" + " position: relative;\n" + " min-width: 40px;\n" + " width: auto;\n" + " text-align: right;\n" + " pointer-events: auto;\n" + "}\n" + "\n" + ".ace_text-layer {\n" + " color: black;\n" + " font: inherit !important;\n" + "}\n" + "\n" + ".ace_cjk {\n" + " display: inline-block;\n" + " text-align: center;\n" + "}\n" + "\n" + ".ace_cursor-layer {\n" + " z-index: 4;\n" + "}\n" + "\n" + ".ace_cursor {\n" + " z-index: 4;\n" + " position: absolute;\n" + "}\n" + "\n" + ".ace_cursor.ace_hidden {\n" + " opacity: 0.2;\n" + "}\n" + "\n" + ".ace_editor.multiselect .ace_cursor {\n" + " border-left-width: 1px;\n" + "}\n" + "\n" + ".ace_line {\n" + " white-space: nowrap;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_step {\n" + " position: absolute;\n" + " z-index: 3;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_selection {\n" + " position: absolute;\n" + " z-index: 5;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_bracket {\n" + " position: absolute;\n" + " z-index: 6;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_active_line {\n" + " position: absolute;\n" + " z-index: 2;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_selected_word {\n" + " position: absolute;\n" + " z-index: 4;\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + "}\n" + "\n" + ".ace_line .ace_fold {\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + "\n" + " display: inline-block;\n" + " height: 11px;\n" + " margin-top: -2px;\n" + " vertical-align: middle;\n" + "\n" + " background-image:\n" + " url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n" + " url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%3AIDAT8%11c%FC%FF%FF%7F%18%03%1A%60%01%F2%3F%A0%891%80%04%FF%11-%F8%17%9BJ%E2%05%B1ZD%81v%26t%E7%80%F8%A3%82h%A12%1A%20%A3%01%02%0F%01%BA%25%06%00%19%C0%0D%AEF%D5%3ES%00%00%00%00IEND%AEB%60%82\");\n" + " background-repeat: no-repeat, repeat-x;\n" + " background-position: center center, top left;\n" + " color: transparent;\n" + "\n" + " border: 1px solid black;\n" + " -moz-border-radius: 2px;\n" + " -webkit-border-radius: 2px;\n" + " border-radius: 2px;\n" + "\n" + " cursor: pointer;\n" + " pointer-events: auto;\n" + "}\n" + "\n" + ".ace_dark .ace_fold {\n" + "}\n" + "\n" + ".ace_fold:hover{\n" + " background-image:\n" + " url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n" + " url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%003IDAT8%11c%FC%FF%FF%7F%3E%03%1A%60%01%F2%3F%A3%891%80%04%FFQ%26%F8w%C0%B43%A1%DB%0C%E2%8F%0A%A2%85%CAh%80%8C%06%08%3C%04%E8%96%18%00%A3S%0D%CD%CF%D8%C1%9D%00%00%00%00IEND%AEB%60%82\");\n" + " background-repeat: no-repeat, repeat-x;\n" + " background-position: center center, top left;\n" + "}\n" + "\n" + ".ace_dragging .ace_content {\n" + " cursor: move;\n" + "}\n" + "\n" + ".ace_folding-enabled > .ace_gutter-cell {\n" + " padding-right: 13px;\n" + "}\n" + "\n" + ".ace_fold-widget {\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + "\n" + " margin: 0 -12px 1px 1px;\n" + " display: inline-block;\n" + " height: 14px;\n" + " width: 11px;\n" + " vertical-align: text-bottom;\n" + "\n" + " background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAe%8A%B1%0D%000%0C%C2%F2%2CK%96%BC%D0%8F9%81%88H%E9%D0%0E%96%C0%10%92%3E%02%80%5E%82%E4%A9*-%EEsw%C8%CC%11%EE%96w%D8%DC%E9*Eh%0C%151(%00%00%00%00IEND%AEB%60%82\");\n" + " background-repeat: no-repeat;\n" + " background-position: center 5px;\n" + "\n" + " border-radius: 3px;\n" + "}\n" + "\n" + ".ace_fold-widget.end {\n" + " background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAm%C7%C1%09%000%08C%D1%8C%ECE%C8E(%8E%EC%02)%1EZJ%F1%C1'%04%07I%E1%E5%EE%CAL%F5%A2%99%99%22%E2%D6%1FU%B5%FE0%D9x%A7%26Wz5%0E%D5%00%00%00%00IEND%AEB%60%82\");\n" + "}\n" + "\n" + ".ace_fold-widget.closed {\n" + " background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%03%00%00%00%06%08%06%00%00%00%06%E5%24%0C%00%00%009IDATx%DA5%CA%C1%09%000%08%03%C0%AC*(%3E%04%C1%0D%BA%B1%23%A4Uh%E0%20%81%C0%CC%F8%82%81%AA%A2%AArGfr%88%08%11%11%1C%DD%7D%E0%EE%5B%F6%F6%CB%B8%05Q%2F%E9tai%D9%00%00%00%00IEND%AEB%60%82\");\n" + "}\n" + "\n" + ".ace_fold-widget:hover {\n" + " border: 1px solid rgba(0, 0, 0, 0.3);\n" + " background-color: rgba(255, 255, 255, 0.2);\n" + " -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " background-position: center 4px;\n" + "}\n" + "\n" + ".ace_fold-widget:active {\n" + " border: 1px solid rgba(0, 0, 0, 0.4);\n" + " background-color: rgba(0, 0, 0, 0.05);\n" + " -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n" + " -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n" + " -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n" + " -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n" + " box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n" + " box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n" + "}\n" + "\n" + ".ace_fold-widget.invalid {\n" + " background-color: #FFB4B4;\n" + " border-color: #DE5555;\n" + "}\n" + "\n" + ".ace_fade-fold-widgets .ace_fold-widget {\n" + " -moz-transition: opacity 0.4s ease 0.05s;\n" + " -webkit-transition: opacity 0.4s ease 0.05s;\n" + " -o-transition: opacity 0.4s ease 0.05s;\n" + " -ms-transition: opacity 0.4s ease 0.05s;\n" + " transition: opacity 0.4s ease 0.05s;\n" + " opacity: 0;\n" + "}\n" + "\n" + ".ace_fade-fold-widgets:hover .ace_fold-widget {\n" + " -moz-transition: opacity 0.05s ease 0.05s;\n" + " -webkit-transition: opacity 0.05s ease 0.05s;\n" + " -o-transition: opacity 0.05s ease 0.05s;\n" + " -ms-transition: opacity 0.05s ease 0.05s;\n" + " transition: opacity 0.05s ease 0.05s;\n" + " opacity:1;\n" + "}\n" + ""); define('ace/multi_select', ['require', 'exports', 'module' , 'ace/range_list', 'ace/range', 'ace/selection', 'ace/mouse/multi_select_handler', 'ace/lib/event', 'ace/commands/multi_select_commands', 'ace/search', 'ace/edit_session', 'ace/editor'], 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 commands = require("./commands/multi_select_commands"); exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands); // Todo: session.find or editor.findVolatile that returns range 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); } // extend EditSession var EditSession = require("./edit_session").EditSession; (function() { this.getSelectionMarkers = function() { return this.$selectionMarkers; }; }).call(EditSession.prototype); // extend Selection (function() { // list of ranges in reverse addition order this.ranges = null; // automatically sorted list of ranges this.rangeList = null; this.addRange = function(range, $blockChangeEvents) { if (!range) return; if (!this.inMultiSelectMode && this.rangeCount == 0) { var oldRange = this.toOrientedRange(); if (range.intersects(oldRange)) return $blockChangeEvents || this.fromOrientedRange(range); 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._emit("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._emit("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._emit("removeRange", {ranges: removed}); if (this.rangeCount == 0 && this.inMultiSelectMode) { this.inMultiSelectMode = false; this._emit("singleSelect"); this.session.$undoSelect = true; this.rangeList.detach(this.session); } lastRange = lastRange || this.ranges[0]; if (lastRange && !lastRange.isEqual(this.getRange())) this.fromOrientedRange(lastRange); }; // adds multicursor support to selection this.$initRangeList = function() { if (this.rangeList) return; this.rangeList = new RangeList(); this.ranges = []; this.rangeCount = 0; }; this.getAllRanges = function() { return this.rangeList.ranges.concat(); }; 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 startRow = range.start.row; var endRow = range.end.row; if (startRow == endRow) 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); // extend Editor var Editor = require("./editor").Editor; (function() { /** extension * Editor.updateSelectionMarkers() * * Updates the cursor and marker layers. **/ 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("multiselect"); this.keyBinding.addKeyboardHandler(commands.keyboardHandler); this.commands.on("exec", this.$onMultiSelectExec); this.renderer.updateCursor(); this.renderer.updateBackMarkers(); }; this.$onSingleSelect = function(e) { if (this.session.multiSelect.inVirtualMode) return; this.inMultiSelectMode = false; this.unsetStyle("multiselect"); this.keyBinding.removeKeyboardHandler(commands.keyboardHandler); this.commands.removeEventListener("exec", this.$onMultiSelectExec); this.renderer.updateCursor(); this.renderer.updateBackMarkers(); }; this.$onMultiSelectExec = function(e) { var command = e.command; var editor = e.editor; if (!editor.multiSelect) return; if (!command.multiSelectAction) { command.exec(editor, e.args || {}); editor.multiSelect.addRange(editor.multiSelect.toOrientedRange()); editor.multiSelect.mergeOverlappingRanges(); } else if (command.multiSelectAction == "forEach") { editor.forEachSelection(command, e.args); } else if (command.multiSelectAction == "single") { editor.exitMultiSelectMode(); command.exec(editor, e.args || {}); } else { command.multiSelectAction(editor, e.args || {}); } e.preventDefault(); }; this.forEachSelection = function(cmd, args) { if (this.inVirtualSelectionMode) return; var session = this.session; var selection = this.selection; var rangeList = selection.rangeList; var reg = selection._eventRegistry; selection._eventRegistry = {}; var tmpSel = new Selection(session); this.inVirtualSelectionMode = true; for (var i = rangeList.ranges.length; i--;) { tmpSel.fromOrientedRange(rangeList.ranges[i]); this.selection = session.selection = tmpSel; cmd.exec(this, args || {}); tmpSel.toOrientedRange(rangeList.ranges[i]); } tmpSel.detach(); this.selection = session.selection = selection; this.inVirtualSelectionMode = false; selection._eventRegistry = reg; selection.mergeOverlappingRanges(); this.onCursorChange(); this.onSelectionChange(); }; this.exitMultiSelectMode = function() { if (this.inVirtualSelectionMode) return; this.multiSelect.toSingleRange(); }; this.getCopyText = function() { var text = ""; if (this.inMultiSelectMode) { var ranges = this.multiSelect.rangeList.ranges; text = []; for (var i = 0; i < ranges.length; i++) { text.push(this.session.getTextRange(ranges[i])); } text = text.join(this.session.getDocument().getNewLineCharacter()); } else if (!this.selection.isEmpty()) { text = this.session.getTextRange(this.getSelectionRange()); } return text; }; this.onPaste = function(text) { this._emit("paste", text); if (!this.inMultiSelectMode) return this.insert(text); 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.findAll = function(needle, options, additive) { options = options || {}; options.needle = needle || options.needle; 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); this.$blockScrolling -= 1; return ranges.length; }; // commands /** extension * Editor.selectMoreLines(dir, skip) * - dir (Number): The direction of lines to select: -1 for up, 1 for down * - skip (Boolean): If `true`, removes the active selection range * * Adds a cursor above or below the active cursor. **/ 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; } } /** extension * Editor.selectMore(dir, skip) * - dir (Number): The direction of lines to select: -1 for up, 1 for down * - skip (Boolean): If `true`, removes the active selection range * * Finds the next occurence of text in an active selection and adds it to the selections. **/ this.selectMore = function (dir, skip) { var session = this.session; var sel = session.multiSelect; var range = sel.toOrientedRange(); if (range.isEmpty()) { var range = session.getWordRange(range.start.row, range.start.column); range.cursor = range.end; this.multiSelect.addRange(range); } var needle = session.getTextRange(range); var newRange = find(session, needle, dir); if (newRange) { newRange.cursor = dir == -1 ? newRange.start : newRange.end; this.multiSelect.addRange(newRange); } if (skip) this.multiSelect.substractPoint(range.cursor); }; }).call(Editor.prototype); function isSamePoint(p1, p2) { return p1.row == p2.row && p1.column == p2.column; } // patch // adds multicursor support to a session exports.onSessionChange = function(e) { var session = e.session; if (!session.multiSelect) { session.$selectionMarkers = []; session.selection.$initRangeList(); session.multiSelect = session.selection; } this.multiSelect = session.multiSelect; var oldSession = e.oldSession; if (oldSession) { // todo use events if (oldSession.multiSelect && oldSession.multiSelect.editor == this) oldSession.multiSelect.editor = null; session.multiSelect.removeEventListener("addRange", this.$onAddRange); session.multiSelect.removeEventListener("removeRange", this.$onRemoveRange); session.multiSelect.removeEventListener("multiSelect", this.$onMultiSelect); session.multiSelect.removeEventListener("singleSelect", this.$onSingleSelect); } session.multiSelect.on("addRange", this.$onAddRange); session.multiSelect.on("removeRange", this.$onRemoveRange); session.multiSelect.on("multiSelect", this.$onMultiSelect); session.multiSelect.on("singleSelect", this.$onSingleSelect); // this.$onSelectionChange = this.onSelectionChange.bind(this); if (this.inMultiSelectMode != session.selection.inMultiSelectMode) { if (session.selection.inMultiSelectMode) this.$onMultiSelect(); else this.$onSingleSelect(); } }; // MultiSelect(editor) // adds multiple selection support to the editor // (note: should be called only once for each editor instance) function MultiSelect(editor) { editor.$onAddRange = editor.$onAddRange.bind(editor); editor.$onRemoveRange = editor.$onRemoveRange.bind(editor); editor.$onMultiSelect = editor.$onMultiSelect.bind(editor); editor.$onSingleSelect = editor.$onSingleSelect.bind(editor); exports.onSessionChange.call(editor, editor); editor.on("changeSession", exports.onSessionChange.bind(editor)); editor.on("mousedown", onMouseDown); editor.commands.addCommands(commands.defaultCommands); addAltCursorListeners(editor); } function addAltCursorListeners(editor){ var el = editor.textInput.getElement(); var altCursor = false; var contentEl = editor.renderer.content; event.addListener(el, "keydown", function(e) { if (e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey)) { if (!altCursor) { contentEl.style.cursor = "crosshair"; altCursor = true; } } else if (altCursor) { contentEl.style.cursor = ""; } }); event.addListener(el, "keyup", reset); event.addListener(el, "blur", reset); function reset() { if (altCursor) { contentEl.style.cursor = ""; altCursor = false; } } } exports.MultiSelect = MultiSelect; }); define('ace/range_list', ['require', 'exports', 'module' ], function(require, exports, module) { var RangeList = function() { this.ranges = []; }; (function() { this.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; this.pointIndex = function(pos, startIndex) { var list = this.ranges; for (var i = startIndex || 0; i < list.length; i++) { var range = list[i]; var cmp = this.comparePoints(pos, range.end); if (cmp > 0) continue; if (cmp == 0) return i; cmp = this.comparePoints(pos, range.start); if (cmp >= 0) return i; return -i-1; } return -i - 1; }; this.add = function(range) { var startIndex = this.pointIndex(range.start); if (startIndex < 0) startIndex = -startIndex - 1; var endIndex = this.pointIndex(range.end, 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.call(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); }; // merge overlapping ranges this.merge = function() { var removed = []; var list = this.ranges; var next = list[0], range; for (var i = 1; i < list.length; i++) { range = next; next = list[i]; var cmp = this.comparePoints(range.end, next.start); if (cmp < 0) continue; if (cmp == 0 && !(range.isEmpty() || next.isEmpty())) continue; if (this.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--; } 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(e) { var changeRange = e.data.range; if (e.data.action[0] == "i"){ var start = changeRange.start; var end = changeRange.end; } else { var end = changeRange.start; var start = changeRange.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 ) { r.start.column += colDiff; r.start.row += lineDif; } if (r.end.row == startRow && r.end.column >= start.column) { 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; }); define('ace/mouse/multi_select_handler', ['require', 'exports', 'module' , 'ace/lib/event'], function(require, exports, module) { var event = require("../lib/event"); // mouse 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 = e.getAccelKey(); var button = e.getButton(); if (!ctrl && !alt) { if (e.editor.inMultiSelectMode) { if (button == 0) { e.editor.exitMultiSelectMode(); } else if (button == 2) { var editor = e.editor; var selectionEmpty = editor.selection.isEmpty(); editor.textInput.onContextMenu({x: e.clientX, y: e.clientY}, selectionEmpty); event.capture(editor.container, function(){}, editor.textInput.onContextMenuClose); e.stop(); } } 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 blockSelect = function() { var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column); if (isSamePoint(screenCursor, newCursor) && isSamePoint(cursor, selection.selectionLead)) return; screenCursor = newCursor; editor.selection.moveCursorToPosition(cursor); editor.selection.clearSelection(); editor.renderer.scrollCursorIntoView(); editor.removeSelectionMarkers(rectSel); rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor); rectSel.forEach(editor.addSelectionMarker, editor); editor.updateSelectionMarkers(); }; var session = editor.session; var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); var screenCursor = screenAnchor; if (ctrl && !shift && !alt && button == 0) { if (!isMultiSelect && inSelection) return; // dragging if (!isMultiSelect) { var range = selection.toOrientedRange(); editor.addSelectionMarker(range); } var oldRange = selection.rangeList.rangeAtPoint(pos); event.capture(editor.container, function(){}, function() { var tmpSel = selection.toOrientedRange(); if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor)) selection.substractPoint(tmpSel.cursor); else { if (range) { editor.removeSelectionMarker(range); selection.addRange(range); } selection.addRange(tmpSel); } }); } else if (!shift && alt && button == 0) { e.stop(); if (isMultiSelect && !ctrl) selection.toSingleRange(); else if (!isMultiSelect && ctrl) selection.addRange(); selection.moveCursorToPosition(pos); selection.clearSelection(); var rectSel = []; var onMouseSelectionEnd = function(e) { clearInterval(timerId); editor.removeSelectionMarkers(rectSel); for (var i = 0; i < rectSel.length; i++) selection.addRange(rectSel[i]); }; var onSelectionInterval = blockSelect; event.capture(editor.container, onMouseSelection, onMouseSelectionEnd); var timerId = setInterval(function() {onSelectionInterval();}, 20); return e.preventDefault(); } } exports.onMouseDown = onMouseDown; }); define('ace/commands/multi_select_commands', ['require', 'exports', 'module' , 'ace/keyboard/hash_handler'], function(require, exports, module) { // commands to enter multiselect mode exports.defaultCommands = [{ name: "addCursorAbove", exec: function(editor) { editor.selectMoreLines(-1); }, bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"}, readonly: true }, { name: "addCursorBelow", exec: function(editor) { editor.selectMoreLines(1); }, bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"}, readonly: true }, { name: "addCursorAboveSkipCurrent", exec: function(editor) { editor.selectMoreLines(-1, true); }, bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"}, readonly: true }, { name: "addCursorBelowSkipCurrent", exec: function(editor) { editor.selectMoreLines(1, true); }, bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"}, readonly: true }, { name: "selectMoreBefore", exec: function(editor) { editor.selectMore(-1); }, bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"}, readonly: true }, { name: "selectMoreAfter", exec: function(editor) { editor.selectMore(1); }, bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"}, readonly: true }, { name: "selectNextBefore", exec: function(editor) { editor.selectMore(-1, true); }, bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"}, readonly: true }, { name: "selectNextAfter", exec: function(editor) { editor.selectMore(1, true); }, bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"}, readonly: true }, { name: "splitIntoLines", exec: function(editor) { editor.multiSelect.splitIntoLines(); }, bindKey: {win: "Ctrl-Shift-L", mac: "Ctrl-Shift-L"}, readonly: true }]; // commands active in multiselect mode exports.multiSelectCommands = [{ name: "singleSelection", bindKey: "esc", exec: function(editor) { editor.exitMultiSelectMode(); }, readonly: true, isAvailable: function(editor) {return editor.inMultiSelectMode} }]; var HashHandler = require("../keyboard/hash_handler").HashHandler; exports.keyboardHandler = new HashHandler(exports.multiSelectCommands); }); define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/config'], function(require, exports, module) { var oop = require("../lib/oop"); var EventEmitter = require("../lib/event_emitter").EventEmitter; var config = require("../config"); var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { this.changeListener = this.changeListener.bind(this); if (config.get("packaged")) { this.$worker = new Worker(config.get("workerPath") + "/" + packagedJs); } else { var workerUrl; if (typeof require.supports !== "undefined" && require.supports.indexOf("ucjs2-pinf-0") >= 0) { // We are running in the sourcemint loader. workerUrl = require.nameToUrl("ace/worker/worker_sourcemint"); } else { // We are running in RequireJS. workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); } this.$worker = new Worker(workerUrl); var tlns = {}; for (var i=0; i<topLevelNamespaces.length; i++) { var ns = topLevelNamespaces[i]; var path = this.$normalizePath(require.nameToUrl(ns, null, "_").replace(/.js$/, "")); tlns[ns] = path; } } this.$worker.postMessage({ init : true, tlns: tlns, module: mod, classname: classname }); this.callbackId = 1; this.callbacks = {}; var _self = this; this.$worker.onerror = function(e) { window.console && console.log && console.log(e); throw e; }; this.$worker.onmessage = function(e) { var msg = e.data; switch(msg.type) { case "log": window.console && console.log && console.log(msg.data); break; case "event": _self._emit(msg.name, {data: msg.data}); break; case "call": var callback = _self.callbacks[msg.id]; if (callback) { callback(msg.data); delete _self.callbacks[msg.id]; } break; } }; }; (function(){ oop.implement(this, EventEmitter); this.$normalizePath = function(path) { path = path.replace(/^[a-z]+:\/\/[^\/]+/, ""); // Remove domain name and rebuild it path = location.protocol + "//" + location.host // paths starting with a slash are relative to the root (host) + (path.charAt(0) == "/" ? "" : location.pathname.replace(/\/[^\/]*$/, "")) + "/" + path.replace(/^[\/]+/, ""); return path; }; this.terminate = function() { this._emit("terminate", {}); this.$worker.terminate(); this.$worker = null; this.$doc.removeEventListener("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 { // firefox refuses to clone objects which have function properties // TODO: cleanup event this.$worker.postMessage({event: event, data: {data: data.data}}); } catch(ex) {} }; 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(e) { e.range = { start: e.data.range.start, end: e.data.range.end }; this.emit("change", e); }; }).call(WorkerClient.prototype); exports.WorkerClient = WorkerClient; }); define('ace/keyboard/state_handler', ['require', 'exports', 'module' ], function(require, exports, module) { // If you're developing a new keymapping and want to get an idea what's going // on, then enable debugging. var DEBUG = false; function StateHandler(keymapping) { this.keymapping = this.$buildKeymappingRegex(keymapping); } StateHandler.prototype = { /* * Build the RegExp from the keymapping as RegExp can't stored directly * in the metadata JSON and as the RegExp used to match the keys/buffer * need to be adapted. */ $buildKeymappingRegex: function(keymapping) { for (var state in keymapping) { this.$buildBindingsRegex(keymapping[state]); } return keymapping; }, $buildBindingsRegex: function(bindings) { // Escape a given Regex string. bindings.forEach(function(binding) { if (binding.key) { binding.key = new RegExp('^' + binding.key + '$'); } else if (Array.isArray(binding.regex)) { if (!('key' in binding)) binding.key = new RegExp('^' + binding.regex[1] + '$'); binding.regex = new RegExp(binding.regex.join('') + '$'); } else if (binding.regex) { binding.regex = new RegExp(binding.regex + '$'); } }); }, $composeBuffer: function(data, hashId, key, e) { // Initialize the data object. if (data.state == null || data.buffer == null) { data.state = "start"; data.buffer = ""; } var keyArray = []; if (hashId & 1) keyArray.push("ctrl"); if (hashId & 8) keyArray.push("command"); if (hashId & 2) keyArray.push("option"); if (hashId & 4) keyArray.push("shift"); if (key) keyArray.push(key); var symbolicName = keyArray.join("-"); var bufferToUse = data.buffer + symbolicName; // Don't add the symbolic name to the key buffer if the alt_ key is // part of the symbolic name. If it starts with alt_, this means // that the user hit an alt keycombo and there will be a single, // new character detected after this event, which then will be // added to the buffer (e.g. alt_j will result in ∆). // // We test for 2 and not for & 2 as we only want to exclude the case where // the option key is pressed alone. if (hashId != 2) { data.buffer = bufferToUse; } var bufferObj = { bufferToUse: bufferToUse, symbolicName: symbolicName, }; if (e) { bufferObj.keyIdentifier = e.keyIdentifier } return bufferObj; }, $find: function(data, buffer, symbolicName, hashId, key, keyIdentifier) { // Holds the command to execute and the args if a command matched. var result = {}; // Loop over all the bindings of the keymap until a match is found. this.keymapping[data.state].some(function(binding) { var match; // Check if the key matches. if (binding.key && !binding.key.test(symbolicName)) { return false; } // Check if the regex matches. if (binding.regex && !(match = binding.regex.exec(buffer))) { return false; } // Check if the match function matches. if (binding.match && !binding.match(buffer, hashId, key, symbolicName, keyIdentifier)) { return false; } // Check for disallowed matches. if (binding.disallowMatches) { for (var i = 0; i < binding.disallowMatches.length; i++) { if (!!match[binding.disallowMatches[i]]) { return false; } } } // If there is a command to execute, then figure out the // command and the arguments. if (binding.exec) { result.command = binding.exec; // Build the arguments. if (binding.params) { var value; result.args = {}; binding.params.forEach(function(param) { if (param.match != null && match != null) { value = match[param.match] || param.defaultValue; } else { value = param.defaultValue; } if (param.type === 'number') { value = parseInt(value); } result.args[param.name] = value; }); } data.buffer = ""; } // Handle the 'then' property. if (binding.then) { data.state = binding.then; data.buffer = ""; } // If no command is set, then execute the "null" fake command. if (result.command == null) { result.command = "null"; } if (DEBUG) { console.log("KeyboardStateMapper#find", binding); } return true; }); if (result.command) { return result; } else { data.buffer = ""; return false; } }, /* * This function is called by keyBinding. */ handleKeyboard: function(data, hashId, key, keyCode, e) { if (hashId == -1) hashId = 0 // If we pressed any command key but no other key, then ignore the input. // Otherwise "shift-" is added to the buffer, and later on "shift-g" // which results in "shift-shift-g" which doesn't make sense. if (hashId != 0 && (key == "" || key == String.fromCharCode(0))) { return null; } // Compute the current value of the keyboard input buffer. var r = this.$composeBuffer(data, hashId, key, e); var buffer = r.bufferToUse; var symbolicName = r.symbolicName; var keyId = r.keyIdentifier; r = this.$find(data, buffer, symbolicName, hashId, key, keyId); if (DEBUG) { console.log("KeyboardStateMapper#match", buffer, symbolicName, r); } return r; } } /* * This is a useful matching function and therefore is defined here so that * users of KeyboardStateMapper can use it. * * @return boolean * If no command key (Command|Option|Shift|Ctrl) is pressed, it * returns true. If the only the Shift key is pressed + a character * true is returned as well. Otherwise, false is returned. * Summing up, the function returns true whenever the user typed * a normal character on the keyboard and no shortcut. */ exports.matchCharacterOnly = function(buffer, hashId, key, symbolicName) { // If no command keys are pressed, then catch the input. if (hashId == 0) { return true; } // If only the shift key is pressed and a character key, then // catch that input as well. else if ((hashId == 4) && key.length == 1) { return true; } // Otherwise, we let the input got through. else { return false; } }; exports.StateHandler = StateHandler; }); define('ace/placeholder', ['require', 'exports', 'module' , 'ace/range', 'ace/lib/event_emitter', 'ace/lib/oop'], function(require, exports, module) { var Range = require('./range').Range; var EventEmitter = require("./lib/event_emitter").EventEmitter; var oop = require("./lib/oop"); /** * new PlaceHolder(session, length, pos, others, mainClass, othersClass) * - session (Document): The document to associate with the anchor * - length (Number): The starting row position * - pos (Number): The starting column position * - others (String): * - mainClass (String): * - othersClass (String): * * TODO * **/ 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; // Used for reset 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; var pos = this.$pos; this.pos = doc.createAnchor(pos.row, pos.column); this.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false); this.pos.on("change", function(event) { session.removeMarker(_self.markerId); _self.markerId = session.addMarker(new Range(event.value.row, event.value.column, event.value.row, event.value.column+_self.length), _self.mainClass, null, false); }); this.others = []; this.$others.forEach(function(other) { var anchor = doc.createAnchor(other.row, other.column); _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); anchor.on("change", function(event) { session.removeMarker(anchor.markerId); anchor.markerId = session.addMarker(new Range(event.value.row, event.value.column, event.value.row, event.value.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(event) { var delta = event.data; var range = delta.range; if(range.start.row !== range.end.row) return; if(range.start.row !== this.pos.row) return; if (this.$updating) return; this.$updating = true; var lengthDiff = delta.action === "insertText" ? range.end.column - range.start.column : range.start.column - range.end.column; if(range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1) { var distanceFromStart = range.start.column - this.pos.column; this.length += lengthDiff; if(!this.session.$fromUndo) { if(delta.action === "insertText") { for (var i = this.others.length - 1; i >= 0; i--) { var otherPos = this.others[i]; var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; if(otherPos.row === range.start.row && range.start.column < otherPos.column) newPos.column += lengthDiff; this.doc.insert(newPos, delta.text); } } else if(delta.action === "removeText") { for (var i = this.others.length - 1; i >= 0; i--) { var otherPos = this.others[i]; var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; if(otherPos.row === range.start.row && range.start.column < otherPos.column) newPos.column += lengthDiff; this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff)); } } // Special case: insert in beginning if(range.start.column === this.pos.column && delta.action === "insertText") { setTimeout(function() { this.pos.setPosition(this.pos.row, this.pos.column - lengthDiff); for (var i = 0; i < this.others.length; i++) { var other = this.others[i]; var newPos = {row: other.row, column: other.column - lengthDiff}; if(other.row === range.start.row && range.start.column < other.column) newPos.column += lengthDiff; other.setPosition(newPos.row, newPos.column); } }.bind(this), 0); } else if(range.start.column === this.pos.column && delta.action === "removeText") { setTimeout(function() { for (var i = 0; i < this.others.length; i++) { var other = this.others[i]; if(other.row === range.start.row && range.start.column < other.column) { other.setPosition(other.row, other.column - lengthDiff); } } }.bind(this), 0); } } this.pos._emit("change", {value: this.pos}); for (var i = 0; i < this.others.length; i++) { this.others[i]._emit("change", {value: this.others[i]}); } } this.$updating = false; }; this.onCursorChange = function(event) { if (this.$updating) 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.markerId); this.hideOtherMarkers(); this.doc.removeEventListener("change", this.$onUpdate); this.session.selection.removeEventListener("changeCursor", this.$onCursorChange); this.pos.detach(); for (var i = 0; i < this.others.length; i++) { this.others[i].detach(); } this.session.setUndoSelect(true); }; this.cancel = function() { if(this.$undoStackDepth === -1) throw Error("Canceling placeholders only supported with undo manager attached to session."); var undoManager = this.session.getUndoManager(); var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth; for (var i = 0; i < undosRequired; i++) { undoManager.undo(true); } }; }).call(PlaceHolder.prototype); exports.PlaceHolder = PlaceHolder; }); define('ace/theme/textmate', ['require', 'exports', 'module' , 'text!ace/theme/textmate.css', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-tm"; exports.cssText = require('text!./textmate.css'); var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); }); define("text!ace/theme/textmate.css", [], ".ace-tm .ace_editor {\n" + " border: 2px solid rgb(159, 159, 159);\n" + "}\n" + "\n" + ".ace-tm .ace_editor.ace_focus {\n" + " border: 2px solid #327fbd;\n" + "}\n" + "\n" + ".ace-tm .ace_gutter {\n" + " background: #e8e8e8;\n" + " color: #333;\n" + "}\n" + "\n" + ".ace-tm .ace_print_margin {\n" + " width: 1px;\n" + " background: #e8e8e8;\n" + "}\n" + "\n" + ".ace-tm .ace_fold {\n" + " background-color: #6B72E6;\n" + "}\n" + "\n" + ".ace-tm .ace_text-layer {\n" + " cursor: text;\n" + "}\n" + "\n" + ".ace-tm .ace_cursor {\n" + " border-left: 2px solid black;\n" + "}\n" + "\n" + ".ace-tm .ace_cursor.ace_overwrite {\n" + " border-left: 0px;\n" + " border-bottom: 1px solid black;\n" + "}\n" + " \n" + ".ace-tm .ace_line .ace_invisible {\n" + " color: rgb(191, 191, 191);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_storage,\n" + ".ace-tm .ace_line .ace_keyword {\n" + " color: blue;\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant {\n" + " color: rgb(197, 6, 11);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant.ace_buildin {\n" + " color: rgb(88, 72, 246);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant.ace_language {\n" + " color: rgb(88, 92, 246);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant.ace_library {\n" + " color: rgb(6, 150, 14);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_invalid {\n" + " background-color: rgba(255, 0, 0, 0.1);\n" + " color: red;\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_support.ace_function {\n" + " color: rgb(60, 76, 114);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_support.ace_constant {\n" + " color: rgb(6, 150, 14);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_support.ace_type,\n" + ".ace-tm .ace_line .ace_support.ace_class {\n" + " color: rgb(109, 121, 222);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_keyword.ace_operator {\n" + " color: rgb(104, 118, 135);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_string {\n" + " color: rgb(3, 106, 7);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_comment {\n" + " color: rgb(76, 136, 107);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_comment.ace_doc {\n" + " color: rgb(0, 102, 255);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_comment.ace_doc.ace_tag {\n" + " color: rgb(128, 159, 191);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant.ace_numeric {\n" + " color: rgb(0, 0, 205);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_variable {\n" + " color: rgb(49, 132, 149);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_xml_pe {\n" + " color: rgb(104, 104, 91);\n" + "}\n" + "\n" + ".ace-tm .ace_entity.ace_name.ace_function {\n" + " color: #0000A2;\n" + "}\n" + "\n" + ".ace-tm .ace_markup.ace_markupine {\n" + " text-decoration:underline;\n" + "}\n" + "\n" + ".ace-tm .ace_markup.ace_heading {\n" + " color: rgb(12, 7, 255);\n" + "}\n" + "\n" + ".ace-tm .ace_markup.ace_list {\n" + " color:rgb(185, 6, 144);\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_selection {\n" + " background: rgb(181, 213, 255);\n" + "}\n" + ".ace-tm.multiselect .ace_selection.start {\n" + " box-shadow: 0 0 3px 0px white;\n" + " border-radius: 2px;\n" + "}\n" + ".ace-tm .ace_marker-layer .ace_step {\n" + " background: rgb(252, 255, 0);\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_stack {\n" + " background: rgb(164, 229, 101);\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_bracket {\n" + " margin: -1px 0 0 -1px;\n" + " border: 1px solid rgb(192, 192, 192);\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_active_line {\n" + " background: rgba(0, 0, 0, 0.07);\n" + "}\n" + ".ace-tm .ace_gutter_active_line{\n" + " background-color : #dcdcdc;\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_selected_word {\n" + " background: rgb(250, 250, 255);\n" + " border: 1px solid rgb(200, 200, 250);\n" + "}\n" + "\n" + ".ace-tm .ace_meta.ace_tag {\n" + " color:rgb(0, 50, 198);\n" + "}\n" + "\n" + ".ace-tm .ace_string.ace_regex {\n" + " color: rgb(255, 0, 0)\n" + "}"); ; (function() { window.require(["ace/ace"], function(a) { a && a.config.init(); if (!window.ace) window.ace = {}; for (var key in a) if (a.hasOwnProperty(key)) ace[key] = a[key]; }); })();
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/ace.js
JavaScript
asf20
533,732
"no use strict"; var console = { log: function(msg) { postMessage({type: "log", data: msg}); } }; var window = { console: console }; 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("/"); var moduleName = base + "/" + moduleName; while(moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; var moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; var require = function(parentId, id) { var id = normalizeModule(parentId, id); var module = require.modules[id]; if (module) { if (!module.initialized) { module.exports = module.factory().exports; module.initialized = true; } return module.exports; } var chunks = id.split("/"); chunks[0] = require.tlns[chunks[0]] || chunks[0]; var path = chunks.join("/") + ".js"; require.id = id; importScripts(path); return require(parentId, id); }; require.modules = {}; require.tlns = {}; var define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; } else if (arguments.length == 1) { factory = id; id = require.id; } if (id.indexOf("text!") === 0) return; var req = function(deps, factory) { return require(id, deps, factory); }; require.modules[id] = { factory: function() { var module = { exports: {} }; var returnExports = factory(req, module.exports, module); if (returnExports) module.exports = returnExports; return module; } }; }; function initBaseUrls(topLevelNamespaces) { require.tlns = topLevelNamespaces; } function initSender() { var EventEmitter = require(null, "ace/lib/event_emitter").EventEmitter; var oop = require(null, "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; var sender; onmessage = function(e) { var msg = e.data; if (msg.command) { main[msg.command].apply(main, msg.args); } else if (msg.init) { initBaseUrls(msg.tlns); require(null, "ace/lib/fixoldbrowsers"); sender = initSender(); var clazz = require(null, msg.module)[msg.classname]; main = new clazz(sender); } else if (msg.event && sender) { sender._emit(msg.event, msg.data); } }; // vim:set ts=4 sts=4 sw=4 st: // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Irakli Gozalishvili Copyright (C) 2010 MIT License /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) { require("./regexp"); require("./es5-shim"); }); define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) { //--------------------------------- // Private variables //--------------------------------- 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; //--------------------------------- // Overriden native methods //--------------------------------- // Adds named capture support (with backreferences returned as `result.name`), and fixes two // cross-browser issues per ES3: // - Captured values for nonparticipating capturing groups should be returned as `undefined`, // rather than the empty string. // - `lastIndex` should not be incremented after zero-length matches. RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed // matching due to characters outside the match 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; } }); } // Attach named capture properties 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]; } } // Fix browsers that increment `lastIndex` after zero-length matches if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; } return match; }; // Don't override `test` if it won't change anything if (!compliantLastIndexIncrement) { // Fix browser bug in native method RegExp.prototype.test = function (str) { // Use the native `exec` to skip some processing overhead, even though the overriden // `exec` would take care of the `lastIndex` fix var match = real.exec.call(this, str); // Fix browsers that increment `lastIndex` after zero-length matches if (match && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; return !!match; }; } //--------------------------------- // Private helper functions //--------------------------------- 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; }; }); // vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License // -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License // -- kossnocorp Sasha Koss XXX TODO License or CLA // -- bryanforbes Bryan Forbes XXX TODO License or CLA // -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence // -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License // -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License // -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain) // -- iwyg XXX TODO License or CLA // -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License // -- xavierm02 Montillet Xavier XXX TODO License or CLA // -- Raynos Raynos XXX TODO License or CLA // -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License // -- rwldrn Rick Waldron Copyright (C) 2011 MIT License // -- lexer Alexey Zakharov XXX TODO License or CLA /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) { /* * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * * @module */ /*whatsupdoc*/ // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (typeof target != "function") throw new TypeError(); // TODO message // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){}; F.prototype = target.prototype; var self = new F; var result = target.apply( self, args.concat(slice.call(arguments)) ); if (result !== null && Object(result) === result) return result; return self; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(slice.call(arguments)) ); } }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. 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); // If JS engine supports accessors creating shortcuts. 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__); } // // Array // ===== // // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function isArray(obj) { return toString(obj) == "[object Array]"; }; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var self = toObject(this), thisp = arguments[1], i = 0, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object context fun.call(thisp, self[i], i, self); } i++; } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var self = toObject(this), length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, self); } return result; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, result = [], thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) result.push(self[i]); } return result; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, self)) return false; } return true; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) return true; } return false; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value and an empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) throw new TypeError(); // TODO message } while (true); } for (; i < length; i++) { if (i in self) result = fun.call(void 0, result, self[i], i, self); } return result; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value, empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) throw new TypeError(); // TODO message } while (true); } do { if (i in this) result = fun.call(void 0, result, self[i], i, self); } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = toObject(this), length = self.length >>> 0; if (!length) return -1; var i = 0; if (arguments.length > 1) i = toInteger(arguments[1]); // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = 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])); // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) return i; } return -1; }; } // // Object // ====== // // ES5 15.2.3.2 // http://es5.github.com/#x15.2.3.2 if (!Object.getPrototypeOf) { // https://github.com/kriskowal/es5-shim/issues#issue/2 // http://ejohn.org/blog/objectgetprototypeof/ // recommended by fschaefer on github Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } // ES5 15.2.3.3 // http://es5.github.com/#x15.2.3.3 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 object does not owns property return undefined immediately. if (!owns(object, property)) return; var descriptor, getter, setter; // If object has a property then it's for sure both `enumerable` and // `configurable`. descriptor = { enumerable: true, configurable: true }; // If JS engine supports accessor properties then property may be a // getter or setter. if (supportsAccessors) { // Unfortunately `__lookupGetter__` will return a getter even // if object has own non getter property along with a same named // inherited getter. To avoid misbehavior we temporary remove // `__proto__` so that `__lookupGetter__` will return getter only // if it's owned by an object. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); // Once we have getter and setter we can put values back. object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; // If it was accessor property we're done and return here // in order to avoid adding `value` to the descriptor. return descriptor; } } // If we got this far we know that object has an own property that is // not an accessor so we set it as a value and return descriptor. descriptor.value = object[property]; return descriptor; }; } // ES5 15.2.3.4 // http://es5.github.com/#x15.2.3.4 if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!Object.create) { Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = { "__proto__": null }; } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); // IE has no built-in implementation of `Object.getPrototypeOf` // neither `__proto__`, but this manually setting `__proto__` will // guarantee that `Object.getPrototypeOf` will work as expected with // objects created using `Object.create` object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } // ES5 15.2.3.6 // http://es5.github.com/#x15.2.3.6 // Patch for WebKit and IE8 standard mode // Designed by hax <hax.github.com> // related issue: https://github.com/kriskowal/es5-shim/issues#issue/5 // IE8 Reference: // http://msdn.microsoft.com/en-us/library/dd282900.aspx // http://msdn.microsoft.com/en-us/library/dd229916.aspx // WebKit Bugs: // https://bugs.webkit.org/show_bug.cgi?id=36423 function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { // returns falsy } } // check whether defineProperty works if it's given. Otherwise, // shim partially. 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); // make a valiant attempt to use the real defineProperty // for I8's DOM elements. if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { // try the shim if the real one doesn't work } } // If it's a data property. if (owns(descriptor, "value")) { // fail silently if "writable", "enumerable", or "configurable" // are requested but not supported /* // alternate approach: if ( // can't implement these features; allow false but not true !(owns(descriptor, "writable") ? descriptor.writable : true) || !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) || !(owns(descriptor, "configurable") ? descriptor.configurable : true) ) throw new RangeError( "This implementation of Object.defineProperty does not " + "support configurable, enumerable, or writable." ); */ if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { // As accessors are supported only on engines implementing // `__proto__` we can safely override `__proto__` while defining // a property to make sure that we don't hit an inherited // accessor. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; // Deleting a property anyway since getter / setter may be // defined on object itself. delete object[property]; object[property] = descriptor.value; // Setting original `__proto__` back now. object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); // If we got that far then getters and setters can be defined !! if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 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; }; } // ES5 15.2.3.8 // http://es5.github.com/#x15.2.3.8 if (!Object.seal) { Object.seal = function seal(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.9 // http://es5.github.com/#x15.2.3.9 if (!Object.freeze) { Object.freeze = function freeze(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // detect a Rhino bug and patch it 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); } // ES5 15.2.3.10 // http://es5.github.com/#x15.2.3.10 if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.11 // http://es5.github.com/#x15.2.3.11 if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } // ES5 15.2.3.12 // http://es5.github.com/#x15.2.3.12 if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } // ES5 15.2.3.13 // http://es5.github.com/#x15.2.3.13 if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { // 1. If Type(O) is not Object throw a TypeError exception. if (Object(object) === object) { throw new TypeError(); // TODO message } // 2. Return the Boolean value of the [[Extensible]] internal property of O. var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation 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; }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) { Date.prototype.toISOString = function toISOString() { var result, length, value, year; if (!isFinite(this)) throw new RangeError; // the date time string format is specified in 15.9.1.15. result = [this.getUTCMonth() + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = this.getUTCFullYear(); year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two digits. if (value < 10) result[length] = "0" + value; } // pad milliseconds to have three digits. return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z"; } } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). if (!Date.prototype.toJSON) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be ToPrimitive(O, hint Number). // 3. If tv is a Number and is not finite, return null. // XXX // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof this.toISOString != "function") throw new TypeError(); // TODO message // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return this.toISOString(); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function(NativeDate) { // Date.length === 7 var Date = function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length == 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); }; // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:\\.(\\d{3}))?" + // milliseconds capture ")?" + "(?:" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) Date[key] = NativeDate[key]; // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { match.shift(); // kill match[0], the full match // parse months, days, hours, minutes, seconds, and milliseconds for (var i = 1; i < 7; i++) { // provide default values if necessary match[i] = +(match[i] || (i < 3 ? 1 : 0)); // match[1] is the month. Months are 0-11 in JavaScript // `Date` objects, but 1-12 in ISO notation, so we // decrement. if (i == 1) match[i]--; } // parse the UTC offset component var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop(); // compute the explicit time zone offset if specified var offset = 0; if (sign) { // detect invalid offsets and return early if (hourOffset > 23 || minuteOffset > 59) return NaN; // express the provided time zone offset in minutes. The offset is // negative for time zones west of UTC; positive otherwise. offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1); } // Date.UTC for years between 0 and 99 converts year to 1900 + year // The Gregorian calendar has a 400-year cycle, so // to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...), // where 12622780800000 - number of milliseconds in Gregorian calendar 400 years var year = +match[0]; if (0 <= year && year <= 99) { match[0] = year + 400; return NativeDate.UTC.apply(this, match) + offset - 12622780800000; } // compute a new UTC date value, accounting for the optional offset return NativeDate.UTC.apply(this, match) + offset; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // // String // ====== // // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 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()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ 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, ""); }; } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer var toInteger = function (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; }; var prepareString = "a"[0] != "a", // ES5 9.9 // http://es5.github.com/#x9.9 toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError(); // TODO message } // If the implementation doesn't support by-index access of // string characters (ex. IE < 7), split the string if (prepareString && typeof o == "string" && o) { return o.split(""); } return Object(o); }; }); define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) { var EventEmitter = {}; 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; e = e || {}; e.type = eventName; if (!e.stopPropagation) { e.stopPropagation = function() { this.propagationStopped = true; }; } if (!e.preventDefault) { e.preventDefault = function() { this.defaultPrevented = true; }; } for (var i=0; i<listeners.length; i++) { listeners[i](e); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e); }; EventEmitter.setDefaultHandler = function(eventName, callback) { this._defaultHandlers = this._defaultHandlers || {}; if (this._defaultHandlers[eventName]) throw new Error("The default handler for '" + eventName + "' is already set"); this._defaultHandlers[eventName] = callback; }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) var listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners.push(callback); }; EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) { exports.inherits = (function() { var tempCtor = function() {}; return function(ctor, superCtor) { tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor.prototype; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }; }()); exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); define('ace/mode/javascript_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/worker/jshint', 'ace/narcissus/parser'], function(require, exports, module) { var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var lint = require("../worker/jshint").JSHINT; var parser = require("../narcissus/parser"); var JavaScriptWorker = exports.JavaScriptWorker = function(sender) { Mirror.call(this, sender); this.setTimeout(500); }; oop.inherits(JavaScriptWorker, Mirror); (function() { this.onUpdate = function() { var value = this.doc.getValue(); value = value.replace(/^#!.*\n/, "\n"); // var start = new Date(); try { parser.parse(value); } catch(e) { // console.log("narcissus") // console.log(e); var chunks = e.message.split(":") var message = chunks.pop().trim(); var lineNumber = parseInt(chunks.pop().trim()) - 1; this.sender.emit("narcissus", { row: lineNumber, column: null, // TODO convert e.cursor text: message, type: "error" }); return; } finally { // console.log("parse time: " + (new Date() - start)); } // var start = new Date(); // console.log("jslint") lint(value, {undef: false, onevar: false, passfail: false}); this.sender.emit("jslint", lint.errors); // console.log("lint time: " + (new Date() - start)); } }).call(JavaScriptWorker.prototype); }); define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) { 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.deferredCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { doc.applyDeltas([e.data]); deferredUpdate.schedule(_self.$timeout); }); }; (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() { // abstract method }; }).call(Mirror.prototype); }); define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; /** * new Document([text]) * - text (String | Array): The starting text * * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * **/ var Document = function(text) { this.$lines = []; // There has to be one line at least in the document. If you pass an empty // string to the insert function, nothing will happen. Workaround. if (text.length == 0) { this.$lines = [""]; } else if (Array.isArray(text)) { this.insertLines(0, text); } else { this.insert({row: 0, column:0}, text); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength(); this.remove(new Range(0, 0, len, this.getLine(len-1).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); }; // check for IE split bug 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); if (match) { this.$autoNewLine = match[1]; } else { this.$autoNewLine = "\n"; } }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; case "auto": return this.$autoNewLine; } }; this.$autoNewLine = "\n"; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; }; 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) { if (range.start.row == range.end.row) { return this.$lines[range.start.row].substring(range.start.column, range.end.column); } else { var lines = this.getLines(range.start.row+1, range.end.row-1); lines.unshift((this.$lines[range.start.row] || "").substring(range.start.column)); lines.push((this.$lines[range.end.row] || "").substring(0, range.end.column)); return lines.join(this.getNewLineCharacter()); } }; 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; } return position; }; this.insert = function(position, text) { if (!text || text.length === 0) return position; position = this.$clipPosition(position); // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); var lines = this.$split(text); var firstLine = lines.splice(0, 1)[0]; var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0]; position = this.insertInLine(position, firstLine); if (lastLine !== null) { position = this.insertNewLine(position); // terminate first line position = this.insertLines(position.row, lines); position = this.insertInLine(position, lastLine || ""); } return position; }; this.insertLines = function(row, lines) { if (lines.length == 0) return {row: row, column: 0}; // apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF) // to circumvent that we have to break huge inserts into smaller chunks here if (lines.length > 0xFFFF) { var end = this.insertLines(row, lines.slice(0xFFFF)); lines = lines.slice(0, 0xFFFF); } var args = [row, 0]; args.push.apply(args, lines); this.$lines.splice.apply(this.$lines, args); var range = new Range(row, 0, row + lines.length, 0); var delta = { action: "insertLines", range: range, lines: lines }; this._emit("change", { data: delta }); return end || range.end; }; this.insertNewLine = function(position) { position = this.$clipPosition(position); var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column); this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length)); var end = { row : position.row + 1, column : 0 }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); return end; }; this.insertInLine = function(position, text) { if (text.length == 0) return position; var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column) + text + line.substring(position.column); var end = { row : position.row, column : position.column + text.length }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: text }; this._emit("change", { data: delta }); return end; }; this.remove = function(range) { // clip to document range.start = this.$clipPosition(range.start); range.end = this.$clipPosition(range.end); if (range.isEmpty()) return range.start; var firstRow = range.start.row; var lastRow = range.end.row; if (range.isMultiLine()) { var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1; var lastFullRow = lastRow - 1; if (range.end.column > 0) this.removeInLine(lastRow, 0, range.end.column); if (lastFullRow >= firstFullRow) this.removeLines(firstFullRow, lastFullRow); if (firstFullRow != firstRow) { this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length); this.removeNewLine(range.start.row); } } else { this.removeInLine(firstRow, range.start.column, range.end.column); } return range.start; }; this.removeInLine = function(row, startColumn, endColumn) { if (startColumn == endColumn) return; var range = new Range(row, startColumn, row, endColumn); var line = this.getLine(row); var removed = line.substring(startColumn, endColumn); var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length); this.$lines.splice(row, 1, newLine); var delta = { action: "removeText", range: range, text: removed }; this._emit("change", { data: delta }); return range.start; }; this.removeLines = function(firstRow, lastRow) { var range = new Range(firstRow, 0, lastRow + 1, 0); var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1); var delta = { action: "removeLines", range: range, nl: this.getNewLineCharacter(), lines: removed }; this._emit("change", { data: delta }); return removed; }; this.removeNewLine = function(row) { var firstLine = this.getLine(row); var secondLine = this.getLine(row+1); var range = new Range(row, firstLine.length, row+1, 0); var line = firstLine + secondLine; this.$lines.splice(row, 2, line); var delta = { action: "removeText", range: range, text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); }; this.replace = function(range, text) { if (text.length == 0 && range.isEmpty()) return range.start; // Shortcut: If the text we want to insert is the same as it is already // in the document, we don't have to replace anything. if (text == this.getTextRange(range)) return range.end; this.remove(range); if (text) { var end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "insertText") this.insert(range.start, delta.text); else if (delta.action == "removeLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "removeText") this.remove(range); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "insertText") this.remove(range); else if (delta.action == "removeLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "removeText") this.insert(range.start, delta.text); } }; }).call(Document.prototype); exports.Document = Document; }); define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class Range * * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. * **/ /** * new Range(startRow, startColumn, endRow, endColumn) * - startRow (Number): The starting row * - startColumn (Number): The starting column * - endRow (Number): The ending row * - endColumn (Number): The ending column * * Creates a new `Range` object with the given starting and ending row and column points. * **/ var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { /** * Range.isEqual(range) -> Boolean * - range (Range): A range to check against * * Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`. * **/ 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; } } } /** related to: Range.compare * Range.comparePoint(p) -> Number * - p (Range): A point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1<br/> * * Checks the row and column points of `p` with the row and column points of the calling range. * * * **/ this.comparePoint = function(p) { return this.compare(p.row, p.column); } /** related to: Range.comparePoint * Range.containsRange(range) -> Boolean * - range (Range): A range to compare with * * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. * **/ this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } /** * Range.intersects(range) -> Boolean * - range (Range): A range to compare with * * Returns `true` if passed in `range` intersects with the one calling this method. * **/ this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); } /** * Range.isEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. * **/ this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } /** * Range.isStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. * **/ this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; } /** * Range.setStart(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** * Range.setEnd(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** related to: Range.compare * Range.inside(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range. * **/ 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; } /** related to: Range.compare * Range.insideStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's starting points. * **/ this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; } /** related to: Range.compare * Range.insideEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's ending points. * **/ this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; } /** * Range.compare(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal <br/> * * `-1` if `p.row` is less then the calling range <br/> * * `1` if `p.row` is greater than the calling range <br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> * <br/> * If the ending row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0` <br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ 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); } } /** * Range.compareEnd(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } } /** * Range.compareInside(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`<br/> * * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`<br/> * <br/> * Otherwise, it returns the value after calling [[Range.compare `compare()`]]. * * Checks the row and column points with the row and column points of the calling range. * * * **/ 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); } } /** * Range.clipRows(firstRow, lastRow) -> Range * - firstRow (Number): The starting row * - lastRow (Number): The ending row * * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. * **/ this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) { var end = { row: lastRow+1, column: 0 }; } if (this.start.row > lastRow) { var start = { row: lastRow+1, column: 0 }; } if (this.start.row < firstRow) { var start = { row: firstRow, column: 0 }; } if (this.end.row < firstRow) { var end = { 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 ); }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; exports.Range = Range; }); define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; /** * new Anchor(doc, row, column) * - doc (Document): The document to associate with the anchor * - row (Number): The starting row position * - column (Number): The starting column position * * Creates a new `Anchor` and associates it with a document. * **/ var Anchor = exports.Anchor = function(doc, row, column) { this.document = doc; if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); this.$onChange = this.onChange.bind(this); doc.on("change", this.$onChange); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.onChange = function(e) { var delta = e.data; var range = delta.range; if (range.start.row == range.end.row && range.start.row != this.row) return; if (range.start.row > this.row) return; if (range.start.row == this.row && range.start.column > this.column) return; var row = this.row; var column = this.column; if (delta.action === "insertText") { if (range.start.row === row && range.start.column <= column) { if (range.start.row === range.end.row) { column += range.end.column - range.start.column; } else { column -= range.start.column; row += range.end.row - range.start.row; } } else if (range.start.row !== range.end.row && range.start.row < row) { row += range.end.row - range.start.row; } } else if (delta.action === "insertLines") { if (range.start.row <= row) { row += range.end.row - range.start.row; } } else if (delta.action == "removeText") { if (range.start.row == row && range.start.column < column) { if (range.end.column >= column) column = range.start.column; else column = Math.max(0, column - (range.end.column - range.start.column)); } else if (range.start.row !== range.end.row && range.start.row < row) { if (range.end.row == row) { column = Math.max(0, column - range.end.column) + range.start.column; } row -= (range.end.row - range.start.row); } else if (range.end.row == row) { row -= range.end.row - range.start.row; column = Math.max(0, column - range.end.column) + range.start.column; } } else if (delta.action == "removeLines") { if (range.start.row <= row) { if (range.end.row <= row) row -= range.end.row - range.start.row; else { row = range.start.row; column = 0; } } } this.setPosition(row, column, true); }; 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._emit("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("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); }); define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) { exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { return new Array(count + 1).join(string); }; 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<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function (obj) { if (typeof obj != "object") { return obj; } var copy = obj.constructor(); for (var key in obj) { if (typeof obj[key] == "object") { copy[key] = this.deepCopy(obj[key]); } else { copy[key] = obj[key]; } } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; return deferred; }; }); define('ace/worker/jshint', ['require', 'exports', 'module' ], function(require, exports, module) { /*! * JSHint, by JSHint Community. * * Licensed under the same slightly modified MIT license that JSLint is. * It stops evil-doers everywhere. * * JSHint is a derivative work of JSLint: * * Copyright (c) 2002 Douglas Crockford (www.JSLint.com) * * 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 shall be used for Good, not Evil. * * 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. * * JSHint was forked from 2010-12-16 edition of JSLint. * */ /* JSHINT is a global function. It takes two parameters. var myResult = JSHINT(source, option); The first parameter is either a string or an array of strings. If it is a string, it will be split on '\n' or '\r'. If it is an array of strings, it is assumed that each string represents one line. The source can be a JavaScript text or a JSON text. The second parameter is an optional object of options which control the operation of JSHINT. Most of the options are booleans: They are all optional and have a default value of false. One of the options, predef, can be an array of names, which will be used to declare global variables, or an object whose keys are used as global names, with a boolean value that determines if they are assignable. If it checks out, JSHINT returns true. Otherwise, it returns false. If false, you can inspect JSHINT.errors to find out the problems. JSHINT.errors is an array of objects containing these members: { line : The line (relative to 0) at which the lint was found character : The character (relative to 0) at which the lint was found reason : The problem evidence : The text line in which the problem occurred raw : The raw message before the details were inserted a : The first detail b : The second detail c : The third detail d : The fourth detail } If a fatal error was found, a null will be the last element of the JSHINT.errors array. You can request a Function Report, which shows all of the functions and the parameters and vars that they use. This can be used to find implied global variables and other problems. The report is in HTML and can be inserted in an HTML <body>. var myReport = JSHINT.report(limited); If limited is true, then the report will be limited to only errors. You can request a data structure which contains JSHint's results. var myData = JSHINT.data(); It returns a structure with this form: { errors: [ { line: NUMBER, character: NUMBER, reason: STRING, evidence: STRING } ], functions: [ name: STRING, line: NUMBER, last: NUMBER, param: [ STRING ], closure: [ STRING ], var: [ STRING ], exception: [ STRING ], outer: [ STRING ], unused: [ STRING ], global: [ STRING ], label: [ STRING ] ], globals: [ STRING ], member: { STRING: NUMBER }, unused: [ { name: STRING, line: NUMBER } ], implieds: [ { name: STRING, line: NUMBER } ], urls: [ STRING ], json: BOOLEAN } Empty arrays will not be included. */ /*jshint evil: true, nomen: false, onevar: false, regexp: false, strict: true, boss: true, undef: true, maxlen: 100, indent:4 */ /*members "\b", "\t", "\n", "\f", "\r", "!=", "!==", "\"", "%", "(begin)", "(breakage)", "(context)", "(error)", "(global)", "(identifier)", "(last)", "(line)", "(loopage)", "(name)", "(onevar)", "(params)", "(scope)", "(statement)", "(verb)", "*", "+", "++", "-", "--", "\/", "<", "<=", "==", "===", ">", ">=", $, $$, $A, $F, $H, $R, $break, $continue, $w, Abstract, Ajax, __filename, __dirname, ActiveXObject, Array, ArrayBuffer, ArrayBufferView, Audio, Autocompleter, Assets, Boolean, Builder, Buffer, Browser, COM, CScript, Canvas, CustomAnimation, Class, Control, Chain, Color, Cookie, Core, DataView, Date, Debug, Draggable, Draggables, Droppables, Document, DomReady, DOMReady, DOMParser, Drag, E, Enumerator, Enumerable, Element, Elements, Error, Effect, EvalError, Event, Events, FadeAnimation, Field, Flash, Float32Array, Float64Array, Form, FormField, Frame, FormData, Function, Fx, GetObject, Group, Hash, HotKey, HTMLElement, HTMLAnchorElement, HTMLBaseElement, HTMLBlockquoteElement, HTMLBodyElement, HTMLBRElement, HTMLButtonElement, HTMLCanvasElement, HTMLDirectoryElement, HTMLDivElement, HTMLDListElement, HTMLFieldSetElement, HTMLFontElement, HTMLFormElement, HTMLFrameElement, HTMLFrameSetElement, HTMLHeadElement, HTMLHeadingElement, HTMLHRElement, HTMLHtmlElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLIsIndexElement, HTMLLabelElement, HTMLLayerElement, HTMLLegendElement, HTMLLIElement, HTMLLinkElement, HTMLMapElement, HTMLMenuElement, HTMLMetaElement, HTMLModElement, HTMLObjectElement, HTMLOListElement, HTMLOptGroupElement, HTMLOptionElement, HTMLParagraphElement, HTMLParamElement, HTMLPreElement, HTMLQuoteElement, HTMLScriptElement, HTMLSelectElement, HTMLStyleElement, HtmlTable, HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, HTMLTextAreaElement, HTMLTitleElement, HTMLUListElement, HTMLVideoElement, Iframe, IframeShim, Image, Int16Array, Int32Array, Int8Array, Insertion, InputValidator, JSON, Keyboard, Locale, LN10, LN2, LOG10E, LOG2E, MAX_VALUE, MIN_VALUE, Mask, Math, MenuItem, MessageChannel, MessageEvent, MessagePort, MoveAnimation, MooTools, Native, NEGATIVE_INFINITY, Number, Object, ObjectRange, Option, Options, OverText, PI, POSITIVE_INFINITY, PeriodicalExecuter, Point, Position, Prototype, RangeError, Rectangle, ReferenceError, RegExp, ResizeAnimation, Request, RotateAnimation, SQRT1_2, SQRT2, ScrollBar, ScriptEngine, ScriptEngineBuildVersion, ScriptEngineMajorVersion, ScriptEngineMinorVersion, Scriptaculous, Scroller, Slick, Slider, Selector, SharedWorker, String, Style, SyntaxError, Sortable, Sortables, SortableObserver, Sound, Spinner, System, Swiff, Text, TextArea, Template, Timer, Tips, Type, TypeError, Toggle, Try, "use strict", unescape, URI, URIError, URL, VBArray, WSH, WScript, XDomainRequest, Web, Window, XMLDOM, XMLHttpRequest, XMLSerializer, XPathEvaluator, XPathException, XPathExpression, XPathNamespace, XPathNSResolver, XPathResult, "\\", a, addEventListener, address, alert, apply, applicationCache, arguments, arity, asi, atob, b, basic, basicToken, bitwise, block, blur, boolOptions, boss, browser, btoa, c, call, callee, caller, cases, charAt, charCodeAt, character, clearInterval, clearTimeout, close, closed, closure, comment, condition, confirm, console, constructor, content, couch, create, css, curly, d, data, datalist, dd, debug, decodeURI, decodeURIComponent, defaultStatus, defineClass, deserialize, devel, document, dojo, dijit, dojox, define, else, emit, encodeURI, encodeURIComponent, entityify, eqeqeq, eqnull, errors, es5, escape, esnext, eval, event, evidence, evil, ex, exception, exec, exps, expr, exports, FileReader, first, floor, focus, forin, fragment, frames, from, fromCharCode, fud, funcscope, funct, function, functions, g, gc, getComputedStyle, getRow, getter, getterToken, GLOBAL, global, globals, globalstrict, hasOwnProperty, help, history, i, id, identifier, immed, implieds, importPackage, include, indent, indexOf, init, ins, instanceOf, isAlpha, isApplicationRunning, isArray, isDigit, isFinite, isNaN, iterator, java, join, jshint, JSHINT, json, jquery, jQuery, keys, label, labelled, last, lastsemic, laxbreak, laxcomma, latedef, lbp, led, left, length, line, load, loadClass, localStorage, location, log, loopfunc, m, match, maxerr, maxlen, member,message, meta, module, moveBy, moveTo, mootools, multistr, name, navigator, new, newcap, noarg, node, noempty, nomen, nonew, nonstandard, nud, onbeforeunload, onblur, onerror, onevar, onecase, onfocus, onload, onresize, onunload, open, openDatabase, openURL, opener, opera, options, outer, param, parent, parseFloat, parseInt, passfail, plusplus, predef, print, process, prompt, proto, prototype, prototypejs, provides, push, quit, range, raw, reach, reason, regexp, readFile, readUrl, regexdash, removeEventListener, replace, report, require, reserved, resizeBy, resizeTo, resolvePath, resumeUpdates, respond, rhino, right, runCommand, scroll, screen, scripturl, scrollBy, scrollTo, scrollbar, search, seal, send, serialize, sessionStorage, setInterval, setTimeout, setter, setterToken, shift, slice, smarttabs, sort, spawn, split, stack, status, start, strict, sub, substr, supernew, shadow, supplant, sum, sync, test, toLowerCase, toString, toUpperCase, toint32, token, top, trailing, type, typeOf, Uint16Array, Uint32Array, Uint8Array, undef, undefs, unused, urls, validthis, value, valueOf, var, version, WebSocket, withstmt, white, window, Worker, wsh*/ /*global exports: false */ // We build the application inside a function so that we produce only a single // global variable. That function will be invoked immediately, and its return // value is the JSHINT function itself. var JSHINT = (function () { var anonname, // The guessed name for anonymous functions. // These are operators that should not be used with the ! operator. bang = { '<' : true, '<=' : true, '==' : true, '===': true, '!==': true, '!=' : true, '>' : true, '>=' : true, '+' : true, '-' : true, '*' : true, '/' : true, '%' : true }, // These are the JSHint boolean options. boolOptions = { asi : true, // if automatic semicolon insertion should be tolerated bitwise : true, // if bitwise operators should not be allowed boss : true, // if advanced usage of assignments should be allowed browser : true, // if the standard browser globals should be predefined couch : true, // if CouchDB globals should be predefined curly : true, // if curly braces around all blocks should be required debug : true, // if debugger statements should be allowed devel : true, // if logging globals should be predefined (console, // alert, etc.) dojo : true, // if Dojo Toolkit globals should be predefined eqeqeq : true, // if === should be required eqnull : true, // if == null comparisons should be tolerated es5 : true, // if ES5 syntax should be allowed esnext : true, // if es.next specific syntax should be allowed evil : true, // if eval should be allowed expr : true, // if ExpressionStatement should be allowed as Programs forin : true, // if for in statements must filter funcscope : true, // if only function scope should be used for scope tests globalstrict: true, // if global should be allowed (also // enables 'strict') immed : true, // if immediate invocations must be wrapped in parens iterator : true, // if the `__iterator__` property should be allowed jquery : true, // if jQuery globals should be predefined lastsemic : true, // if semicolons may be ommitted for the trailing // statements inside of a one-line blocks. latedef : true, // if the use before definition should not be tolerated laxbreak : true, // if line breaks should not be checked laxcomma : true, // if line breaks should not be checked around commas loopfunc : true, // if functions should be allowed to be defined within // loops mootools : true, // if MooTools globals should be predefined multistr : true, // allow multiline strings newcap : true, // if constructor names must be capitalized noarg : true, // if arguments.caller and arguments.callee should be // disallowed node : true, // if the Node.js environment globals should be // predefined noempty : true, // if empty blocks should be disallowed nonew : true, // if using `new` for side-effects should be disallowed nonstandard : true, // if non-standard (but widely adopted) globals should // be predefined nomen : true, // if names should be checked onevar : true, // if only one var statement per function should be // allowed onecase : true, // if one case switch statements should be allowed passfail : true, // if the scan should stop on first error plusplus : true, // if increment/decrement should not be allowed proto : true, // if the `__proto__` property should be allowed prototypejs : true, // if Prototype and Scriptaculous globals should be // predefined regexdash : true, // if unescaped first/last dash (-) inside brackets // should be tolerated regexp : true, // if the . should not be allowed in regexp literals rhino : true, // if the Rhino environment globals should be predefined undef : true, // if variables should be declared before used scripturl : true, // if script-targeted URLs should be tolerated shadow : true, // if variable shadowing should be tolerated smarttabs : true, // if smarttabs should be tolerated // (http://www.emacswiki.org/emacs/SmartTabs) strict : true, // require the pragma sub : true, // if all forms of subscript notation are tolerated supernew : true, // if `new function () { ... };` and `new Object;` // should be tolerated trailing : true, // if trailing whitespace rules apply validthis : true, // if 'this' inside a non-constructor function is valid. // This is a function scoped option only. withstmt : true, // if with statements should be allowed white : true, // if strict whitespace rules apply wsh : true // if the Windows Scripting Host environment globals // should be predefined }, // These are the JSHint options that can take any value // (we use this object to detect invalid options) valOptions = { maxlen: false, indent: false, maxerr: false, predef: false }, // browser contains a set of global names which are commonly provided by a // web browser environment. browser = { ArrayBuffer : false, ArrayBufferView : false, Audio : false, addEventListener : false, applicationCache : false, atob : false, blur : false, btoa : false, clearInterval : false, clearTimeout : false, close : false, closed : false, DataView : false, DOMParser : false, defaultStatus : false, document : false, event : false, FileReader : false, Float32Array : false, Float64Array : false, FormData : false, focus : false, frames : false, getComputedStyle : false, HTMLElement : false, HTMLAnchorElement : false, HTMLBaseElement : false, HTMLBlockquoteElement : false, HTMLBodyElement : false, HTMLBRElement : false, HTMLButtonElement : false, HTMLCanvasElement : false, HTMLDirectoryElement : false, HTMLDivElement : false, HTMLDListElement : false, HTMLFieldSetElement : false, HTMLFontElement : false, HTMLFormElement : false, HTMLFrameElement : false, HTMLFrameSetElement : false, HTMLHeadElement : false, HTMLHeadingElement : false, HTMLHRElement : false, HTMLHtmlElement : false, HTMLIFrameElement : false, HTMLImageElement : false, HTMLInputElement : false, HTMLIsIndexElement : false, HTMLLabelElement : false, HTMLLayerElement : false, HTMLLegendElement : false, HTMLLIElement : false, HTMLLinkElement : false, HTMLMapElement : false, HTMLMenuElement : false, HTMLMetaElement : false, HTMLModElement : false, HTMLObjectElement : false, HTMLOListElement : false, HTMLOptGroupElement : false, HTMLOptionElement : false, HTMLParagraphElement : false, HTMLParamElement : false, HTMLPreElement : false, HTMLQuoteElement : false, HTMLScriptElement : false, HTMLSelectElement : false, HTMLStyleElement : false, HTMLTableCaptionElement : false, HTMLTableCellElement : false, HTMLTableColElement : false, HTMLTableElement : false, HTMLTableRowElement : false, HTMLTableSectionElement : false, HTMLTextAreaElement : false, HTMLTitleElement : false, HTMLUListElement : false, HTMLVideoElement : false, history : false, Int16Array : false, Int32Array : false, Int8Array : false, Image : false, length : false, localStorage : false, location : false, MessageChannel : false, MessageEvent : false, MessagePort : false, moveBy : false, moveTo : false, name : false, navigator : false, onbeforeunload : true, onblur : true, onerror : true, onfocus : true, onload : true, onresize : true, onunload : true, open : false, openDatabase : false, opener : false, Option : false, parent : false, print : false, removeEventListener : false, resizeBy : false, resizeTo : false, screen : false, scroll : false, scrollBy : false, scrollTo : false, sessionStorage : false, setInterval : false, setTimeout : false, SharedWorker : false, status : false, top : false, Uint16Array : false, Uint32Array : false, Uint8Array : false, WebSocket : false, window : false, Worker : false, XMLHttpRequest : false, XMLSerializer : false, XPathEvaluator : false, XPathException : false, XPathExpression : false, XPathNamespace : false, XPathNSResolver : false, XPathResult : false }, couch = { "require" : false, respond : false, getRow : false, emit : false, send : false, start : false, sum : false, log : false, exports : false, module : false, provides : false }, devel = { alert : false, confirm : false, console : false, Debug : false, opera : false, prompt : false }, dojo = { dojo : false, dijit : false, dojox : false, define : false, "require" : false }, escapes = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '/' : '\\/', '\\': '\\\\' }, funct, // The current function functionicity = [ 'closure', 'exception', 'global', 'label', 'outer', 'unused', 'var' ], functions, // All of the functions global, // The global scope implied, // Implied globals inblock, indent, jsonmode, jquery = { '$' : false, jQuery : false }, lines, lookahead, member, membersOnly, mootools = { '$' : false, '$$' : false, Assets : false, Browser : false, Chain : false, Class : false, Color : false, Cookie : false, Core : false, Document : false, DomReady : false, DOMReady : false, Drag : false, Element : false, Elements : false, Event : false, Events : false, Fx : false, Group : false, Hash : false, HtmlTable : false, Iframe : false, IframeShim : false, InputValidator : false, instanceOf : false, Keyboard : false, Locale : false, Mask : false, MooTools : false, Native : false, Options : false, OverText : false, Request : false, Scroller : false, Slick : false, Slider : false, Sortables : false, Spinner : false, Swiff : false, Tips : false, Type : false, typeOf : false, URI : false, Window : false }, nexttoken, node = { __filename : false, __dirname : false, Buffer : false, console : false, exports : false, GLOBAL : false, global : false, module : false, process : false, require : false, setTimeout : false, clearTimeout : false, setInterval : false, clearInterval : false }, noreach, option, predefined, // Global variables defined by option prereg, prevtoken, prototypejs = { '$' : false, '$$' : false, '$A' : false, '$F' : false, '$H' : false, '$R' : false, '$break' : false, '$continue' : false, '$w' : false, Abstract : false, Ajax : false, Class : false, Enumerable : false, Element : false, Event : false, Field : false, Form : false, Hash : false, Insertion : false, ObjectRange : false, PeriodicalExecuter: false, Position : false, Prototype : false, Selector : false, Template : false, Toggle : false, Try : false, Autocompleter : false, Builder : false, Control : false, Draggable : false, Draggables : false, Droppables : false, Effect : false, Sortable : false, SortableObserver : false, Sound : false, Scriptaculous : false }, rhino = { defineClass : false, deserialize : false, gc : false, help : false, importPackage: false, "java" : false, load : false, loadClass : false, print : false, quit : false, readFile : false, readUrl : false, runCommand : false, seal : false, serialize : false, spawn : false, sync : false, toint32 : false, version : false }, scope, // The current scope stack, // standard contains the global names that are provided by the // ECMAScript standard. standard = { Array : false, Boolean : false, Date : false, decodeURI : false, decodeURIComponent : false, encodeURI : false, encodeURIComponent : false, Error : false, 'eval' : false, EvalError : false, Function : false, hasOwnProperty : false, isFinite : false, isNaN : false, JSON : false, Math : false, Number : false, Object : false, parseInt : false, parseFloat : false, RangeError : false, ReferenceError : false, RegExp : false, String : false, SyntaxError : false, TypeError : false, URIError : false }, // widely adopted global names that are not part of ECMAScript standard nonstandard = { escape : false, unescape : false }, standard_member = { E : true, LN2 : true, LN10 : true, LOG2E : true, LOG10E : true, MAX_VALUE : true, MIN_VALUE : true, NEGATIVE_INFINITY : true, PI : true, POSITIVE_INFINITY : true, SQRT1_2 : true, SQRT2 : true }, directive, syntax = {}, tab, token, urls, useESNextSyntax, warnings, wsh = { ActiveXObject : true, Enumerator : true, GetObject : true, ScriptEngine : true, ScriptEngineBuildVersion : true, ScriptEngineMajorVersion : true, ScriptEngineMinorVersion : true, VBArray : true, WSH : true, WScript : true, XDomainRequest : true }; // Regular expressions. Some of these are stupidly long. var ax, cx, tx, nx, nxg, lx, ix, jx, ft; (function () { /*jshint maxlen:300 */ // unsafe comment or string ax = /@cc|<\/?|script|\]\s*\]|<\s*!|&lt/i; // unsafe characters that are silently deleted by one or more browsers cx = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; // token tx = /^\s*([(){}\[.,:;'"~\?\]#@]|==?=?|\/(\*(jshint|jslint|members?|global)?|=|\/)?|\*[\/=]?|\+(?:=|\++)?|-(?:=|-+)?|%=?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=!]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/; // characters in strings that need escapement nx = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; nxg = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // star slash lx = /\*\/|\/\*/; // identifier ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/; // javascript url jx = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i; // catches /* falls through */ comments ft = /^\s*\/\*\s*falls\sthrough\s*\*\/\s*$/; }()); function F() {} // Used by Object.create function is_own(object, name) { // The object.hasOwnProperty method fails when the property under consideration // is named 'hasOwnProperty'. So we have to use this more convoluted form. return Object.prototype.hasOwnProperty.call(object, name); } function checkOption(name, t) { if (valOptions[name] === undefined && boolOptions[name] === undefined) { warning("Bad option: '" + name + "'.", t); } } // Provide critical ES5 functions to ES3. if (typeof Array.isArray !== 'function') { Array.isArray = function (o) { return Object.prototype.toString.apply(o) === '[object Array]'; }; } if (typeof Object.create !== 'function') { Object.create = function (o) { F.prototype = o; return new F(); }; } if (typeof Object.keys !== 'function') { Object.keys = function (o) { var a = [], k; for (k in o) { if (is_own(o, k)) { a.push(k); } } return a; }; } // Non standard methods if (typeof String.prototype.entityify !== 'function') { String.prototype.entityify = function () { return this .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); }; } if (typeof String.prototype.isAlpha !== 'function') { String.prototype.isAlpha = function () { return (this >= 'a' && this <= 'z\uffff') || (this >= 'A' && this <= 'Z\uffff'); }; } if (typeof String.prototype.isDigit !== 'function') { String.prototype.isDigit = function () { return (this >= '0' && this <= '9'); }; } if (typeof String.prototype.supplant !== 'function') { String.prototype.supplant = function (o) { return this.replace(/\{([^{}]*)\}/g, function (a, b) { var r = o[b]; return typeof r === 'string' || typeof r === 'number' ? r : a; }); }; } if (typeof String.prototype.name !== 'function') { String.prototype.name = function () { // If the string looks like an identifier, then we can return it as is. // If the string contains no control characters, no quote characters, and no // backslash characters, then we can simply slap some quotes around it. // Otherwise we must also replace the offending characters with safe // sequences. if (ix.test(this)) { return this; } if (nx.test(this)) { return '"' + this.replace(nxg, function (a) { var c = escapes[a]; if (c) { return c; } return '\\u' + ('0000' + a.charCodeAt().toString(16)).slice(-4); }) + '"'; } return '"' + this + '"'; }; } function combine(t, o) { var n; for (n in o) { if (is_own(o, n)) { t[n] = o[n]; } } } function assume() { if (option.couch) { combine(predefined, couch); } if (option.rhino) { combine(predefined, rhino); } if (option.prototypejs) { combine(predefined, prototypejs); } if (option.node) { combine(predefined, node); option.globalstrict = true; } if (option.devel) { combine(predefined, devel); } if (option.dojo) { combine(predefined, dojo); } if (option.browser) { combine(predefined, browser); } if (option.nonstandard) { combine(predefined, nonstandard); } if (option.jquery) { combine(predefined, jquery); } if (option.mootools) { combine(predefined, mootools); } if (option.wsh) { combine(predefined, wsh); } if (option.esnext) { useESNextSyntax(); } if (option.globalstrict && option.strict !== false) { option.strict = true; } } // Produce an error warning. function quit(message, line, chr) { var percentage = Math.floor((line / lines.length) * 100); throw { name: 'JSHintError', line: line, character: chr, message: message + " (" + percentage + "% scanned).", raw: message }; } function isundef(scope, m, t, a) { return JSHINT.undefs.push([scope, m, t, a]); } function warning(m, t, a, b, c, d) { var ch, l, w; t = t || nexttoken; if (t.id === '(end)') { // `~ t = token; } l = t.line || 0; ch = t.from || 0; w = { id: '(error)', raw: m, evidence: lines[l - 1] || '', line: l, character: ch, a: a, b: b, c: c, d: d }; w.reason = m.supplant(w); JSHINT.errors.push(w); if (option.passfail) { quit('Stopping. ', l, ch); } warnings += 1; if (warnings >= option.maxerr) { quit("Too many errors.", l, ch); } return w; } function warningAt(m, l, ch, a, b, c, d) { return warning(m, { line: l, from: ch }, a, b, c, d); } function error(m, t, a, b, c, d) { var w = warning(m, t, a, b, c, d); } function errorAt(m, l, ch, a, b, c, d) { return error(m, { line: l, from: ch }, a, b, c, d); } // lexical analysis and token construction var lex = (function lex() { var character, from, line, s; // Private lex methods function nextLine() { var at, tw; // trailing whitespace check if (line >= lines.length) return false; character = 1; s = lines[line]; line += 1; // If smarttabs option is used check for spaces followed by tabs only. // Otherwise check for any occurence of mixed tabs and spaces. if (option.smarttabs) at = s.search(/ \t/); else at = s.search(/ \t|\t /); if (at >= 0) warningAt("Mixed spaces and tabs.", line, at + 1); s = s.replace(/\t/g, tab); at = s.search(cx); if (at >= 0) warningAt("Unsafe character.", line, at); if (option.maxlen && option.maxlen < s.length) warningAt("Line too long.", line, s.length); // Check for trailing whitespaces tw = option.trailing && s.match(/^(.*?)\s+$/); if (tw && !/^\s+$/.test(s)) { warningAt("Trailing whitespace.", line, tw[1].length + 1); } return true; } // Produce a token object. The token inherits from a syntax symbol. function it(type, value) { var i, t; if (type === '(color)' || type === '(range)') { t = {type: type}; } else if (type === '(punctuator)' || (type === '(identifier)' && is_own(syntax, value))) { t = syntax[value] || syntax['(error)']; } else { t = syntax[type]; } t = Object.create(t); if (type === '(string)' || type === '(range)') { if (!option.scripturl && jx.test(value)) { warningAt("Script URL.", line, from); } } if (type === '(identifier)') { t.identifier = true; if (value === '__proto__' && !option.proto) { warningAt("The '{a}' property is deprecated.", line, from, value); } else if (value === '__iterator__' && !option.iterator) { warningAt("'{a}' is only available in JavaScript 1.7.", line, from, value); } else if (option.nomen && (value.charAt(0) === '_' || value.charAt(value.length - 1) === '_')) { if (!option.node || token.id === '.' || (value !== '__dirname' && value !== '__filename')) { warningAt("Unexpected {a} in '{b}'.", line, from, "dangling '_'", value); } } } t.value = value; t.line = line; t.character = character; t.from = from; i = t.id; if (i !== '(endline)') { prereg = i && (('(,=:[!&|?{};'.indexOf(i.charAt(i.length - 1)) >= 0) || i === 'return' || i === 'case'); } return t; } // Public lex methods return { init: function (source) { if (typeof source === 'string') { lines = source .replace(/\r\n/g, '\n') .replace(/\r/g, '\n') .split('\n'); } else { lines = source; } // If the first line is a shebang (#!), make it a blank and move on. // Shebangs are used by Node scripts. if (lines[0] && lines[0].substr(0, 2) === '#!') lines[0] = ''; line = 0; nextLine(); from = 1; }, range: function (begin, end) { var c, value = ''; from = character; if (s.charAt(0) !== begin) { errorAt("Expected '{a}' and instead saw '{b}'.", line, character, begin, s.charAt(0)); } for (;;) { s = s.slice(1); character += 1; c = s.charAt(0); switch (c) { case '': errorAt("Missing '{a}'.", line, character, c); break; case end: s = s.slice(1); character += 1; return it('(range)', value); case '\\': warningAt("Unexpected '{a}'.", line, character, c); } value += c; } }, // token -- this is called by advance to get the next token token: function () { var b, c, captures, d, depth, high, i, l, low, q, t, isLiteral, isInRange, n; function match(x) { var r = x.exec(s), r1; if (r) { l = r[0].length; r1 = r[1]; c = r1.charAt(0); s = s.substr(l); from = character + l - r1.length; character += l; return r1; } } function string(x) { var c, j, r = '', allowNewLine = false; if (jsonmode && x !== '"') { warningAt("Strings must use doublequote.", line, character); } function esc(n) { var i = parseInt(s.substr(j + 1, n), 16); j += n; if (i >= 32 && i <= 126 && i !== 34 && i !== 92 && i !== 39) { warningAt("Unnecessary escapement.", line, character); } character += n; c = String.fromCharCode(i); } j = 0; unclosedString: for (;;) { while (j >= s.length) { j = 0; var cl = line, cf = from; if (!nextLine()) { errorAt("Unclosed string.", cl, cf); break unclosedString; } if (allowNewLine) { allowNewLine = false; } else { warningAt("Unclosed string.", cl, cf); } } c = s.charAt(j); if (c === x) { character += 1; s = s.substr(j + 1); return it('(string)', r, x); } if (c < ' ') { if (c === '\n' || c === '\r') { break; } warningAt("Control character in string: {a}.", line, character + j, s.slice(0, j)); } else if (c === '\\') { j += 1; character += 1; c = s.charAt(j); n = s.charAt(j + 1); switch (c) { case '\\': case '"': case '/': break; case '\'': if (jsonmode) { warningAt("Avoid \\'.", line, character); } break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case '0': c = '\0'; // Octal literals fail in strict mode // check if the number is between 00 and 07 // where 'n' is the token next to 'c' if (n >= 0 && n <= 7 && directive["use strict"]) { warningAt( "Octal literals are not allowed in strict mode.", line, character); } break; case 'u': esc(4); break; case 'v': if (jsonmode) { warningAt("Avoid \\v.", line, character); } c = '\v'; break; case 'x': if (jsonmode) { warningAt("Avoid \\x-.", line, character); } esc(2); break; case '': // last character is escape character // always allow new line if escaped, but show // warning if option is not set allowNewLine = true; if (option.multistr) { if (jsonmode) { warningAt("Avoid EOL escapement.", line, character); } c = ''; character -= 1; break; } warningAt("Bad escapement of EOL. Use option multistr if needed.", line, character); break; default: warningAt("Bad escapement.", line, character); } } r += c; character += 1; j += 1; } } for (;;) { if (!s) { return it(nextLine() ? '(endline)' : '(end)', ''); } t = match(tx); if (!t) { t = ''; c = ''; while (s && s < '!') { s = s.substr(1); } if (s) { errorAt("Unexpected '{a}'.", line, character, s.substr(0, 1)); s = ''; } } else { // identifier if (c.isAlpha() || c === '_' || c === '$') { return it('(identifier)', t); } // number if (c.isDigit()) { if (!isFinite(Number(t))) { warningAt("Bad number '{a}'.", line, character, t); } if (s.substr(0, 1).isAlpha()) { warningAt("Missing space after '{a}'.", line, character, t); } if (c === '0') { d = t.substr(1, 1); if (d.isDigit()) { if (token.id !== '.') { warningAt("Don't use extra leading zeros '{a}'.", line, character, t); } } else if (jsonmode && (d === 'x' || d === 'X')) { warningAt("Avoid 0x-. '{a}'.", line, character, t); } } if (t.substr(t.length - 1) === '.') { warningAt( "A trailing decimal point can be confused with a dot '{a}'.", line, character, t); } return it('(number)', t); } switch (t) { // string case '"': case "'": return string(t); // // comment case '//': s = ''; token.comment = true; break; // /* comment case '/*': for (;;) { i = s.search(lx); if (i >= 0) { break; } if (!nextLine()) { errorAt("Unclosed comment.", line, character); } } character += i + 2; if (s.substr(i, 1) === '/') { errorAt("Nested comment.", line, character); } s = s.substr(i + 2); token.comment = true; break; // /*members /*jshint /*global case '/*members': case '/*member': case '/*jshint': case '/*jslint': case '/*global': case '*/': return { value: t, type: 'special', line: line, character: character, from: from }; case '': break; // / case '/': if (token.id === '/=') { errorAt("A regular expression literal can be confused with '/='.", line, from); } if (prereg) { depth = 0; captures = 0; l = 0; for (;;) { b = true; c = s.charAt(l); l += 1; switch (c) { case '': errorAt("Unclosed regular expression.", line, from); return quit('Stopping.', line, from); case '/': if (depth > 0) { warningAt("{a} unterminated regular expression " + "group(s).", line, from + l, depth); } c = s.substr(0, l - 1); q = { g: true, i: true, m: true }; while (q[s.charAt(l)] === true) { q[s.charAt(l)] = false; l += 1; } character += l; s = s.substr(l); q = s.charAt(0); if (q === '/' || q === '*') { errorAt("Confusing regular expression.", line, from); } return it('(regexp)', c); case '\\': c = s.charAt(l); if (c < ' ') { warningAt( "Unexpected control character in regular expression.", line, from + l); } else if (c === '<') { warningAt( "Unexpected escaped character '{a}' in regular expression.", line, from + l, c); } l += 1; break; case '(': depth += 1; b = false; if (s.charAt(l) === '?') { l += 1; switch (s.charAt(l)) { case ':': case '=': case '!': l += 1; break; default: warningAt( "Expected '{a}' and instead saw '{b}'.", line, from + l, ':', s.charAt(l)); } } else { captures += 1; } break; case '|': b = false; break; case ')': if (depth === 0) { warningAt("Unescaped '{a}'.", line, from + l, ')'); } else { depth -= 1; } break; case ' ': q = 1; while (s.charAt(l) === ' ') { l += 1; q += 1; } if (q > 1) { warningAt( "Spaces are hard to count. Use {{a}}.", line, from + l, q); } break; case '[': c = s.charAt(l); if (c === '^') { l += 1; if (option.regexp) { warningAt("Insecure '{a}'.", line, from + l, c); } else if (s.charAt(l) === ']') { errorAt("Unescaped '{a}'.", line, from + l, '^'); } } if (c === ']') { warningAt("Empty class.", line, from + l - 1); } isLiteral = false; isInRange = false; klass: do { c = s.charAt(l); l += 1; switch (c) { case '[': case '^': warningAt("Unescaped '{a}'.", line, from + l, c); if (isInRange) { isInRange = false; } else { isLiteral = true; } break; case '-': if (isLiteral && !isInRange) { isLiteral = false; isInRange = true; } else if (isInRange) { isInRange = false; } else if (s.charAt(l) === ']') { isInRange = true; } else { if (option.regexdash !== (l === 2 || (l === 3 && s.charAt(1) === '^'))) { warningAt("Unescaped '{a}'.", line, from + l - 1, '-'); } isLiteral = true; } break; case ']': if (isInRange && !option.regexdash) { warningAt("Unescaped '{a}'.", line, from + l - 1, '-'); } break klass; case '\\': c = s.charAt(l); if (c < ' ') { warningAt( "Unexpected control character in regular expression.", line, from + l); } else if (c === '<') { warningAt( "Unexpected escaped character '{a}' in regular expression.", line, from + l, c); } l += 1; // \w, \s and \d are never part of a character range if (/[wsd]/i.test(c)) { if (isInRange) { warningAt("Unescaped '{a}'.", line, from + l, '-'); isInRange = false; } isLiteral = false; } else if (isInRange) { isInRange = false; } else { isLiteral = true; } break; case '/': warningAt("Unescaped '{a}'.", line, from + l - 1, '/'); if (isInRange) { isInRange = false; } else { isLiteral = true; } break; case '<': if (isInRange) { isInRange = false; } else { isLiteral = true; } break; default: if (isInRange) { isInRange = false; } else { isLiteral = true; } } } while (c); break; case '.': if (option.regexp) { warningAt("Insecure '{a}'.", line, from + l, c); } break; case ']': case '?': case '{': case '}': case '+': case '*': warningAt("Unescaped '{a}'.", line, from + l, c); } if (b) { switch (s.charAt(l)) { case '?': case '+': case '*': l += 1; if (s.charAt(l) === '?') { l += 1; } break; case '{': l += 1; c = s.charAt(l); if (c < '0' || c > '9') { warningAt( "Expected a number and instead saw '{a}'.", line, from + l, c); } l += 1; low = +c; for (;;) { c = s.charAt(l); if (c < '0' || c > '9') { break; } l += 1; low = +c + (low * 10); } high = low; if (c === ',') { l += 1; high = Infinity; c = s.charAt(l); if (c >= '0' && c <= '9') { l += 1; high = +c; for (;;) { c = s.charAt(l); if (c < '0' || c > '9') { break; } l += 1; high = +c + (high * 10); } } } if (s.charAt(l) !== '}') { warningAt( "Expected '{a}' and instead saw '{b}'.", line, from + l, '}', c); } else { l += 1; } if (s.charAt(l) === '?') { l += 1; } if (low > high) { warningAt( "'{a}' should not be greater than '{b}'.", line, from + l, low, high); } } } } c = s.substr(0, l - 1); character += l; s = s.substr(l); return it('(regexp)', c); } return it('(punctuator)', t); // punctuator case '#': return it('(punctuator)', t); default: return it('(punctuator)', t); } } } } }; }()); function addlabel(t, type) { if (t === 'hasOwnProperty') { warning("'hasOwnProperty' is a really bad name."); } // Define t in the current function in the current scope. if (is_own(funct, t) && !funct['(global)']) { if (funct[t] === true) { if (option.latedef) warning("'{a}' was used before it was defined.", nexttoken, t); } else { if (!option.shadow && type !== "exception") warning("'{a}' is already defined.", nexttoken, t); } } funct[t] = type; if (funct['(global)']) { global[t] = funct; if (is_own(implied, t)) { if (option.latedef) warning("'{a}' was used before it was defined.", nexttoken, t); delete implied[t]; } } else { scope[t] = funct; } } function doOption() { var b, obj, filter, o = nexttoken.value, t, v; switch (o) { case '*/': error("Unbegun comment."); break; case '/*members': case '/*member': o = '/*members'; if (!membersOnly) { membersOnly = {}; } obj = membersOnly; break; case '/*jshint': case '/*jslint': obj = option; filter = boolOptions; break; case '/*global': obj = predefined; break; default: error("What?"); } t = lex.token(); loop: for (;;) { for (;;) { if (t.type === 'special' && t.value === '*/') { break loop; } if (t.id !== '(endline)' && t.id !== ',') { break; } t = lex.token(); } if (t.type !== '(string)' && t.type !== '(identifier)' && o !== '/*members') { error("Bad option.", t); } v = lex.token(); if (v.id === ':') { v = lex.token(); if (obj === membersOnly) { error("Expected '{a}' and instead saw '{b}'.", t, '*/', ':'); } if (o === '/*jshint') { checkOption(t.value, t); } if (t.value === 'indent' && (o === '/*jshint' || o === '/*jslint')) { b = +v.value; if (typeof b !== 'number' || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { error("Expected a small integer and instead saw '{a}'.", v, v.value); } obj.white = true; obj.indent = b; } else if (t.value === 'maxerr' && (o === '/*jshint' || o === '/*jslint')) { b = +v.value; if (typeof b !== 'number' || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { error("Expected a small integer and instead saw '{a}'.", v, v.value); } obj.maxerr = b; } else if (t.value === 'maxlen' && (o === '/*jshint' || o === '/*jslint')) { b = +v.value; if (typeof b !== 'number' || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { error("Expected a small integer and instead saw '{a}'.", v, v.value); } obj.maxlen = b; } else if (t.value === 'validthis') { if (funct['(global)']) { error("Option 'validthis' can't be used in a global scope."); } else { if (v.value === 'true' || v.value === 'false') obj[t.value] = v.value === 'true'; else error("Bad option value.", v); } } else if (v.value === 'true') { obj[t.value] = true; } else if (v.value === 'false') { obj[t.value] = false; } else { error("Bad option value.", v); } t = lex.token(); } else { if (o === '/*jshint' || o === '/*jslint') { error("Missing option value.", t); } obj[t.value] = false; t = v; } } if (filter) { assume(); } } // We need a peek function. If it has an argument, it peeks that much farther // ahead. It is used to distinguish // for ( var i in ... // from // for ( var i = ... function peek(p) { var i = p || 0, j = 0, t; while (j <= i) { t = lookahead[j]; if (!t) { t = lookahead[j] = lex.token(); } j += 1; } return t; } // Produce the next token. It looks for programming errors. function advance(id, t) { switch (token.id) { case '(number)': if (nexttoken.id === '.') { warning("A dot following a number can be confused with a decimal point.", token); } break; case '-': if (nexttoken.id === '-' || nexttoken.id === '--') { warning("Confusing minusses."); } break; case '+': if (nexttoken.id === '+' || nexttoken.id === '++') { warning("Confusing plusses."); } break; } if (token.type === '(string)' || token.identifier) { anonname = token.value; } if (id && nexttoken.id !== id) { if (t) { if (nexttoken.id === '(end)') { warning("Unmatched '{a}'.", t, t.id); } else { warning("Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", nexttoken, id, t.id, t.line, nexttoken.value); } } else if (nexttoken.type !== '(identifier)' || nexttoken.value !== id) { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, id, nexttoken.value); } } prevtoken = token; token = nexttoken; for (;;) { nexttoken = lookahead.shift() || lex.token(); if (nexttoken.id === '(end)' || nexttoken.id === '(error)') { return; } if (nexttoken.type === 'special') { doOption(); } else { if (nexttoken.id !== '(endline)') { break; } } } } // This is the heart of JSHINT, the Pratt parser. In addition to parsing, it // is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is // like .nud except that it is only used on the first token of a statement. // Having .fud makes it much easier to define statement-oriented languages like // JavaScript. I retained Pratt's nomenclature. // .nud Null denotation // .fud First null denotation // .led Left denotation // lbp Left binding power // rbp Right binding power // They are elements of the parsing method called Top Down Operator Precedence. function expression(rbp, initial) { var left, isArray = false, isObject = false; if (nexttoken.id === '(end)') error("Unexpected early end of program.", token); advance(); if (initial) { anonname = 'anonymous'; funct['(verb)'] = token.value; } if (initial === true && token.fud) { left = token.fud(); } else { if (token.nud) { left = token.nud(); } else { if (nexttoken.type === '(number)' && token.id === '.') { warning("A leading decimal point can be confused with a dot: '.{a}'.", token, nexttoken.value); advance(); return token; } else { error("Expected an identifier and instead saw '{a}'.", token, token.id); } } while (rbp < nexttoken.lbp) { isArray = token.value === 'Array'; isObject = token.value === 'Object'; advance(); if (isArray && token.id === '(' && nexttoken.id === ')') warning("Use the array literal notation [].", token); if (isObject && token.id === '(' && nexttoken.id === ')') warning("Use the object literal notation {}.", token); if (token.led) { left = token.led(left); } else { error("Expected an operator and instead saw '{a}'.", token, token.id); } } } return left; } // Functions for conformance of style. function adjacent(left, right) { left = left || token; right = right || nexttoken; if (option.white) { if (left.character !== right.from && left.line === right.line) { left.from += (left.character - left.from); warning("Unexpected space after '{a}'.", left, left.value); } } } function nobreak(left, right) { left = left || token; right = right || nexttoken; if (option.white && (left.character !== right.from || left.line !== right.line)) { warning("Unexpected space before '{a}'.", right, right.value); } } function nospace(left, right) { left = left || token; right = right || nexttoken; if (option.white && !left.comment) { if (left.line === right.line) { adjacent(left, right); } } } function nonadjacent(left, right) { if (option.white) { left = left || token; right = right || nexttoken; if (left.line === right.line && left.character === right.from) { left.from += (left.character - left.from); warning("Missing space after '{a}'.", left, left.value); } } } function nobreaknonadjacent(left, right) { left = left || token; right = right || nexttoken; if (!option.laxbreak && left.line !== right.line) { warning("Bad line breaking before '{a}'.", right, right.id); } else if (option.white) { left = left || token; right = right || nexttoken; if (left.character === right.from) { left.from += (left.character - left.from); warning("Missing space after '{a}'.", left, left.value); } } } function indentation(bias) { var i; if (option.white && nexttoken.id !== '(end)') { i = indent + (bias || 0); if (nexttoken.from !== i) { warning( "Expected '{a}' to have an indentation at {b} instead at {c}.", nexttoken, nexttoken.value, i, nexttoken.from); } } } function nolinebreak(t) { t = t || token; if (t.line !== nexttoken.line) { warning("Line breaking error '{a}'.", t, t.value); } } function comma() { if (token.line !== nexttoken.line) { if (!option.laxcomma) { if (comma.first) { warning("Comma warnings can be turned off with 'laxcomma'"); comma.first = false; } warning("Bad line breaking before '{a}'.", token, nexttoken.id); } } else if (!token.comment && token.character !== nexttoken.from && option.white) { token.from += (token.character - token.from); warning("Unexpected space after '{a}'.", token, token.value); } advance(','); nonadjacent(token, nexttoken); } // Functional constructors for making the symbols that will be inherited by // tokens. function symbol(s, p) { var x = syntax[s]; if (!x || typeof x !== 'object') { syntax[s] = x = { id: s, lbp: p, value: s }; } return x; } function delim(s) { return symbol(s, 0); } function stmt(s, f) { var x = delim(s); x.identifier = x.reserved = true; x.fud = f; return x; } function blockstmt(s, f) { var x = stmt(s, f); x.block = true; return x; } function reserveName(x) { var c = x.id.charAt(0); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { x.identifier = x.reserved = true; } return x; } function prefix(s, f) { var x = symbol(s, 150); reserveName(x); x.nud = (typeof f === 'function') ? f : function () { this.right = expression(150); this.arity = 'unary'; if (this.id === '++' || this.id === '--') { if (option.plusplus) { warning("Unexpected use of '{a}'.", this, this.id); } else if ((!this.right.identifier || this.right.reserved) && this.right.id !== '.' && this.right.id !== '[') { warning("Bad operand.", this); } } return this; }; return x; } function type(s, f) { var x = delim(s); x.type = s; x.nud = f; return x; } function reserve(s, f) { var x = type(s, f); x.identifier = x.reserved = true; return x; } function reservevar(s, v) { return reserve(s, function () { if (typeof v === 'function') { v(this); } return this; }); } function infix(s, f, p, w) { var x = symbol(s, p); reserveName(x); x.led = function (left) { if (!w) { nobreaknonadjacent(prevtoken, token); nonadjacent(token, nexttoken); } if (s === "in" && left.id === "!") { warning("Confusing use of '{a}'.", left, '!'); } if (typeof f === 'function') { return f(left, this); } else { this.left = left; this.right = expression(p); return this; } }; return x; } function relation(s, f) { var x = symbol(s, 100); x.led = function (left) { nobreaknonadjacent(prevtoken, token); nonadjacent(token, nexttoken); var right = expression(100); if ((left && left.id === 'NaN') || (right && right.id === 'NaN')) { warning("Use the isNaN function to compare with NaN.", this); } else if (f) { f.apply(this, [left, right]); } if (left.id === '!') { warning("Confusing use of '{a}'.", left, '!'); } if (right.id === '!') { warning("Confusing use of '{a}'.", right, '!'); } this.left = left; this.right = right; return this; }; return x; } function isPoorRelation(node) { return node && ((node.type === '(number)' && +node.value === 0) || (node.type === '(string)' && node.value === '') || (node.type === 'null' && !option.eqnull) || node.type === 'true' || node.type === 'false' || node.type === 'undefined'); } function assignop(s, f) { symbol(s, 20).exps = true; return infix(s, function (left, that) { var l; that.left = left; if (predefined[left.value] === false && scope[left.value]['(global)'] === true) { warning("Read only.", left); } else if (left['function']) { warning("'{a}' is a function.", left, left.value); } if (left) { if (option.esnext && funct[left.value] === 'const') { warning("Attempting to override '{a}' which is a constant", left, left.value); } if (left.id === '.' || left.id === '[') { if (!left.left || left.left.value === 'arguments') { warning('Bad assignment.', that); } that.right = expression(19); return that; } else if (left.identifier && !left.reserved) { if (funct[left.value] === 'exception') { warning("Do not assign to the exception parameter.", left); } that.right = expression(19); return that; } if (left === syntax['function']) { warning( "Expected an identifier in an assignment and instead saw a function invocation.", token); } } error("Bad assignment.", that); }, 20); } function bitwise(s, f, p) { var x = symbol(s, p); reserveName(x); x.led = (typeof f === 'function') ? f : function (left) { if (option.bitwise) { warning("Unexpected use of '{a}'.", this, this.id); } this.left = left; this.right = expression(p); return this; }; return x; } function bitwiseassignop(s) { symbol(s, 20).exps = true; return infix(s, function (left, that) { if (option.bitwise) { warning("Unexpected use of '{a}'.", that, that.id); } nonadjacent(prevtoken, token); nonadjacent(token, nexttoken); if (left) { if (left.id === '.' || left.id === '[' || (left.identifier && !left.reserved)) { expression(19); return that; } if (left === syntax['function']) { warning( "Expected an identifier in an assignment, and instead saw a function invocation.", token); } return that; } error("Bad assignment.", that); }, 20); } function suffix(s, f) { var x = symbol(s, 150); x.led = function (left) { if (option.plusplus) { warning("Unexpected use of '{a}'.", this, this.id); } else if ((!left.identifier || left.reserved) && left.id !== '.' && left.id !== '[') { warning("Bad operand.", this); } this.left = left; return this; }; return x; } // fnparam means that this identifier is being defined as a function // argument (see identifier()) function optionalidentifier(fnparam) { if (nexttoken.identifier) { advance(); if (token.reserved && !option.es5) { // `undefined` as a function param is a common pattern to protect // against the case when somebody does `undefined = true` and // help with minification. More info: https://gist.github.com/315916 if (!fnparam || token.value !== 'undefined') { warning("Expected an identifier and instead saw '{a}' (a reserved word).", token, token.id); } } return token.value; } } // fnparam means that this identifier is being defined as a function // argument function identifier(fnparam) { var i = optionalidentifier(fnparam); if (i) { return i; } if (token.id === 'function' && nexttoken.id === '(') { warning("Missing name in function declaration."); } else { error("Expected an identifier and instead saw '{a}'.", nexttoken, nexttoken.value); } } function reachable(s) { var i = 0, t; if (nexttoken.id !== ';' || noreach) { return; } for (;;) { t = peek(i); if (t.reach) { return; } if (t.id !== '(endline)') { if (t.id === 'function') { if (!option.latedef) { break; } warning( "Inner functions should be listed at the top of the outer function.", t); break; } warning("Unreachable '{a}' after '{b}'.", t, t.value, s); break; } i += 1; } } function statement(noindent) { var i = indent, r, s = scope, t = nexttoken; if (t.id === ";") { advance(";"); return; } // Is this a labelled statement? if (t.identifier && !t.reserved && peek().id === ':') { advance(); advance(':'); scope = Object.create(s); addlabel(t.value, 'label'); if (!nexttoken.labelled) { warning("Label '{a}' on {b} statement.", nexttoken, t.value, nexttoken.value); } if (jx.test(t.value + ':')) { warning("Label '{a}' looks like a javascript url.", t, t.value); } nexttoken.label = t.value; t = nexttoken; } // Parse the statement. if (!noindent) { indentation(); } r = expression(0, true); // Look for the final semicolon. if (!t.block) { if (!option.expr && (!r || !r.exps)) { warning("Expected an assignment or function call and instead saw an expression.", token); } else if (option.nonew && r.id === '(' && r.left.id === 'new') { warning("Do not use 'new' for side effects."); } if (nexttoken.id === ',') { return comma(); } if (nexttoken.id !== ';') { if (!option.asi) { // If this is the last statement in a block that ends on // the same line *and* option lastsemic is on, ignore the warning. // Otherwise, complain about missing semicolon. if (!option.lastsemic || nexttoken.id !== '}' || nexttoken.line !== token.line) { warningAt("Missing semicolon.", token.line, token.character); } } } else { adjacent(token, nexttoken); advance(';'); nonadjacent(token, nexttoken); } } // Restore the indentation. indent = i; scope = s; return r; } function statements(startLine) { var a = [], f, p; while (!nexttoken.reach && nexttoken.id !== '(end)') { if (nexttoken.id === ';') { p = peek(); if (!p || p.id !== "(") { warning("Unnecessary semicolon."); } advance(';'); } else { a.push(statement(startLine === nexttoken.line)); } } return a; } /* * read all directives * recognizes a simple form of asi, but always * warns, if it is used */ function directives() { var i, p, pn; for (;;) { if (nexttoken.id === "(string)") { p = peek(0); if (p.id === "(endline)") { i = 1; do { pn = peek(i); i = i + 1; } while (pn.id === "(endline)"); if (pn.id !== ";") { if (pn.id !== "(string)" && pn.id !== "(number)" && pn.id !== "(regexp)" && pn.identifier !== true && pn.id !== "}") { break; } warning("Missing semicolon.", nexttoken); } else { p = pn; } } else if (p.id === "}") { // directive with no other statements, warn about missing semicolon warning("Missing semicolon.", p); } else if (p.id !== ";") { break; } indentation(); advance(); if (directive[token.value]) { warning("Unnecessary directive \"{a}\".", token, token.value); } if (token.value === "use strict") { option.newcap = true; option.undef = true; } // there's no directive negation, so always set to true directive[token.value] = true; if (p.id === ";") { advance(";"); } continue; } break; } } /* * Parses a single block. A block is a sequence of statements wrapped in * braces. * * ordinary - true for everything but function bodies and try blocks. * stmt - true if block can be a single statement (e.g. in if/for/while). * isfunc - true if block is a function body */ function block(ordinary, stmt, isfunc) { var a, b = inblock, old_indent = indent, m, s = scope, t, line, d; inblock = ordinary; if (!ordinary || !option.funcscope) scope = Object.create(scope); nonadjacent(token, nexttoken); t = nexttoken; if (nexttoken.id === '{') { advance('{'); line = token.line; if (nexttoken.id !== '}') { indent += option.indent; while (!ordinary && nexttoken.from > indent) { indent += option.indent; } if (isfunc) { m = {}; for (d in directive) { if (is_own(directive, d)) { m[d] = directive[d]; } } directives(); if (option.strict && funct['(context)']['(global)']) { if (!m["use strict"] && !directive["use strict"]) { warning("Missing \"use strict\" statement."); } } } a = statements(line); if (isfunc) { directive = m; } indent -= option.indent; if (line !== nexttoken.line) { indentation(); } } else if (line !== nexttoken.line) { indentation(); } advance('}', t); indent = old_indent; } else if (!ordinary) { error("Expected '{a}' and instead saw '{b}'.", nexttoken, '{', nexttoken.value); } else { if (!stmt || option.curly) warning("Expected '{a}' and instead saw '{b}'.", nexttoken, '{', nexttoken.value); noreach = true; indent += option.indent; // test indentation only if statement is in new line a = [statement(nexttoken.line === token.line)]; indent -= option.indent; noreach = false; } funct['(verb)'] = null; if (!ordinary || !option.funcscope) scope = s; inblock = b; if (ordinary && option.noempty && (!a || a.length === 0)) { warning("Empty block."); } return a; } function countMember(m) { if (membersOnly && typeof membersOnly[m] !== 'boolean') { warning("Unexpected /*member '{a}'.", token, m); } if (typeof member[m] === 'number') { member[m] += 1; } else { member[m] = 1; } } function note_implied(token) { var name = token.value, line = token.line, a = implied[name]; if (typeof a === 'function') { a = false; } if (!a) { a = [line]; implied[name] = a; } else if (a[a.length - 1] !== line) { a.push(line); } } // Build the syntax table by declaring the syntactic elements of the language. type('(number)', function () { return this; }); type('(string)', function () { return this; }); syntax['(identifier)'] = { type: '(identifier)', lbp: 0, identifier: true, nud: function () { var v = this.value, s = scope[v], f; if (typeof s === 'function') { // Protection against accidental inheritance. s = undefined; } else if (typeof s === 'boolean') { f = funct; funct = functions[0]; addlabel(v, 'var'); s = funct; funct = f; } // The name is in scope and defined in the current function. if (funct === s) { // Change 'unused' to 'var', and reject labels. switch (funct[v]) { case 'unused': funct[v] = 'var'; break; case 'unction': funct[v] = 'function'; this['function'] = true; break; case 'function': this['function'] = true; break; case 'label': warning("'{a}' is a statement label.", token, v); break; } } else if (funct['(global)']) { // The name is not defined in the function. If we are in the global // scope, then we have an undefined variable. // // Operators typeof and delete do not raise runtime errors even if // the base object of a reference is null so no need to display warning // if we're inside of typeof or delete. if (option.undef && typeof predefined[v] !== 'boolean') { // Attempting to subscript a null reference will throw an // error, even within the typeof and delete operators if (!(anonname === 'typeof' || anonname === 'delete') || (nexttoken && (nexttoken.value === '.' || nexttoken.value === '['))) { isundef(funct, "'{a}' is not defined.", token, v); } } note_implied(token); } else { // If the name is already defined in the current // function, but not as outer, then there is a scope error. switch (funct[v]) { case 'closure': case 'function': case 'var': case 'unused': warning("'{a}' used out of scope.", token, v); break; case 'label': warning("'{a}' is a statement label.", token, v); break; case 'outer': case 'global': break; default: // If the name is defined in an outer function, make an outer entry, // and if it was unused, make it var. if (s === true) { funct[v] = true; } else if (s === null) { warning("'{a}' is not allowed.", token, v); note_implied(token); } else if (typeof s !== 'object') { // Operators typeof and delete do not raise runtime errors even // if the base object of a reference is null so no need to // display warning if we're inside of typeof or delete. if (option.undef) { // Attempting to subscript a null reference will throw an // error, even within the typeof and delete operators if (!(anonname === 'typeof' || anonname === 'delete') || (nexttoken && (nexttoken.value === '.' || nexttoken.value === '['))) { isundef(funct, "'{a}' is not defined.", token, v); } } funct[v] = true; note_implied(token); } else { switch (s[v]) { case 'function': case 'unction': this['function'] = true; s[v] = 'closure'; funct[v] = s['(global)'] ? 'global' : 'outer'; break; case 'var': case 'unused': s[v] = 'closure'; funct[v] = s['(global)'] ? 'global' : 'outer'; break; case 'closure': case 'parameter': funct[v] = s['(global)'] ? 'global' : 'outer'; break; case 'label': warning("'{a}' is a statement label.", token, v); } } } } return this; }, led: function () { error("Expected an operator and instead saw '{a}'.", nexttoken, nexttoken.value); } }; type('(regexp)', function () { return this; }); // ECMAScript parser delim('(endline)'); delim('(begin)'); delim('(end)').reach = true; delim('</').reach = true; delim('<!'); delim('<!--'); delim('-->'); delim('(error)').reach = true; delim('}').reach = true; delim(')'); delim(']'); delim('"').reach = true; delim("'").reach = true; delim(';'); delim(':').reach = true; delim(','); delim('#'); delim('@'); reserve('else'); reserve('case').reach = true; reserve('catch'); reserve('default').reach = true; reserve('finally'); reservevar('arguments', function (x) { if (directive['use strict'] && funct['(global)']) { warning("Strict violation.", x); } }); reservevar('eval'); reservevar('false'); reservevar('Infinity'); reservevar('NaN'); reservevar('null'); reservevar('this', function (x) { if (directive['use strict'] && !option.validthis && ((funct['(statement)'] && funct['(name)'].charAt(0) > 'Z') || funct['(global)'])) { warning("Possible strict violation.", x); } }); reservevar('true'); reservevar('undefined'); assignop('=', 'assign', 20); assignop('+=', 'assignadd', 20); assignop('-=', 'assignsub', 20); assignop('*=', 'assignmult', 20); assignop('/=', 'assigndiv', 20).nud = function () { error("A regular expression literal can be confused with '/='."); }; assignop('%=', 'assignmod', 20); bitwiseassignop('&=', 'assignbitand', 20); bitwiseassignop('|=', 'assignbitor', 20); bitwiseassignop('^=', 'assignbitxor', 20); bitwiseassignop('<<=', 'assignshiftleft', 20); bitwiseassignop('>>=', 'assignshiftright', 20); bitwiseassignop('>>>=', 'assignshiftrightunsigned', 20); infix('?', function (left, that) { that.left = left; that.right = expression(10); advance(':'); that['else'] = expression(10); return that; }, 30); infix('||', 'or', 40); infix('&&', 'and', 50); bitwise('|', 'bitor', 70); bitwise('^', 'bitxor', 80); bitwise('&', 'bitand', 90); relation('==', function (left, right) { var eqnull = option.eqnull && (left.value === 'null' || right.value === 'null'); if (!eqnull && option.eqeqeq) warning("Expected '{a}' and instead saw '{b}'.", this, '===', '=='); else if (isPoorRelation(left)) warning("Use '{a}' to compare with '{b}'.", this, '===', left.value); else if (isPoorRelation(right)) warning("Use '{a}' to compare with '{b}'.", this, '===', right.value); return this; }); relation('==='); relation('!=', function (left, right) { var eqnull = option.eqnull && (left.value === 'null' || right.value === 'null'); if (!eqnull && option.eqeqeq) { warning("Expected '{a}' and instead saw '{b}'.", this, '!==', '!='); } else if (isPoorRelation(left)) { warning("Use '{a}' to compare with '{b}'.", this, '!==', left.value); } else if (isPoorRelation(right)) { warning("Use '{a}' to compare with '{b}'.", this, '!==', right.value); } return this; }); relation('!=='); relation('<'); relation('>'); relation('<='); relation('>='); bitwise('<<', 'shiftleft', 120); bitwise('>>', 'shiftright', 120); bitwise('>>>', 'shiftrightunsigned', 120); infix('in', 'in', 120); infix('instanceof', 'instanceof', 120); infix('+', function (left, that) { var right = expression(130); if (left && right && left.id === '(string)' && right.id === '(string)') { left.value += right.value; left.character = right.character; if (!option.scripturl && jx.test(left.value)) { warning("JavaScript URL.", left); } return left; } that.left = left; that.right = right; return that; }, 130); prefix('+', 'num'); prefix('+++', function () { warning("Confusing pluses."); this.right = expression(150); this.arity = 'unary'; return this; }); infix('+++', function (left) { warning("Confusing pluses."); this.left = left; this.right = expression(130); return this; }, 130); infix('-', 'sub', 130); prefix('-', 'neg'); prefix('---', function () { warning("Confusing minuses."); this.right = expression(150); this.arity = 'unary'; return this; }); infix('---', function (left) { warning("Confusing minuses."); this.left = left; this.right = expression(130); return this; }, 130); infix('*', 'mult', 140); infix('/', 'div', 140); infix('%', 'mod', 140); suffix('++', 'postinc'); prefix('++', 'preinc'); syntax['++'].exps = true; suffix('--', 'postdec'); prefix('--', 'predec'); syntax['--'].exps = true; prefix('delete', function () { var p = expression(0); if (!p || (p.id !== '.' && p.id !== '[')) { warning("Variables should not be deleted."); } this.first = p; return this; }).exps = true; prefix('~', function () { if (option.bitwise) { warning("Unexpected '{a}'.", this, '~'); } expression(150); return this; }); prefix('!', function () { this.right = expression(150); this.arity = 'unary'; if (bang[this.right.id] === true) { warning("Confusing use of '{a}'.", this, '!'); } return this; }); prefix('typeof', 'typeof'); prefix('new', function () { var c = expression(155), i; if (c && c.id !== 'function') { if (c.identifier) { c['new'] = true; switch (c.value) { case 'Number': case 'String': case 'Boolean': case 'Math': case 'JSON': warning("Do not use {a} as a constructor.", token, c.value); break; case 'Function': if (!option.evil) { warning("The Function constructor is eval."); } break; case 'Date': case 'RegExp': break; default: if (c.id !== 'function') { i = c.value.substr(0, 1); if (option.newcap && (i < 'A' || i > 'Z')) { warning("A constructor name should start with an uppercase letter.", token); } } } } else { if (c.id !== '.' && c.id !== '[' && c.id !== '(') { warning("Bad constructor.", token); } } } else { if (!option.supernew) warning("Weird construction. Delete 'new'.", this); } adjacent(token, nexttoken); if (nexttoken.id !== '(' && !option.supernew) { warning("Missing '()' invoking a constructor."); } this.first = c; return this; }); syntax['new'].exps = true; prefix('void').exps = true; infix('.', function (left, that) { adjacent(prevtoken, token); nobreak(); var m = identifier(); if (typeof m === 'string') { countMember(m); } that.left = left; that.right = m; if (left && left.value === 'arguments' && (m === 'callee' || m === 'caller')) { if (option.noarg) warning("Avoid arguments.{a}.", left, m); else if (directive['use strict']) error('Strict violation.'); } else if (!option.evil && left && left.value === 'document' && (m === 'write' || m === 'writeln')) { warning("document.write can be a form of eval.", left); } if (!option.evil && (m === 'eval' || m === 'execScript')) { warning('eval is evil.'); } return that; }, 160, true); infix('(', function (left, that) { if (prevtoken.id !== '}' && prevtoken.id !== ')') { nobreak(prevtoken, token); } nospace(); if (option.immed && !left.immed && left.id === 'function') { warning("Wrap an immediate function invocation in parentheses " + "to assist the reader in understanding that the expression " + "is the result of a function, and not the function itself."); } var n = 0, p = []; if (left) { if (left.type === '(identifier)') { if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { if (left.value !== 'Number' && left.value !== 'String' && left.value !== 'Boolean' && left.value !== 'Date') { if (left.value === 'Math') { warning("Math is not a function.", left); } else if (option.newcap) { warning( "Missing 'new' prefix when invoking a constructor.", left); } } } } } if (nexttoken.id !== ')') { for (;;) { p[p.length] = expression(10); n += 1; if (nexttoken.id !== ',') { break; } comma(); } } advance(')'); nospace(prevtoken, token); if (typeof left === 'object') { if (left.value === 'parseInt' && n === 1) { warning("Missing radix parameter.", left); } if (!option.evil) { if (left.value === 'eval' || left.value === 'Function' || left.value === 'execScript') { warning("eval is evil.", left); } else if (p[0] && p[0].id === '(string)' && (left.value === 'setTimeout' || left.value === 'setInterval')) { warning( "Implied eval is evil. Pass a function instead of a string.", left); } } if (!left.identifier && left.id !== '.' && left.id !== '[' && left.id !== '(' && left.id !== '&&' && left.id !== '||' && left.id !== '?') { warning("Bad invocation.", left); } } that.left = left; return that; }, 155, true).exps = true; prefix('(', function () { nospace(); if (nexttoken.id === 'function') { nexttoken.immed = true; } var v = expression(0); advance(')', this); nospace(prevtoken, token); if (option.immed && v.id === 'function') { if (nexttoken.id === '(' || (nexttoken.id === '.' && (peek().value === 'call' || peek().value === 'apply'))) { warning( "Move the invocation into the parens that contain the function.", nexttoken); } else { warning( "Do not wrap function literals in parens unless they are to be immediately invoked.", this); } } return v; }); infix('[', function (left, that) { nobreak(prevtoken, token); nospace(); var e = expression(0), s; if (e && e.type === '(string)') { if (!option.evil && (e.value === 'eval' || e.value === 'execScript')) { warning("eval is evil.", that); } countMember(e.value); if (!option.sub && ix.test(e.value)) { s = syntax[e.value]; if (!s || !s.reserved) { warning("['{a}'] is better written in dot notation.", e, e.value); } } } advance(']', that); nospace(prevtoken, token); that.left = left; that.right = e; return that; }, 160, true); prefix('[', function () { var b = token.line !== nexttoken.line; this.first = []; if (b) { indent += option.indent; if (nexttoken.from === indent + option.indent) { indent += option.indent; } } while (nexttoken.id !== '(end)') { while (nexttoken.id === ',') { warning("Extra comma."); advance(','); } if (nexttoken.id === ']') { break; } if (b && token.line !== nexttoken.line) { indentation(); } this.first.push(expression(10)); if (nexttoken.id === ',') { comma(); if (nexttoken.id === ']' && !option.es5) { warning("Extra comma.", token); break; } } else { break; } } if (b) { indent -= option.indent; indentation(); } advance(']', this); return this; }, 160); function property_name() { var id = optionalidentifier(true); if (!id) { if (nexttoken.id === '(string)') { id = nexttoken.value; advance(); } else if (nexttoken.id === '(number)') { id = nexttoken.value.toString(); advance(); } } return id; } function functionparams() { var i, t = nexttoken, p = []; advance('('); nospace(); if (nexttoken.id === ')') { advance(')'); return; } for (;;) { i = identifier(true); p.push(i); addlabel(i, 'parameter'); if (nexttoken.id === ',') { comma(); } else { advance(')', t); nospace(prevtoken, token); return p; } } } function doFunction(i, statement) { var f, oldOption = option, oldScope = scope; option = Object.create(option); scope = Object.create(scope); funct = { '(name)' : i || '"' + anonname + '"', '(line)' : nexttoken.line, '(context)' : funct, '(breakage)' : 0, '(loopage)' : 0, '(scope)' : scope, '(statement)': statement }; f = funct; token.funct = funct; functions.push(funct); if (i) { addlabel(i, 'function'); } funct['(params)'] = functionparams(); block(false, false, true); scope = oldScope; option = oldOption; funct['(last)'] = token.line; funct = funct['(context)']; return f; } (function (x) { x.nud = function () { var b, f, i, j, p, t; var props = {}; // All properties, including accessors function saveProperty(name, token) { if (props[name] && is_own(props, name)) warning("Duplicate member '{a}'.", nexttoken, i); else props[name] = {}; props[name].basic = true; props[name].basicToken = token; } function saveSetter(name, token) { if (props[name] && is_own(props, name)) { if (props[name].basic || props[name].setter) warning("Duplicate member '{a}'.", nexttoken, i); } else { props[name] = {}; } props[name].setter = true; props[name].setterToken = token; } function saveGetter(name) { if (props[name] && is_own(props, name)) { if (props[name].basic || props[name].getter) warning("Duplicate member '{a}'.", nexttoken, i); } else { props[name] = {}; } props[name].getter = true; props[name].getterToken = token; } b = token.line !== nexttoken.line; if (b) { indent += option.indent; if (nexttoken.from === indent + option.indent) { indent += option.indent; } } for (;;) { if (nexttoken.id === '}') { break; } if (b) { indentation(); } if (nexttoken.value === 'get' && peek().id !== ':') { advance('get'); if (!option.es5) { error("get/set are ES5 features."); } i = property_name(); if (!i) { error("Missing property name."); } saveGetter(i); t = nexttoken; adjacent(token, nexttoken); f = doFunction(); p = f['(params)']; if (p) { warning("Unexpected parameter '{a}' in get {b} function.", t, p[0], i); } adjacent(token, nexttoken); } else if (nexttoken.value === 'set' && peek().id !== ':') { advance('set'); if (!option.es5) { error("get/set are ES5 features."); } i = property_name(); if (!i) { error("Missing property name."); } saveSetter(i, nexttoken); t = nexttoken; adjacent(token, nexttoken); f = doFunction(); p = f['(params)']; if (!p || p.length !== 1) { warning("Expected a single parameter in set {a} function.", t, i); } } else { i = property_name(); saveProperty(i, nexttoken); if (typeof i !== 'string') { break; } advance(':'); nonadjacent(token, nexttoken); expression(10); } countMember(i); if (nexttoken.id === ',') { comma(); if (nexttoken.id === ',') { warning("Extra comma.", token); } else if (nexttoken.id === '}' && !option.es5) { warning("Extra comma.", token); } } else { break; } } if (b) { indent -= option.indent; indentation(); } advance('}', this); // Check for lonely setters if in the ES5 mode. if (option.es5) { for (var name in props) { if (is_own(props, name) && props[name].setter && !props[name].getter) { warning("Setter is defined without getter.", props[name].setterToken); } } } return this; }; x.fud = function () { error("Expected to see a statement and instead saw a block.", token); }; }(delim('{'))); // This Function is called when esnext option is set to true // it adds the `const` statement to JSHINT useESNextSyntax = function () { var conststatement = stmt('const', function (prefix) { var id, name, value; this.first = []; for (;;) { nonadjacent(token, nexttoken); id = identifier(); if (funct[id] === "const") { warning("const '" + id + "' has already been declared"); } if (funct['(global)'] && predefined[id] === false) { warning("Redefinition of '{a}'.", token, id); } addlabel(id, 'const'); if (prefix) { break; } name = token; this.first.push(token); if (nexttoken.id !== "=") { warning("const " + "'{a}' is initialized to 'undefined'.", token, id); } if (nexttoken.id === '=') { nonadjacent(token, nexttoken); advance('='); nonadjacent(token, nexttoken); if (nexttoken.id === 'undefined') { warning("It is not necessary to initialize " + "'{a}' to 'undefined'.", token, id); } if (peek(0).id === '=' && nexttoken.identifier) { error("Constant {a} was not declared correctly.", nexttoken, nexttoken.value); } value = expression(0); name.first = value; } if (nexttoken.id !== ',') { break; } comma(); } return this; }); conststatement.exps = true; }; var varstatement = stmt('var', function (prefix) { // JavaScript does not have block scope. It only has function scope. So, // declaring a variable in a block can have unexpected consequences. var id, name, value; if (funct['(onevar)'] && option.onevar) { warning("Too many var statements."); } else if (!funct['(global)']) { funct['(onevar)'] = true; } this.first = []; for (;;) { nonadjacent(token, nexttoken); id = identifier(); if (option.esnext && funct[id] === "const") { warning("const '" + id + "' has already been declared"); } if (funct['(global)'] && predefined[id] === false) { warning("Redefinition of '{a}'.", token, id); } addlabel(id, 'unused'); if (prefix) { break; } name = token; this.first.push(token); if (nexttoken.id === '=') { nonadjacent(token, nexttoken); advance('='); nonadjacent(token, nexttoken); if (nexttoken.id === 'undefined') { warning("It is not necessary to initialize '{a}' to 'undefined'.", token, id); } if (peek(0).id === '=' && nexttoken.identifier) { error("Variable {a} was not declared correctly.", nexttoken, nexttoken.value); } value = expression(0); name.first = value; } if (nexttoken.id !== ',') { break; } comma(); } return this; }); varstatement.exps = true; blockstmt('function', function () { if (inblock) { warning("Function declarations should not be placed in blocks. " + "Use a function expression or move the statement to the top of " + "the outer function.", token); } var i = identifier(); if (option.esnext && funct[i] === "const") { warning("const '" + i + "' has already been declared"); } adjacent(token, nexttoken); addlabel(i, 'unction'); doFunction(i, true); if (nexttoken.id === '(' && nexttoken.line === token.line) { error( "Function declarations are not invocable. Wrap the whole function invocation in parens."); } return this; }); prefix('function', function () { var i = optionalidentifier(); if (i) { adjacent(token, nexttoken); } else { nonadjacent(token, nexttoken); } doFunction(i); if (!option.loopfunc && funct['(loopage)']) { warning("Don't make functions within a loop."); } return this; }); blockstmt('if', function () { var t = nexttoken; advance('('); nonadjacent(this, t); nospace(); expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } advance(')', t); nospace(prevtoken, token); block(true, true); if (nexttoken.id === 'else') { nonadjacent(token, nexttoken); advance('else'); if (nexttoken.id === 'if' || nexttoken.id === 'switch') { statement(true); } else { block(true, true); } } return this; }); blockstmt('try', function () { var b, e, s; block(false); if (nexttoken.id === 'catch') { advance('catch'); nonadjacent(token, nexttoken); advance('('); s = scope; scope = Object.create(s); e = nexttoken.value; if (nexttoken.type !== '(identifier)') { warning("Expected an identifier and instead saw '{a}'.", nexttoken, e); } else { addlabel(e, 'exception'); } advance(); advance(')'); block(false); b = true; scope = s; } if (nexttoken.id === 'finally') { advance('finally'); block(false); return; } else if (!b) { error("Expected '{a}' and instead saw '{b}'.", nexttoken, 'catch', nexttoken.value); } return this; }); blockstmt('while', function () { var t = nexttoken; funct['(breakage)'] += 1; funct['(loopage)'] += 1; advance('('); nonadjacent(this, t); nospace(); expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } advance(')', t); nospace(prevtoken, token); block(true, true); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; }).labelled = true; blockstmt('with', function () { var t = nexttoken; if (directive['use strict']) { error("'with' is not allowed in strict mode.", token); } else if (!option.withstmt) { warning("Don't use 'with'.", token); } advance('('); nonadjacent(this, t); nospace(); expression(0); advance(')', t); nospace(prevtoken, token); block(true, true); return this; }); blockstmt('switch', function () { var t = nexttoken, g = false; funct['(breakage)'] += 1; advance('('); nonadjacent(this, t); nospace(); this.condition = expression(20); advance(')', t); nospace(prevtoken, token); nonadjacent(token, nexttoken); t = nexttoken; advance('{'); nonadjacent(token, nexttoken); indent += option.indent; this.cases = []; for (;;) { switch (nexttoken.id) { case 'case': switch (funct['(verb)']) { case 'break': case 'case': case 'continue': case 'return': case 'switch': case 'throw': break; default: // You can tell JSHint that you don't use break intentionally by // adding a comment /* falls through */ on a line just before // the next `case`. if (!ft.test(lines[nexttoken.line - 2])) { warning( "Expected a 'break' statement before 'case'.", token); } } indentation(-option.indent); advance('case'); this.cases.push(expression(20)); g = true; advance(':'); funct['(verb)'] = 'case'; break; case 'default': switch (funct['(verb)']) { case 'break': case 'continue': case 'return': case 'throw': break; default: if (!ft.test(lines[nexttoken.line - 2])) { warning( "Expected a 'break' statement before 'default'.", token); } } indentation(-option.indent); advance('default'); g = true; advance(':'); break; case '}': indent -= option.indent; indentation(); advance('}', t); if (this.cases.length === 1 || this.condition.id === 'true' || this.condition.id === 'false') { if (!option.onecase) warning("This 'switch' should be an 'if'.", this); } funct['(breakage)'] -= 1; funct['(verb)'] = undefined; return; case '(end)': error("Missing '{a}'.", nexttoken, '}'); return; default: if (g) { switch (token.id) { case ',': error("Each value should have its own case label."); return; case ':': g = false; statements(); break; default: error("Missing ':' on a case clause.", token); return; } } else { if (token.id === ':') { advance(':'); error("Unexpected '{a}'.", token, ':'); statements(); } else { error("Expected '{a}' and instead saw '{b}'.", nexttoken, 'case', nexttoken.value); return; } } } } }).labelled = true; stmt('debugger', function () { if (!option.debug) { warning("All 'debugger' statements should be removed."); } return this; }).exps = true; (function () { var x = stmt('do', function () { funct['(breakage)'] += 1; funct['(loopage)'] += 1; this.first = block(true); advance('while'); var t = nexttoken; nonadjacent(token, t); advance('('); nospace(); expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } advance(')', t); nospace(prevtoken, token); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; }); x.labelled = true; x.exps = true; }()); blockstmt('for', function () { var s, t = nexttoken; funct['(breakage)'] += 1; funct['(loopage)'] += 1; advance('('); nonadjacent(this, t); nospace(); if (peek(nexttoken.id === 'var' ? 1 : 0).id === 'in') { if (nexttoken.id === 'var') { advance('var'); varstatement.fud.call(varstatement, true); } else { switch (funct[nexttoken.value]) { case 'unused': funct[nexttoken.value] = 'var'; break; case 'var': break; default: warning("Bad for in variable '{a}'.", nexttoken, nexttoken.value); } advance(); } advance('in'); expression(20); advance(')', t); s = block(true, true); if (option.forin && s && (s.length > 1 || typeof s[0] !== 'object' || s[0].value !== 'if')) { warning("The body of a for in should be wrapped in an if statement to filter " + "unwanted properties from the prototype.", this); } funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; } else { if (nexttoken.id !== ';') { if (nexttoken.id === 'var') { advance('var'); varstatement.fud.call(varstatement); } else { for (;;) { expression(0, 'for'); if (nexttoken.id !== ',') { break; } comma(); } } } nolinebreak(token); advance(';'); if (nexttoken.id !== ';') { expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } } nolinebreak(token); advance(';'); if (nexttoken.id === ';') { error("Expected '{a}' and instead saw '{b}'.", nexttoken, ')', ';'); } if (nexttoken.id !== ')') { for (;;) { expression(0, 'for'); if (nexttoken.id !== ',') { break; } comma(); } } advance(')', t); nospace(prevtoken, token); block(true, true); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; } }).labelled = true; stmt('break', function () { var v = nexttoken.value; if (funct['(breakage)'] === 0) warning("Unexpected '{a}'.", nexttoken, this.value); if (!option.asi) nolinebreak(this); if (nexttoken.id !== ';') { if (token.line === nexttoken.line) { if (funct[v] !== 'label') { warning("'{a}' is not a statement label.", nexttoken, v); } else if (scope[v] !== funct) { warning("'{a}' is out of scope.", nexttoken, v); } this.first = nexttoken; advance(); } } reachable('break'); return this; }).exps = true; stmt('continue', function () { var v = nexttoken.value; if (funct['(breakage)'] === 0) warning("Unexpected '{a}'.", nexttoken, this.value); if (!option.asi) nolinebreak(this); if (nexttoken.id !== ';') { if (token.line === nexttoken.line) { if (funct[v] !== 'label') { warning("'{a}' is not a statement label.", nexttoken, v); } else if (scope[v] !== funct) { warning("'{a}' is out of scope.", nexttoken, v); } this.first = nexttoken; advance(); } } else if (!funct['(loopage)']) { warning("Unexpected '{a}'.", nexttoken, this.value); } reachable('continue'); return this; }).exps = true; stmt('return', function () { if (this.line === nexttoken.line) { if (nexttoken.id === '(regexp)') warning("Wrap the /regexp/ literal in parens to disambiguate the slash operator."); if (nexttoken.id !== ';' && !nexttoken.reach) { nonadjacent(token, nexttoken); if (peek().value === "=" && !option.boss) { warningAt("Did you mean to return a conditional instead of an assignment?", token.line, token.character + 1); } this.first = expression(0); } } else if (!option.asi) { nolinebreak(this); // always warn (Line breaking error) } reachable('return'); return this; }).exps = true; stmt('throw', function () { nolinebreak(this); nonadjacent(token, nexttoken); this.first = expression(20); reachable('throw'); return this; }).exps = true; // Superfluous reserved words reserve('class'); reserve('const'); reserve('enum'); reserve('export'); reserve('extends'); reserve('import'); reserve('super'); reserve('let'); reserve('yield'); reserve('implements'); reserve('interface'); reserve('package'); reserve('private'); reserve('protected'); reserve('public'); reserve('static'); // Parse JSON function jsonValue() { function jsonObject() { var o = {}, t = nexttoken; advance('{'); if (nexttoken.id !== '}') { for (;;) { if (nexttoken.id === '(end)') { error("Missing '}' to match '{' from line {a}.", nexttoken, t.line); } else if (nexttoken.id === '}') { warning("Unexpected comma.", token); break; } else if (nexttoken.id === ',') { error("Unexpected comma.", nexttoken); } else if (nexttoken.id !== '(string)') { warning("Expected a string and instead saw {a}.", nexttoken, nexttoken.value); } if (o[nexttoken.value] === true) { warning("Duplicate key '{a}'.", nexttoken, nexttoken.value); } else if ((nexttoken.value === '__proto__' && !option.proto) || (nexttoken.value === '__iterator__' && !option.iterator)) { warning("The '{a}' key may produce unexpected results.", nexttoken, nexttoken.value); } else { o[nexttoken.value] = true; } advance(); advance(':'); jsonValue(); if (nexttoken.id !== ',') { break; } advance(','); } } advance('}'); } function jsonArray() { var t = nexttoken; advance('['); if (nexttoken.id !== ']') { for (;;) { if (nexttoken.id === '(end)') { error("Missing ']' to match '[' from line {a}.", nexttoken, t.line); } else if (nexttoken.id === ']') { warning("Unexpected comma.", token); break; } else if (nexttoken.id === ',') { error("Unexpected comma.", nexttoken); } jsonValue(); if (nexttoken.id !== ',') { break; } advance(','); } } advance(']'); } switch (nexttoken.id) { case '{': jsonObject(); break; case '[': jsonArray(); break; case 'true': case 'false': case 'null': case '(number)': case '(string)': advance(); break; case '-': advance('-'); if (token.character !== nexttoken.from) { warning("Unexpected space after '-'.", token); } adjacent(token, nexttoken); advance('(number)'); break; default: error("Expected a JSON value.", nexttoken); } } // The actual JSHINT function itself. var itself = function (s, o, g) { var a, i, k; JSHINT.errors = []; JSHINT.undefs = []; predefined = Object.create(standard); combine(predefined, g || {}); if (o) { a = o.predef; if (a) { if (Array.isArray(a)) { for (i = 0; i < a.length; i += 1) { predefined[a[i]] = true; } } else if (typeof a === 'object') { k = Object.keys(a); for (i = 0; i < k.length; i += 1) { predefined[k[i]] = !!a[k[i]]; } } } option = o; } else { option = {}; } option.indent = option.indent || 4; option.maxerr = option.maxerr || 50; tab = ''; for (i = 0; i < option.indent; i += 1) { tab += ' '; } indent = 1; global = Object.create(predefined); scope = global; funct = { '(global)': true, '(name)': '(global)', '(scope)': scope, '(breakage)': 0, '(loopage)': 0 }; functions = [funct]; urls = []; stack = null; member = {}; membersOnly = null; implied = {}; inblock = false; lookahead = []; jsonmode = false; warnings = 0; lex.init(s); prereg = true; directive = {}; prevtoken = token = nexttoken = syntax['(begin)']; // Check options for (var name in o) { if (is_own(o, name)) { checkOption(name, token); } } assume(); // combine the passed globals after we've assumed all our options combine(predefined, g || {}); //reset values comma.first = true; try { advance(); switch (nexttoken.id) { case '{': case '[': option.laxbreak = true; jsonmode = true; jsonValue(); break; default: directives(); if (directive["use strict"] && !option.globalstrict) { warning("Use the function form of \"use strict\".", prevtoken); } statements(); } advance('(end)'); var markDefined = function (name, context) { do { if (typeof context[name] === 'string') { // JSHINT marks unused variables as 'unused' and // unused function declaration as 'unction'. This // code changes such instances back 'var' and // 'closure' so that the code in JSHINT.data() // doesn't think they're unused. if (context[name] === 'unused') context[name] = 'var'; else if (context[name] === 'unction') context[name] = 'closure'; return true; } context = context['(context)']; } while (context); return false; }; var clearImplied = function (name, line) { if (!implied[name]) return; var newImplied = []; for (var i = 0; i < implied[name].length; i += 1) { if (implied[name][i] !== line) newImplied.push(implied[name][i]); } if (newImplied.length === 0) delete implied[name]; else implied[name] = newImplied; }; // Check queued 'x is not defined' instances to see if they're still undefined. for (i = 0; i < JSHINT.undefs.length; i += 1) { k = JSHINT.undefs[i].slice(0); if (markDefined(k[2].value, k[0])) { clearImplied(k[2].value, k[2].line); } else { warning.apply(warning, k.slice(1)); } } } catch (e) { if (e) { var nt = nexttoken || {}; JSHINT.errors.push({ raw : e.raw, reason : e.message, line : e.line || nt.line, character : e.character || nt.from }, null); } } return JSHINT.errors.length === 0; }; // Data summary. itself.data = function () { var data = { functions: [], options: option }, fu, globals, implieds = [], f, i, j, members = [], n, unused = [], v; if (itself.errors.length) { data.errors = itself.errors; } if (jsonmode) { data.json = true; } for (n in implied) { if (is_own(implied, n)) { implieds.push({ name: n, line: implied[n] }); } } if (implieds.length > 0) { data.implieds = implieds; } if (urls.length > 0) { data.urls = urls; } globals = Object.keys(scope); if (globals.length > 0) { data.globals = globals; } for (i = 1; i < functions.length; i += 1) { f = functions[i]; fu = {}; for (j = 0; j < functionicity.length; j += 1) { fu[functionicity[j]] = []; } for (n in f) { if (is_own(f, n) && n.charAt(0) !== '(') { v = f[n]; if (v === 'unction') { v = 'unused'; } if (Array.isArray(fu[v])) { fu[v].push(n); if (v === 'unused') { unused.push({ name: n, line: f['(line)'], 'function': f['(name)'] }); } } } } for (j = 0; j < functionicity.length; j += 1) { if (fu[functionicity[j]].length === 0) { delete fu[functionicity[j]]; } } fu.name = f['(name)']; fu.param = f['(params)']; fu.line = f['(line)']; fu.last = f['(last)']; data.functions.push(fu); } if (unused.length > 0) { data.unused = unused; } members = []; for (n in member) { if (typeof member[n] === 'number') { data.member = member; break; } } return data; }; itself.report = function (option) { var data = itself.data(); var a = [], c, e, err, f, i, k, l, m = '', n, o = [], s; function detail(h, array) { var b, i, singularity; if (array) { o.push('<div><i>' + h + '</i> '); array = array.sort(); for (i = 0; i < array.length; i += 1) { if (array[i] !== singularity) { singularity = array[i]; o.push((b ? ', ' : '') + singularity); b = true; } } o.push('</div>'); } } if (data.errors || data.implieds || data.unused) { err = true; o.push('<div id=errors><i>Error:</i>'); if (data.errors) { for (i = 0; i < data.errors.length; i += 1) { c = data.errors[i]; if (c) { e = c.evidence || ''; o.push('<p>Problem' + (isFinite(c.line) ? ' at line ' + c.line + ' character ' + c.character : '') + ': ' + c.reason.entityify() + '</p><p class=evidence>' + (e && (e.length > 80 ? e.slice(0, 77) + '...' : e).entityify()) + '</p>'); } } } if (data.implieds) { s = []; for (i = 0; i < data.implieds.length; i += 1) { s[i] = '<code>' + data.implieds[i].name + '</code>&nbsp;<i>' + data.implieds[i].line + '</i>'; } o.push('<p><i>Implied global:</i> ' + s.join(', ') + '</p>'); } if (data.unused) { s = []; for (i = 0; i < data.unused.length; i += 1) { s[i] = '<code><u>' + data.unused[i].name + '</u></code>&nbsp;<i>' + data.unused[i].line + '</i> <code>' + data.unused[i]['function'] + '</code>'; } o.push('<p><i>Unused variable:</i> ' + s.join(', ') + '</p>'); } if (data.json) { o.push('<p>JSON: bad.</p>'); } o.push('</div>'); } if (!option) { o.push('<br><div id=functions>'); if (data.urls) { detail("URLs<br>", data.urls, '<br>'); } if (data.json && !err) { o.push('<p>JSON: good.</p>'); } else if (data.globals) { o.push('<div><i>Global</i> ' + data.globals.sort().join(', ') + '</div>'); } else { o.push('<div><i>No new global variables introduced.</i></div>'); } for (i = 0; i < data.functions.length; i += 1) { f = data.functions[i]; o.push('<br><div class=function><i>' + f.line + '-' + f.last + '</i> ' + (f.name || '') + '(' + (f.param ? f.param.join(', ') : '') + ')</div>'); detail('<big><b>Unused</b></big>', f.unused); detail('Closure', f.closure); detail('Variable', f['var']); detail('Exception', f.exception); detail('Outer', f.outer); detail('Global', f.global); detail('Label', f.label); } if (data.member) { a = Object.keys(data.member); if (a.length) { a = a.sort(); m = '<br><pre id=members>/*members '; l = 10; for (i = 0; i < a.length; i += 1) { k = a[i]; n = k.name(); if (l + n.length > 72) { o.push(m + '<br>'); m = ' '; l = 1; } l += n.length + 2; if (data.member[k] === 1) { n = '<i>' + n + '</i>'; } if (i < a.length - 1) { n += ', '; } m += n; } o.push(m + '<br>*/</pre>'); } o.push('</div>'); } } return o.join(''); }; itself.jshint = itself; return itself; }()); // Make JSHINT a Node module, if possible. if (typeof exports === 'object' && exports) exports.JSHINT = JSHINT; }); /* * Narcissus - JS implemented in JS. * * Parser. */ define('ace/narcissus/parser', ['require', 'exports', 'module' , 'ace/narcissus/lexer', 'ace/narcissus/definitions', 'ace/narcissus/options'], function(require, exports, module) { var lexer = require('./lexer'); var definitions = require('./definitions'); var options = require('./options'); var Tokenizer = lexer.Tokenizer; var Dict = definitions.Dict; var Stack = definitions.Stack; // Set constants in the local scope. eval(definitions.consts); function pushDestructuringVarDecls(n, s) { for (var i in n) { var sub = n[i]; if (sub.type === IDENTIFIER) { s.varDecls.push(sub); } else { pushDestructuringVarDecls(sub, s); } } } function Parser(tokenizer) { tokenizer.parser = this; this.t = tokenizer; this.x = null; this.unexpectedEOF = false; options.mozillaMode && (this.mozillaMode = true); options.parenFreeMode && (this.parenFreeMode = true); } function StaticContext(parentScript, parentBlock, inModule, inFunction, strictMode) { this.parentScript = parentScript; this.parentBlock = parentBlock || parentScript; this.inModule = inModule || false; this.inFunction = inFunction || false; this.inForLoopInit = false; this.topLevel = true; this.allLabels = new Stack(); this.currentLabels = new Stack(); this.labeledTargets = new Stack(); this.defaultLoopTarget = null; this.defaultTarget = null; this.strictMode = strictMode; } StaticContext.prototype = { // non-destructive update via prototype extension update: function(ext) { var desc = {}; for (var key in ext) { desc[key] = { value: ext[key], writable: true, enumerable: true, configurable: true } } return Object.create(this, desc); }, pushLabel: function(label) { return this.update({ currentLabels: this.currentLabels.push(label), allLabels: this.allLabels.push(label) }); }, pushTarget: function(target) { var isDefaultLoopTarget = target.isLoop; var isDefaultTarget = isDefaultLoopTarget || target.type === SWITCH; if (this.currentLabels.isEmpty()) { if (isDefaultLoopTarget) this.update({ defaultLoopTarget: target }); if (isDefaultTarget) this.update({ defaultTarget: target }); return this; } target.labels = new Dict(); this.currentLabels.forEach(function(label) { target.labels.set(label, true); }); return this.update({ currentLabels: new Stack(), labeledTargets: this.labeledTargets.push(target), defaultLoopTarget: isDefaultLoopTarget ? target : this.defaultLoopTarget, defaultTarget: isDefaultTarget ? target : this.defaultTarget }); }, nest: function() { return this.topLevel ? this.update({ topLevel: false }) : this; }, canImport: function() { return this.topLevel && !this.inFunction; }, canExport: function() { return this.inModule && this.topLevel && !this.inFunction; }, banWith: function() { return this.strictMode || this.inModule; }, modulesAllowed: function() { return this.topLevel && !this.inFunction; } }; var Pp = Parser.prototype; Pp.mozillaMode = false; Pp.parenFreeMode = false; Pp.withContext = function(x, f) { var x0 = this.x; this.x = x; var result = f.call(this); // NB: we don't bother with finally, since exceptions trash the parser this.x = x0; return result; }; Pp.newNode = function newNode(opts) { return new Node(this.t, opts); }; Pp.fail = function fail(msg) { throw this.t.newSyntaxError(msg); }; Pp.match = function match(tt, scanOperand, keywordIsName) { return this.t.match(tt, scanOperand, keywordIsName); }; Pp.mustMatch = function mustMatch(tt, keywordIsName) { return this.t.mustMatch(tt, keywordIsName); }; Pp.peek = function peek(scanOperand) { return this.t.peek(scanOperand); }; Pp.peekOnSameLine = function peekOnSameLine(scanOperand) { return this.t.peekOnSameLine(scanOperand); }; Pp.done = function done() { return this.t.done; }; Pp.Script = function Script(inModule, inFunction, expectEnd) { var node = this.newNode(scriptInit()); var x2 = new StaticContext(node, node, inModule, inFunction); this.withContext(x2, function() { this.Statements(node, true); }); if (expectEnd && !this.done()) this.fail("expected end of input"); return node; }; function Pragma(n) { if (n.type === SEMICOLON) { var e = n.expression; if (e.type === STRING && e.value === "use strict") { n.pragma = "strict"; return true; } } return false; } /* * Node :: (tokenizer, optional init object) -> node */ function Node(t, init) { var token = t.token; if (token) { // If init.type exists it will override token.type. this.type = token.type; this.value = token.value; this.lineno = token.lineno; // Start and end are file positions for error handling. this.start = token.start; this.end = token.end; } else { this.lineno = t.lineno; } this.filename = t.filename; this.children = []; for (var prop in init) this[prop] = init[prop]; } /* * SyntheticNode :: (optional init object) -> node */ function SyntheticNode(init) { this.children = []; for (var prop in init) this[prop] = init[prop]; this.synthetic = true; } var Np = Node.prototype = SyntheticNode.prototype = {}; Np.constructor = Node; var TO_SOURCE_SKIP = { type: true, value: true, lineno: true, start: true, end: true, tokenizer: true, assignOp: true }; function unevalableConst(code) { var token = definitions.tokens[code]; var constName = definitions.opTypeNames.hasOwnProperty(token) ? definitions.opTypeNames[token] : token in definitions.keywords ? token.toUpperCase() : token; return { toSource: function() { return constName } }; } Np.toSource = function toSource() { var mock = {}; var self = this; mock.type = unevalableConst(this.type); // avoid infinite recursion in case of back-links if (this.generatingSource) return mock.toSource(); this.generatingSource = true; if ("value" in this) mock.value = this.value; if ("lineno" in this) mock.lineno = this.lineno; if ("start" in this) mock.start = this.start; if ("end" in this) mock.end = this.end; if (this.assignOp) mock.assignOp = unevalableConst(this.assignOp); for (var key in this) { if (this.hasOwnProperty(key) && !(key in TO_SOURCE_SKIP)) mock[key] = this[key]; } try { return mock.toSource(); } finally { delete this.generatingSource; } }; // Always use push to add operands to an expression, to update start and end. Np.push = function (kid) { // kid can be null e.g. [1, , 2]. if (kid !== null) { if (kid.start < this.start) this.start = kid.start; if (this.end < kid.end) this.end = kid.end; } return this.children.push(kid); } Node.indentLevel = 0; function tokenString(tt) { var t = definitions.tokens[tt]; return /^\W/.test(t) ? definitions.opTypeNames[t] : t.toUpperCase(); } Np.toString = function () { var a = []; for (var i in this) { if (this.hasOwnProperty(i) && i !== 'type' && i !== 'target') a.push({id: i, value: this[i]}); } a.sort(function (a,b) { return (a.id < b.id) ? -1 : 1; }); var INDENTATION = " "; var n = ++Node.indentLevel; var s = "{\n" + INDENTATION.repeat(n) + "type: " + tokenString(this.type); for (i = 0; i < a.length; i++) s += ",\n" + INDENTATION.repeat(n) + a[i].id + ": " + a[i].value; n = --Node.indentLevel; s += "\n" + INDENTATION.repeat(n) + "}"; return s; } Np.synth = function(init) { var node = new SyntheticNode(init); node.filename = this.filename; node.lineno = this.lineno; node.start = this.start; node.end = this.end; return node; }; var LOOP_INIT = { isLoop: true }; function blockInit() { return { type: BLOCK, varDecls: [] }; } function scriptInit() { return { type: SCRIPT, funDecls: [], varDecls: [], modDefns: new Dict(), modAssns: new Dict(), modDecls: new Dict(), modLoads: new Dict(), impDecls: [], expDecls: [], exports: new Dict(), hasEmptyReturn: false, hasReturnWithValue: false, hasYield: false }; } definitions.defineGetter(Np, "length", function() { throw new Error("Node.prototype.length is gone; " + "use n.children.length instead"); }); definitions.defineProperty(String.prototype, "repeat", function(n) { var s = "", t = this + s; while (--n >= 0) s += t; return s; }, false, false, true); Pp.MaybeLeftParen = function MaybeLeftParen() { if (this.parenFreeMode) return this.match(LEFT_PAREN) ? LEFT_PAREN : END; return this.mustMatch(LEFT_PAREN).type; }; Pp.MaybeRightParen = function MaybeRightParen(p) { if (p === LEFT_PAREN) this.mustMatch(RIGHT_PAREN); } /* * Statements :: (node[, boolean]) -> void * * Parses a sequence of Statements. */ Pp.Statements = function Statements(n, topLevel) { var prologue = !!topLevel; try { while (!this.done() && this.peek(true) !== RIGHT_CURLY) { var n2 = this.Statement(); n.push(n2); if (prologue && Pragma(n2)) { this.x.strictMode = true; n.strict = true; } else { prologue = false; } } } catch (e) { try { if (this.done()) this.unexpectedEOF = true; } catch(e) {} throw e; } } Pp.Block = function Block() { this.mustMatch(LEFT_CURLY); var n = this.newNode(blockInit()); var x2 = this.x.update({ parentBlock: n }).pushTarget(n); this.withContext(x2, function() { this.Statements(n); }); this.mustMatch(RIGHT_CURLY); return n; } var DECLARED_FORM = 0, EXPRESSED_FORM = 1, STATEMENT_FORM = 2; function Export(node, isDefinition) { this.node = node; // the AST node declaring this individual export this.isDefinition = isDefinition; // is the node an 'export'-annotated definition? this.resolved = null; // resolved pointer to the target of this export } /* * registerExport :: (Dict, EXPORT node) -> void */ function registerExport(exports, decl) { function register(name, exp) { if (exports.has(name)) throw new SyntaxError("multiple exports of " + name); exports.set(name, exp); } switch (decl.type) { case MODULE: case FUNCTION: register(decl.name, new Export(decl, true)); break; case VAR: for (var i = 0; i < decl.children.length; i++) register(decl.children[i].name, new Export(decl.children[i], true)); break; case LET: case CONST: throw new Error("NYI: " + definitions.tokens[decl.type]); case EXPORT: for (var i = 0; i < decl.pathList.length; i++) { var path = decl.pathList[i]; switch (path.type) { case OBJECT_INIT: for (var j = 0; j < path.children.length; j++) { // init :: IDENTIFIER | PROPERTY_INIT var init = path.children[j]; if (init.type === IDENTIFIER) register(init.value, new Export(init, false)); else register(init.children[0].value, new Export(init.children[1], false)); } break; case DOT: register(path.children[1].value, new Export(path, false)); break; case IDENTIFIER: register(path.value, new Export(path, false)); break; default: throw new Error("unexpected export path: " + definitions.tokens[path.type]); } } break; default: throw new Error("unexpected export decl: " + definitions.tokens[exp.type]); } } /* * Module :: (node) -> Module * * Static semantic representation of a module. */ function Module(node) { var exports = node.body.exports; var modDefns = node.body.modDefns; var exportedModules = new Dict(); exports.forEach(function(name, exp) { var node = exp.node; if (node.type === MODULE) { exportedModules.set(name, node); } else if (!exp.isDefinition && node.type === IDENTIFIER && modDefns.has(node.value)) { var mod = modDefns.get(node.value); exportedModules.set(name, mod); } }); this.node = node; this.exports = exports; this.exportedModules = exportedModules; } /* * Statement :: () -> node * * Parses a Statement. */ Pp.Statement = function Statement() { var i, label, n, n2, p, c, ss, tt = this.t.get(true), tt2, x0, x2, x3; var comments = this.t.blockComments; // Cases for statements ending in a right curly return early, avoiding the // common semicolon insertion magic after this switch. switch (tt) { case IMPORT: if (!this.x.canImport()) this.fail("illegal context for import statement"); n = this.newNode(); n.pathList = this.ImportPathList(); this.x.parentScript.impDecls.push(n); break; case EXPORT: if (!this.x.canExport()) this.fail("export statement not in module top level"); switch (this.peek()) { case MODULE: case FUNCTION: case LET: case VAR: case CONST: n = this.Statement(); n.blockComments = comments; n.exported = true; this.x.parentScript.expDecls.push(n); registerExport(this.x.parentScript.exports, n); return n; } n = this.newNode(); n.pathList = this.ExportPathList(); this.x.parentScript.expDecls.push(n); registerExport(this.x.parentScript.exports, n); break; case FUNCTION: // DECLARED_FORM extends funDecls of x, STATEMENT_FORM doesn't. return this.FunctionDefinition(true, this.x.topLevel ? DECLARED_FORM : STATEMENT_FORM, comments); case LEFT_CURLY: n = this.newNode(blockInit()); x2 = this.x.update({ parentBlock: n }).pushTarget(n).nest(); this.withContext(x2, function() { this.Statements(n); }); this.mustMatch(RIGHT_CURLY); return n; case IF: n = this.newNode(); n.condition = this.HeadExpression(); x2 = this.x.pushTarget(n).nest(); this.withContext(x2, function() { n.thenPart = this.Statement(); n.elsePart = this.match(ELSE, true) ? this.Statement() : null; }); return n; case SWITCH: // This allows CASEs after a DEFAULT, which is in the standard. n = this.newNode({ cases: [], defaultIndex: -1 }); n.discriminant = this.HeadExpression(); x2 = this.x.pushTarget(n).nest(); this.withContext(x2, function() { this.mustMatch(LEFT_CURLY); while ((tt = this.t.get()) !== RIGHT_CURLY) { switch (tt) { case DEFAULT: if (n.defaultIndex >= 0) this.fail("More than one switch default"); // FALL THROUGH case CASE: n2 = this.newNode(); if (tt === DEFAULT) n.defaultIndex = n.cases.length; else n2.caseLabel = this.Expression(COLON); break; default: this.fail("Invalid switch case"); } this.mustMatch(COLON); n2.statements = this.newNode(blockInit()); while ((tt=this.peek(true)) !== CASE && tt !== DEFAULT && tt !== RIGHT_CURLY) n2.statements.push(this.Statement()); n.cases.push(n2); } }); return n; case FOR: n = this.newNode(LOOP_INIT); n.blockComments = comments; if (this.match(IDENTIFIER)) { if (this.t.token.value === "each") n.isEach = true; else this.t.unget(); } if (!this.parenFreeMode) this.mustMatch(LEFT_PAREN); x2 = this.x.pushTarget(n).nest(); x3 = this.x.update({ inForLoopInit: true }); n2 = null; if ((tt = this.peek(true)) !== SEMICOLON) { this.withContext(x3, function() { if (tt === VAR || tt === CONST) { this.t.get(); n2 = this.Variables(); } else if (tt === LET) { this.t.get(); if (this.peek() === LEFT_PAREN) { n2 = this.LetBlock(false); } else { // Let in for head, we need to add an implicit block // around the rest of the for. this.x.parentBlock = n; n.varDecls = []; n2 = this.Variables(); } } else { n2 = this.Expression(); } }); } if (n2 && this.match(IN)) { n.type = FOR_IN; this.withContext(x3, function() { n.object = this.Expression(); if (n2.type === VAR || n2.type === LET) { c = n2.children; // Destructuring turns one decl into multiples, so either // there must be only one destructuring or only one // decl. if (c.length !== 1 && n2.destructurings.length !== 1) { // FIXME: this.fail ? throw new SyntaxError("Invalid for..in left-hand side", this.filename, n2.lineno); } if (n2.destructurings.length > 0) { n.iterator = n2.destructurings[0]; } else { n.iterator = c[0]; } n.varDecl = n2; } else { if (n2.type === ARRAY_INIT || n2.type === OBJECT_INIT) { n2.destructuredNames = this.checkDestructuring(n2); } n.iterator = n2; } }); } else { x3.inForLoopInit = false; n.setup = n2; this.mustMatch(SEMICOLON); if (n.isEach) this.fail("Invalid for each..in loop"); this.withContext(x3, function() { n.condition = (this.peek(true) === SEMICOLON) ? null : this.Expression(); this.mustMatch(SEMICOLON); tt2 = this.peek(true); n.update = (this.parenFreeMode ? tt2 === LEFT_CURLY || definitions.isStatementStartCode[tt2] : tt2 === RIGHT_PAREN) ? null : this.Expression(); }); } if (!this.parenFreeMode) this.mustMatch(RIGHT_PAREN); this.withContext(x2, function() { n.body = this.Statement(); }); return n; case WHILE: n = this.newNode({ isLoop: true }); n.blockComments = comments; n.condition = this.HeadExpression(); x2 = this.x.pushTarget(n).nest(); this.withContext(x2, function() { n.body = this.Statement(); }); return n; case DO: n = this.newNode({ isLoop: true }); n.blockComments = comments; x2 = this.x.pushTarget(n).next(); this.withContext(x2, function() { n.body = this.Statement(); }); this.mustMatch(WHILE); n.condition = this.HeadExpression(); // <script language="JavaScript"> (without version hints) may need // automatic semicolon insertion without a newline after do-while. // See http://bugzilla.mozilla.org/show_bug.cgi?id=238945. this.match(SEMICOLON); return n; case BREAK: case CONTINUE: n = this.newNode(); n.blockComments = comments; // handle the |foo: break foo;| corner case x2 = this.x.pushTarget(n); if (this.peekOnSameLine() === IDENTIFIER) { this.t.get(); n.label = this.t.token.value; } if (n.label) { n.target = x2.labeledTargets.find(function(target) { return target.labels.has(n.label) }); } else if (tt === CONTINUE) { n.target = x2.defaultLoopTarget; } else { n.target = x2.defaultTarget; } if (!n.target) this.fail("Invalid " + ((tt === BREAK) ? "break" : "continue")); if (!n.target.isLoop && tt === CONTINUE) this.fail("Invalid continue"); break; case TRY: n = this.newNode({ catchClauses: [] }); n.blockComments = comments; n.tryBlock = this.Block(); while (this.match(CATCH)) { n2 = this.newNode(); p = this.MaybeLeftParen(); switch (this.t.get()) { case LEFT_BRACKET: case LEFT_CURLY: // Destructured catch identifiers. this.t.unget(); n2.varName = this.DestructuringExpression(true); break; case IDENTIFIER: n2.varName = this.t.token.value; break; default: this.fail("missing identifier in catch"); break; } if (this.match(IF)) { if (!this.mozillaMode) this.fail("Illegal catch guard"); if (n.catchClauses.length && !n.catchClauses.top().guard) this.fail("Guarded catch after unguarded"); n2.guard = this.Expression(); } this.MaybeRightParen(p); n2.block = this.Block(); n.catchClauses.push(n2); } if (this.match(FINALLY)) n.finallyBlock = this.Block(); if (!n.catchClauses.length && !n.finallyBlock) this.fail("Invalid try statement"); return n; case CATCH: case FINALLY: this.fail(definitions.tokens[tt] + " without preceding try"); case THROW: n = this.newNode(); n.exception = this.Expression(); break; case RETURN: n = this.ReturnOrYield(); break; case WITH: if (this.x.banWith()) this.fail("with statements not allowed in strict code or modules"); n = this.newNode(); n.blockComments = comments; n.object = this.HeadExpression(); x2 = this.x.pushTarget(n).next(); this.withContext(x2, function() { n.body = this.Statement(); }); return n; case VAR: case CONST: n = this.Variables(); break; case LET: if (this.peek() === LEFT_PAREN) { n = this.LetBlock(true); return n; } n = this.Variables(); break; case DEBUGGER: n = this.newNode(); break; case NEWLINE: case SEMICOLON: n = this.newNode({ type: SEMICOLON }); n.blockComments = comments; n.expression = null; return n; case IDENTIFIER: case USE: case MODULE: switch (this.t.token.value) { case "use": if (!isPragmaToken(this.peekOnSameLine())) { this.t.unget(); break; } return this.newNode({ type: USE, params: this.Pragmas() }); case "module": if (!this.x.modulesAllowed()) this.fail("module declaration not at top level"); this.x.parentScript.hasModules = true; tt = this.peekOnSameLine(); if (tt !== IDENTIFIER && tt !== LEFT_CURLY) { this.t.unget(); break; } n = this.newNode({ type: MODULE }); n.blockComments = comments; this.mustMatch(IDENTIFIER); label = this.t.token.value; if (this.match(LEFT_CURLY)) { n.name = label; n.body = this.Script(true, false); n.module = new Module(n); this.mustMatch(RIGHT_CURLY); this.x.parentScript.modDefns.set(n.name, n); return n; } this.t.unget(); this.ModuleVariables(n); return n; default: tt = this.peek(); // Labeled statement. if (tt === COLON) { label = this.t.token.value; if (this.x.allLabels.has(label)) this.fail("Duplicate label: " + label); this.t.get(); n = this.newNode({ type: LABEL, label: label }); n.blockComments = comments; x2 = this.x.pushLabel(label).nest(); this.withContext(x2, function() { n.statement = this.Statement(); }); n.target = (n.statement.type === LABEL) ? n.statement.target : n.statement; return n; } // FALL THROUGH } // FALL THROUGH default: // Expression statement. // We unget the current token to parse the expression as a whole. n = this.newNode({ type: SEMICOLON }); this.t.unget(); n.blockComments = comments; n.expression = this.Expression(); n.end = n.expression.end; break; } n.blockComments = comments; this.MagicalSemicolon(); return n; } /* * isPragmaToken :: (number) -> boolean */ function isPragmaToken(tt) { switch (tt) { case IDENTIFIER: case STRING: case NUMBER: case NULL: case TRUE: case FALSE: return true; } return false; } /* * Pragmas :: () -> Array[Array[token]] */ Pp.Pragmas = function Pragmas() { var pragmas = []; do { pragmas.push(this.Pragma()); } while (this.match(COMMA)); this.MagicalSemicolon(); return pragmas; } /* * Pragmas :: () -> Array[token] */ Pp.Pragma = function Pragma() { var items = []; var tt; do { tt = this.t.get(true); items.push(this.t.token); } while (isPragmaToken(this.peek())); return items; } /* * MagicalSemicolon :: () -> void */ Pp.MagicalSemicolon = function MagicalSemicolon() { var tt; if (this.t.lineno === this.t.token.lineno) { tt = this.peekOnSameLine(); if (tt !== END && tt !== NEWLINE && tt !== SEMICOLON && tt !== RIGHT_CURLY) this.fail("missing ; before statement"); } this.match(SEMICOLON); } /* * ReturnOrYield :: () -> (RETURN | YIELD) node */ Pp.ReturnOrYield = function ReturnOrYield() { var n, b, tt = this.t.token.type, tt2; var parentScript = this.x.parentScript; if (tt === RETURN) { if (!this.x.inFunction) this.fail("Return not in function"); } else /* if (tt === YIELD) */ { if (!this.x.inFunction) this.fail("Yield not in function"); parentScript.hasYield = true; } n = this.newNode({ value: undefined }); tt2 = (tt === RETURN) ? this.peekOnSameLine(true) : this.peek(true); if (tt2 !== END && tt2 !== NEWLINE && tt2 !== SEMICOLON && tt2 !== RIGHT_CURLY && (tt !== YIELD || (tt2 !== tt && tt2 !== RIGHT_BRACKET && tt2 !== RIGHT_PAREN && tt2 !== COLON && tt2 !== COMMA))) { if (tt === RETURN) { n.value = this.Expression(); parentScript.hasReturnWithValue = true; } else { n.value = this.AssignExpression(); } } else if (tt === RETURN) { parentScript.hasEmptyReturn = true; } return n; } /* * ModuleExpression :: () -> (STRING | IDENTIFIER | DOT) node */ Pp.ModuleExpression = function ModuleExpression() { return this.match(STRING) ? this.newNode() : this.QualifiedPath(); } /* * ImportPathList :: () -> Array[DOT node] */ Pp.ImportPathList = function ImportPathList() { var a = []; do { a.push(this.ImportPath()); } while (this.match(COMMA)); return a; } /* * ImportPath :: () -> DOT node */ Pp.ImportPath = function ImportPath() { var n = this.QualifiedPath(); if (!this.match(DOT)) { if (n.type === IDENTIFIER) this.fail("cannot import local variable"); return n; } var n2 = this.newNode(); n2.push(n); n2.push(this.ImportSpecifierSet()); return n2; } /* * ExplicitSpecifierSet :: (() -> node) -> OBJECT_INIT node */ Pp.ExplicitSpecifierSet = function ExplicitSpecifierSet(SpecifierRHS) { var n, n2, id, tt; n = this.newNode({ type: OBJECT_INIT }); this.mustMatch(LEFT_CURLY); if (!this.match(RIGHT_CURLY)) { do { id = this.Identifier(); if (this.match(COLON)) { n2 = this.newNode({ type: PROPERTY_INIT }); n2.push(id); n2.push(SpecifierRHS()); n.push(n2); } else { n.push(id); } } while (!this.match(RIGHT_CURLY) && this.mustMatch(COMMA)); } return n; } /* * ImportSpecifierSet :: () -> (IDENTIFIER | OBJECT_INIT) node */ Pp.ImportSpecifierSet = function ImportSpecifierSet() { var self = this; return this.match(MUL) ? this.newNode({ type: IDENTIFIER, name: "*" }) : ExplicitSpecifierSet(function() { return self.Identifier() }); } /* * Identifier :: () -> IDENTIFIER node */ Pp.Identifier = function Identifier() { this.mustMatch(IDENTIFIER); return this.newNode({ type: IDENTIFIER }); } /* * IdentifierName :: () -> IDENTIFIER node */ Pp.IdentifierName = function IdentifierName() { this.mustMatch(IDENTIFIER, true); return this.newNode({ type: IDENTIFIER }); } /* * QualifiedPath :: () -> (IDENTIFIER | DOT) node */ Pp.QualifiedPath = function QualifiedPath() { var n, n2; n = this.Identifier(); while (this.match(DOT)) { if (this.peek() !== IDENTIFIER) { // Unget the '.' token, which isn't part of the QualifiedPath. this.t.unget(); break; } n2 = this.newNode(); n2.push(n); n2.push(this.Identifier()); n = n2; } return n; } /* * ExportPath :: () -> (IDENTIFIER | DOT | OBJECT_INIT) node */ Pp.ExportPath = function ExportPath() { var self = this; if (this.peek() === LEFT_CURLY) return this.ExplicitSpecifierSet(function() { return self.QualifiedPath() }); return this.QualifiedPath(); } /* * ExportPathList :: () -> Array[(IDENTIFIER | DOT | OBJECT_INIT) node] */ Pp.ExportPathList = function ExportPathList() { var a = []; do { a.push(this.ExportPath()); } while (this.match(COMMA)); return a; } /* * FunctionDefinition :: (boolean, * DECLARED_FORM or EXPRESSED_FORM or STATEMENT_FORM, * [string] or null or undefined) * -> node */ Pp.FunctionDefinition = function FunctionDefinition(requireName, functionForm, comments) { var tt; var f = this.newNode({ params: [], paramComments: [] }); if (typeof comments === "undefined") comments = null; f.blockComments = comments; if (f.type !== FUNCTION) f.type = (f.value === "get") ? GETTER : SETTER; if (this.match(MUL)) f.isExplicitGenerator = true; if (this.match(IDENTIFIER, false, true)) f.name = this.t.token.value; else if (requireName) this.fail("missing function identifier"); var inModule = this.x.inModule; x2 = new StaticContext(null, null, inModule, true, this.x.strictMode); this.withContext(x2, function() { this.mustMatch(LEFT_PAREN); if (!this.match(RIGHT_PAREN)) { do { tt = this.t.get(); f.paramComments.push(this.t.lastBlockComment()); switch (tt) { case LEFT_BRACKET: case LEFT_CURLY: // Destructured formal parameters. this.t.unget(); f.params.push(this.DestructuringExpression()); break; case IDENTIFIER: f.params.push(this.t.token.value); break; default: this.fail("missing formal parameter"); } } while (this.match(COMMA)); this.mustMatch(RIGHT_PAREN); } // Do we have an expression closure or a normal body? tt = this.t.get(true); if (tt !== LEFT_CURLY) this.t.unget(); if (tt !== LEFT_CURLY) { f.body = this.AssignExpression(); } else { f.body = this.Script(inModule, true); } }); if (tt === LEFT_CURLY) this.mustMatch(RIGHT_CURLY); f.end = this.t.token.end; f.functionForm = functionForm; if (functionForm === DECLARED_FORM) this.x.parentScript.funDecls.push(f); if (this.x.inModule && !f.isExplicitGenerator && f.body.hasYield) this.fail("yield in non-generator function"); if (f.isExplicitGenerator || f.body.hasYield) f.body = this.newNode({ type: GENERATOR, body: f.body }); return f; } /* * ModuleVariables :: (MODULE node) -> void * * Parses a comma-separated list of module declarations (and maybe * initializations). */ Pp.ModuleVariables = function ModuleVariables(n) { var n1, n2; do { n1 = this.Identifier(); if (this.match(ASSIGN)) { n2 = this.ModuleExpression(); n1.initializer = n2; if (n2.type === STRING) this.x.parentScript.modLoads.set(n1.value, n2.value); else this.x.parentScript.modAssns.set(n1.value, n1); } n.push(n1); } while (this.match(COMMA)); } /* * Variables :: () -> node * * Parses a comma-separated list of var declarations (and maybe * initializations). */ Pp.Variables = function Variables(letBlock) { var n, n2, ss, i, s, tt; tt = this.t.token.type; switch (tt) { case VAR: case CONST: s = this.x.parentScript; break; case LET: s = this.x.parentBlock; break; case LEFT_PAREN: tt = LET; s = letBlock; break; } n = this.newNode({ type: tt, destructurings: [] }); do { tt = this.t.get(); if (tt === LEFT_BRACKET || tt === LEFT_CURLY) { // Need to unget to parse the full destructured expression. this.t.unget(); var dexp = this.DestructuringExpression(true); n2 = this.newNode({ type: IDENTIFIER, name: dexp, readOnly: n.type === CONST }); n.push(n2); pushDestructuringVarDecls(n2.name.destructuredNames, s); n.destructurings.push({ exp: dexp, decl: n2 }); if (this.x.inForLoopInit && this.peek() === IN) { continue; } this.mustMatch(ASSIGN); if (this.t.token.assignOp) this.fail("Invalid variable initialization"); n2.blockComment = this.t.lastBlockComment(); n2.initializer = this.AssignExpression(); continue; } if (tt !== IDENTIFIER) this.fail("missing variable name"); n2 = this.newNode({ type: IDENTIFIER, name: this.t.token.value, readOnly: n.type === CONST }); n.push(n2); s.varDecls.push(n2); if (this.match(ASSIGN)) { var comment = this.t.lastBlockComment(); if (this.t.token.assignOp) this.fail("Invalid variable initialization"); n2.initializer = this.AssignExpression(); } else { var comment = this.t.lastBlockComment(); } n2.blockComment = comment; } while (this.match(COMMA)); return n; } /* * LetBlock :: (boolean) -> node * * Does not handle let inside of for loop init. */ Pp.LetBlock = function LetBlock(isStatement) { var n, n2; // t.token.type must be LET n = this.newNode({ type: LET_BLOCK, varDecls: [] }); this.mustMatch(LEFT_PAREN); n.variables = this.Variables(n); this.mustMatch(RIGHT_PAREN); if (isStatement && this.peek() !== LEFT_CURLY) { /* * If this is really an expression in let statement guise, then we * need to wrap the LET_BLOCK node in a SEMICOLON node so that we pop * the return value of the expression. */ n2 = this.newNode({ type: SEMICOLON, expression: n }); isStatement = false; } if (isStatement) n.block = this.Block(); else n.expression = this.AssignExpression(); return n; } Pp.checkDestructuring = function checkDestructuring(n, simpleNamesOnly) { if (n.type === ARRAY_COMP) this.fail("Invalid array comprehension left-hand side"); if (n.type !== ARRAY_INIT && n.type !== OBJECT_INIT) return; var lhss = {}; var nn, n2, idx, sub, cc, c = n.children; for (var i = 0, j = c.length; i < j; i++) { if (!(nn = c[i])) continue; if (nn.type === PROPERTY_INIT) { cc = nn.children; sub = cc[1]; idx = cc[0].value; } else if (n.type === OBJECT_INIT) { // Do we have destructuring shorthand {foo, bar}? sub = nn; idx = nn.value; } else { sub = nn; idx = i; } if (sub.type === ARRAY_INIT || sub.type === OBJECT_INIT) { lhss[idx] = this.checkDestructuring(sub, simpleNamesOnly); } else { if (simpleNamesOnly && sub.type !== IDENTIFIER) { // In declarations, lhs must be simple names this.fail("missing name in pattern"); } lhss[idx] = sub; } } return lhss; } Pp.DestructuringExpression = function DestructuringExpression(simpleNamesOnly) { var n = this.PrimaryExpression(); // Keep the list of lefthand sides for varDecls n.destructuredNames = this.checkDestructuring(n, simpleNamesOnly); return n; } Pp.GeneratorExpression = function GeneratorExpression(e) { return this.newNode({ type: GENERATOR, expression: e, tail: this.ComprehensionTail() }); } Pp.ComprehensionTail = function ComprehensionTail() { var body, n, n2, n3, p; // t.token.type must be FOR body = this.newNode({ type: COMP_TAIL }); do { // Comprehension tails are always for..in loops. n = this.newNode({ type: FOR_IN, isLoop: true }); if (this.match(IDENTIFIER)) { // But sometimes they're for each..in. if (this.mozillaMode && this.t.token.value === "each") n.isEach = true; else this.t.unget(); } p = this.MaybeLeftParen(); switch(this.t.get()) { case LEFT_BRACKET: case LEFT_CURLY: this.t.unget(); // Destructured left side of for in comprehension tails. n.iterator = this.DestructuringExpression(); break; case IDENTIFIER: n.iterator = n3 = this.newNode({ type: IDENTIFIER }); n3.name = n3.value; n.varDecl = n2 = this.newNode({ type: VAR }); n2.push(n3); this.x.parentScript.varDecls.push(n3); // Don't add to varDecls since the semantics of comprehensions is // such that the variables are in their own function when // desugared. break; default: this.fail("missing identifier"); } this.mustMatch(IN); n.object = this.Expression(); this.MaybeRightParen(p); body.push(n); } while (this.match(FOR)); // Optional guard. if (this.match(IF)) body.guard = this.HeadExpression(); return body; } Pp.HeadExpression = function HeadExpression() { var p = this.MaybeLeftParen(); var n = this.ParenExpression(); this.MaybeRightParen(p); if (p === END && !n.parenthesized) { var tt = this.peek(); if (tt !== LEFT_CURLY && !definitions.isStatementStartCode[tt]) this.fail("Unparenthesized head followed by unbraced body"); } return n; } Pp.ParenExpression = function ParenExpression() { // Always accept the 'in' operator in a parenthesized expression, // where it's unambiguous, even if we might be parsing the init of a // for statement. var x2 = this.x.update({ inForLoopInit: this.x.inForLoopInit && (this.t.token.type === LEFT_PAREN) }); var n = this.withContext(x2, function() { return this.Expression(); }); if (this.match(FOR)) { if (n.type === YIELD && !n.parenthesized) this.fail("Yield expression must be parenthesized"); if (n.type === COMMA && !n.parenthesized) this.fail("Generator expression must be parenthesized"); n = this.GeneratorExpression(n); } return n; } /* * Expression :: () -> node * * Top-down expression parser matched against SpiderMonkey. */ Pp.Expression = function Expression() { var n, n2; n = this.AssignExpression(); if (this.match(COMMA)) { n2 = this.newNode({ type: COMMA }); n2.push(n); n = n2; do { n2 = n.children[n.children.length-1]; if (n2.type === YIELD && !n2.parenthesized) this.fail("Yield expression must be parenthesized"); n.push(this.AssignExpression()); } while (this.match(COMMA)); } return n; } Pp.AssignExpression = function AssignExpression() { var n, lhs; // Have to treat yield like an operand because it could be the leftmost // operand of the expression. if (this.match(YIELD, true)) return this.ReturnOrYield(); n = this.newNode({ type: ASSIGN }); lhs = this.ConditionalExpression(); if (!this.match(ASSIGN)) { return lhs; } n.blockComment = this.t.lastBlockComment(); switch (lhs.type) { case OBJECT_INIT: case ARRAY_INIT: lhs.destructuredNames = this.checkDestructuring(lhs); // FALL THROUGH case IDENTIFIER: case DOT: case INDEX: case CALL: break; default: this.fail("Bad left-hand side of assignment"); break; } n.assignOp = lhs.assignOp = this.t.token.assignOp; n.push(lhs); n.push(this.AssignExpression()); return n; } Pp.ConditionalExpression = function ConditionalExpression() { var n, n2; n = this.OrExpression(); if (this.match(HOOK)) { n2 = n; n = this.newNode({ type: HOOK }); n.push(n2); var x2 = this.x.update({ inForLoopInit: false }); this.withContext(x2, function() { n.push(this.AssignExpression()); }); if (!this.match(COLON)) this.fail("missing : after ?"); n.push(this.AssignExpression()); } return n; } Pp.OrExpression = function OrExpression() { var n, n2; n = this.AndExpression(); while (this.match(OR)) { n2 = this.newNode(); n2.push(n); n2.push(this.AndExpression()); n = n2; } return n; } Pp.AndExpression = function AndExpression() { var n, n2; n = this.BitwiseOrExpression(); while (this.match(AND)) { n2 = this.newNode(); n2.push(n); n2.push(this.BitwiseOrExpression()); n = n2; } return n; } Pp.BitwiseOrExpression = function BitwiseOrExpression() { var n, n2; n = this.BitwiseXorExpression(); while (this.match(BITWISE_OR)) { n2 = this.newNode(); n2.push(n); n2.push(this.BitwiseXorExpression()); n = n2; } return n; } Pp.BitwiseXorExpression = function BitwiseXorExpression() { var n, n2; n = this.BitwiseAndExpression(); while (this.match(BITWISE_XOR)) { n2 = this.newNode(); n2.push(n); n2.push(this.BitwiseAndExpression()); n = n2; } return n; } Pp.BitwiseAndExpression = function BitwiseAndExpression() { var n, n2; n = this.EqualityExpression(); while (this.match(BITWISE_AND)) { n2 = this.newNode(); n2.push(n); n2.push(this.EqualityExpression()); n = n2; } return n; } Pp.EqualityExpression = function EqualityExpression() { var n, n2; n = this.RelationalExpression(); while (this.match(EQ) || this.match(NE) || this.match(STRICT_EQ) || this.match(STRICT_NE)) { n2 = this.newNode(); n2.push(n); n2.push(this.RelationalExpression()); n = n2; } return n; } Pp.RelationalExpression = function RelationalExpression() { var n, n2; var x2 = this.x.update({ inForLoopInit: false }); this.withContext(x2, function() { n = this.ShiftExpression(); while ((this.match(LT) || this.match(LE) || this.match(GE) || this.match(GT) || (!this.x.inForLoopInit && this.match(IN)) || this.match(INSTANCEOF))) { n2 = this.newNode(); n2.push(n); n2.push(this.ShiftExpression()); n = n2; } }); return n; } Pp.ShiftExpression = function ShiftExpression() { var n, n2; n = this.AddExpression(); while (this.match(LSH) || this.match(RSH) || this.match(URSH)) { n2 = this.newNode(); n2.push(n); n2.push(this.AddExpression()); n = n2; } return n; } Pp.AddExpression = function AddExpression() { var n, n2; n = this.MultiplyExpression(); while (this.match(PLUS) || this.match(MINUS)) { n2 = this.newNode(); n2.push(n); n2.push(this.MultiplyExpression()); n = n2; } return n; } Pp.MultiplyExpression = function MultiplyExpression() { var n, n2; n = this.UnaryExpression(); while (this.match(MUL) || this.match(DIV) || this.match(MOD)) { n2 = this.newNode(); n2.push(n); n2.push(this.UnaryExpression()); n = n2; } return n; } Pp.UnaryExpression = function UnaryExpression() { var n, n2, tt; switch (tt = this.t.get(true)) { case DELETE: case VOID: case TYPEOF: case NOT: case BITWISE_NOT: case PLUS: case MINUS: if (tt === PLUS) n = this.newNode({ type: UNARY_PLUS }); else if (tt === MINUS) n = this.newNode({ type: UNARY_MINUS }); else n = this.newNode(); n.push(this.UnaryExpression()); break; case INCREMENT: case DECREMENT: // Prefix increment/decrement. n = this.newNode(); n.push(this.MemberExpression(true)); break; default: this.t.unget(); n = this.MemberExpression(true); // Don't look across a newline boundary for a postfix {in,de}crement. if (this.t.tokens[(this.t.tokenIndex + this.t.lookahead - 1) & 3].lineno === this.t.lineno) { if (this.match(INCREMENT) || this.match(DECREMENT)) { n2 = this.newNode({ postfix: true }); n2.push(n); n = n2; } } break; } return n; } Pp.MemberExpression = function MemberExpression(allowCallSyntax) { var n, n2, name, tt; if (this.match(NEW)) { n = this.newNode(); n.push(this.MemberExpression(false)); if (this.match(LEFT_PAREN)) { n.type = NEW_WITH_ARGS; n.push(this.ArgumentList()); } } else { n = this.PrimaryExpression(); } while ((tt = this.t.get()) !== END) { switch (tt) { case DOT: n2 = this.newNode(); n2.push(n); n2.push(this.IdentifierName()); break; case LEFT_BRACKET: n2 = this.newNode({ type: INDEX }); n2.push(n); n2.push(this.Expression()); this.mustMatch(RIGHT_BRACKET); break; case LEFT_PAREN: if (allowCallSyntax) { n2 = this.newNode({ type: CALL }); n2.push(n); n2.push(this.ArgumentList()); break; } // FALL THROUGH default: this.t.unget(); return n; } n = n2; } return n; } Pp.ArgumentList = function ArgumentList() { var n, n2; n = this.newNode({ type: LIST }); if (this.match(RIGHT_PAREN, true)) return n; do { n2 = this.AssignExpression(); if (n2.type === YIELD && !n2.parenthesized && this.peek() === COMMA) this.fail("Yield expression must be parenthesized"); if (this.match(FOR)) { n2 = this.GeneratorExpression(n2); if (n.children.length > 1 || this.peek(true) === COMMA) this.fail("Generator expression must be parenthesized"); } n.push(n2); } while (this.match(COMMA)); this.mustMatch(RIGHT_PAREN); return n; } Pp.PrimaryExpression = function PrimaryExpression() { var n, n2, tt = this.t.get(true); switch (tt) { case FUNCTION: n = this.FunctionDefinition(false, EXPRESSED_FORM); break; case LEFT_BRACKET: n = this.newNode({ type: ARRAY_INIT }); while ((tt = this.peek(true)) !== RIGHT_BRACKET) { if (tt === COMMA) { this.t.get(); n.push(null); continue; } n.push(this.AssignExpression()); if (tt !== COMMA && !this.match(COMMA)) break; } // If we matched exactly one element and got a FOR, we have an // array comprehension. if (n.children.length === 1 && this.match(FOR)) { n2 = this.newNode({ type: ARRAY_COMP, expression: n.children[0], tail: this.ComprehensionTail() }); n = n2; } this.mustMatch(RIGHT_BRACKET); break; case LEFT_CURLY: var id, fd; n = this.newNode({ type: OBJECT_INIT }); object_init: if (!this.match(RIGHT_CURLY)) { do { tt = this.t.get(); if ((this.t.token.value === "get" || this.t.token.value === "set") && this.peek() === IDENTIFIER) { n.push(this.FunctionDefinition(true, EXPRESSED_FORM)); } else { var comments = this.t.blockComments; switch (tt) { case IDENTIFIER: case NUMBER: case STRING: id = this.newNode({ type: IDENTIFIER }); break; case RIGHT_CURLY: break object_init; default: if (this.t.token.value in definitions.keywords) { id = this.newNode({ type: IDENTIFIER }); break; } this.fail("Invalid property name"); } if (this.match(COLON)) { n2 = this.newNode({ type: PROPERTY_INIT }); n2.push(id); n2.push(this.AssignExpression()); n2.blockComments = comments; n.push(n2); } else { // Support, e.g., |var {x, y} = o| as destructuring shorthand // for |var {x: x, y: y} = o|, per proposed JS2/ES4 for JS1.8. if (this.peek() !== COMMA && this.peek() !== RIGHT_CURLY) this.fail("missing : after property"); n.push(id); } } } while (this.match(COMMA)); this.mustMatch(RIGHT_CURLY); } break; case LEFT_PAREN: n = this.ParenExpression(); this.mustMatch(RIGHT_PAREN); n.parenthesized = true; break; case LET: n = this.LetBlock(false); break; case NULL: case THIS: case TRUE: case FALSE: case IDENTIFIER: case NUMBER: case STRING: case REGEXP: n = this.newNode(); break; default: this.fail("missing operand; found " + definitions.tokens[tt]); break; } return n; } /* * parse :: (source, filename, line number) -> node */ function parse(s, f, l) { var t = new Tokenizer(s, f, l, options.allowHTMLComments); var p = new Parser(t); return p.Script(false, false, true); } /* * parseFunction :: (source, boolean, * DECLARED_FORM or EXPRESSED_FORM or STATEMENT_FORM, * filename, line number) * -> node */ function parseFunction(s, requireName, form, f, l) { var t = new Tokenizer(s, f, l); var p = new Parser(t); p.x = new StaticContext(null, null, false, false, false); return p.FunctionDefinition(requireName, form); } /* * parseStdin :: (source, {line number}, string, (string) -> boolean) -> program node */ function parseStdin(s, ln, prefix, isCommand) { // the special .begin command is only recognized at the beginning if (s.match(/^[\s]*\.begin[\s]*$/)) { ++ln.value; return parseMultiline(ln, prefix); } // commands at the beginning are treated as the entire input if (isCommand(s.trim())) s = ""; for (;;) { try { var t = new Tokenizer(s, "stdin", ln.value, false); var p = new Parser(t); var n = p.Script(false, false); ln.value = t.lineno; return n; } catch (e) { if (!p.unexpectedEOF) throw e; // commands in the middle are not treated as part of the input var more; do { if (prefix) putstr(prefix); more = readline(); if (!more) throw e; } while (isCommand(more.trim())); s += "\n" + more; } } } /* * parseMultiline :: ({line number}, string | null) -> program node */ function parseMultiline(ln, prefix) { var s = ""; for (;;) { if (prefix) putstr(prefix); var more = readline(); if (more === null) return null; // the only command recognized in multiline mode is .end if (more.match(/^[\s]*\.end[\s]*$/)) break; s += "\n" + more; } var t = new Tokenizer(s, "stdin", ln.value, false); var p = new Parser(t); var n = p.Script(false, false); ln.value = t.lineno; return n; } exports.parse = parse; exports.parseStdin = parseStdin; exports.parseFunction = parseFunction; exports.Node = Node; exports.DECLARED_FORM = DECLARED_FORM; exports.EXPRESSED_FORM = EXPRESSED_FORM; exports.STATEMENT_FORM = STATEMENT_FORM; exports.Tokenizer = Tokenizer; exports.Parser = Parser; exports.Module = Module; exports.Export = Export; }); /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Narcissus JavaScript engine. * * The Initial Developer of the Original Code is * Brendan Eich <brendan@mozilla.org>. * Portions created by the Initial Developer are Copyright (C) 2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Tom Austin <taustin@ucsc.edu> * Brendan Eich <brendan@mozilla.org> * Shu-Yu Guo <shu@rfrn.org> * Stephan Herhut <stephan.a.herhut@intel.com> * Dave Herman <dherman@mozilla.com> * Dimitris Vardoulakis <dimvar@ccs.neu.edu> * Patrick Walton <pcwalton@mozilla.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * Narcissus - JS implemented in JS. * * Lexical scanner. */ define('ace/narcissus/lexer', ['require', 'exports', 'module' , 'ace/narcissus/definitions'], function(require, exports, module) { var definitions = require('./definitions'); // Set constants in the local scope. eval(definitions.consts); // Build up a trie of operator tokens. var opTokens = {}; for (var op in definitions.opTypeNames) { if (op === '\n' || op === '.') continue; var node = opTokens; for (var i = 0; i < op.length; i++) { var ch = op[i]; if (!(ch in node)) node[ch] = {}; node = node[ch]; node.op = op; } } /* * Since JavaScript provides no convenient way to determine if a * character is in a particular Unicode category, we use * metacircularity to accomplish this (oh yeaaaah!) */ function isValidIdentifierChar(ch, first) { // check directly for ASCII if (ch <= "\u007F") { if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '$' || ch === '_' || (!first && (ch >= '0' && ch <= '9'))) { return true; } return false; } // create an object to test this in var x = {}; x["x"+ch] = true; x[ch] = true; // then use eval to determine if it's a valid character var valid = false; try { valid = (Function("x", "return (x." + (first?"":"x") + ch + ");")(x) === true); } catch (ex) {} return valid; } function isIdentifier(str) { if (typeof str !== "string") return false; if (str.length === 0) return false; if (!isValidIdentifierChar(str[0], true)) return false; for (var i = 1; i < str.length; i++) { if (!isValidIdentifierChar(str[i], false)) return false; } return true; } /* * Tokenizer :: (source, filename, line number, boolean) -> Tokenizer */ function Tokenizer(s, f, l, allowHTMLComments) { this.cursor = 0; this.source = String(s); this.tokens = []; this.tokenIndex = 0; this.lookahead = 0; this.scanNewlines = false; this.filename = f || ""; this.lineno = l || 1; this.allowHTMLComments = allowHTMLComments; this.blockComments = null; } Tokenizer.prototype = { get done() { // We need to set scanOperand to true here because the first thing // might be a regexp. return this.peek(true) === END; }, get token() { return this.tokens[this.tokenIndex]; }, match: function (tt, scanOperand, keywordIsName) { return this.get(scanOperand, keywordIsName) === tt || this.unget(); }, mustMatch: function (tt, keywordIsName) { if (!this.match(tt, false, keywordIsName)) { throw this.newSyntaxError("Missing " + definitions.tokens[tt].toLowerCase()); } return this.token; }, peek: function (scanOperand) { var tt, next; if (this.lookahead) { next = this.tokens[(this.tokenIndex + this.lookahead) & 3]; tt = (this.scanNewlines && next.lineno !== this.lineno) ? NEWLINE : next.type; } else { tt = this.get(scanOperand); this.unget(); } return tt; }, peekOnSameLine: function (scanOperand) { this.scanNewlines = true; var tt = this.peek(scanOperand); this.scanNewlines = false; return tt; }, lastBlockComment: function() { var length = this.blockComments.length; return length ? this.blockComments[length - 1] : null; }, // Eat comments and whitespace. skip: function () { var input = this.source; this.blockComments = []; for (;;) { var ch = input[this.cursor++]; var next = input[this.cursor]; // handle \r, \r\n and (always preferable) \n if (ch === '\r') { // if the next character is \n, we don't care about this at all if (next === '\n') continue; // otherwise, we want to consider this as a newline ch = '\n'; } if (ch === '\n' && !this.scanNewlines) { this.lineno++; } else if (ch === '/' && next === '*') { var commentStart = ++this.cursor; for (;;) { ch = input[this.cursor++]; if (ch === undefined) throw this.newSyntaxError("Unterminated comment"); if (ch === '*') { next = input[this.cursor]; if (next === '/') { var commentEnd = this.cursor - 1; this.cursor++; break; } } else if (ch === '\n') { this.lineno++; } } this.blockComments.push(input.substring(commentStart, commentEnd)); } else if ((ch === '/' && next === '/') || (this.allowHTMLComments && ch === '<' && next === '!' && input[this.cursor + 1] === '-' && input[this.cursor + 2] === '-' && (this.cursor += 2))) { this.cursor++; for (;;) { ch = input[this.cursor++]; next = input[this.cursor]; if (ch === undefined) return; if (ch === '\r') { // check for \r\n if (next !== '\n') ch = '\n'; } if (ch === '\n') { if (this.scanNewlines) { this.cursor--; } else { this.lineno++; } break; } } } else if (!(ch in definitions.whitespace)) { this.cursor--; return; } } }, // Lex the exponential part of a number, if present. Return true iff an // exponential part was found. lexExponent: function() { var input = this.source; var next = input[this.cursor]; if (next === 'e' || next === 'E') { this.cursor++; ch = input[this.cursor++]; if (ch === '+' || ch === '-') ch = input[this.cursor++]; if (ch < '0' || ch > '9') throw this.newSyntaxError("Missing exponent"); do { ch = input[this.cursor++]; } while (ch >= '0' && ch <= '9'); this.cursor--; return true; } return false; }, lexZeroNumber: function (ch) { var token = this.token, input = this.source; token.type = NUMBER; ch = input[this.cursor++]; if (ch === '.') { do { ch = input[this.cursor++]; } while (ch >= '0' && ch <= '9'); this.cursor--; this.lexExponent(); token.value = parseFloat( input.substring(token.start, this.cursor)); } else if (ch === 'x' || ch === 'X') { do { ch = input[this.cursor++]; } while ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')); this.cursor--; token.value = parseInt(input.substring(token.start, this.cursor)); } else if (ch >= '0' && ch <= '7') { do { ch = input[this.cursor++]; } while (ch >= '0' && ch <= '7'); this.cursor--; token.value = parseInt(input.substring(token.start, this.cursor)); } else { this.cursor--; this.lexExponent(); // 0E1, &c. token.value = 0; } }, lexNumber: function (ch) { var token = this.token, input = this.source; token.type = NUMBER; var floating = false; do { ch = input[this.cursor++]; if (ch === '.' && !floating) { floating = true; ch = input[this.cursor++]; } } while (ch >= '0' && ch <= '9'); this.cursor--; var exponent = this.lexExponent(); floating = floating || exponent; var str = input.substring(token.start, this.cursor); token.value = floating ? parseFloat(str) : parseInt(str); }, lexDot: function (ch) { var token = this.token, input = this.source; var next = input[this.cursor]; if (next >= '0' && next <= '9') { do { ch = input[this.cursor++]; } while (ch >= '0' && ch <= '9'); this.cursor--; this.lexExponent(); token.type = NUMBER; token.value = parseFloat( input.substring(token.start, this.cursor)); } else { token.type = DOT; token.assignOp = null; token.value = '.'; } }, lexString: function (ch) { var token = this.token, input = this.source; token.type = STRING; var hasEscapes = false; var delim = ch; if (input.length <= this.cursor) throw this.newSyntaxError("Unterminated string literal"); while ((ch = input[this.cursor++]) !== delim) { if (ch == '\n' || ch == '\r') throw this.newSyntaxError("Unterminated string literal"); if (this.cursor == input.length) throw this.newSyntaxError("Unterminated string literal"); if (ch === '\\') { hasEscapes = true; if (++this.cursor == input.length) throw this.newSyntaxError("Unterminated string literal"); } } token.value = hasEscapes ? eval(input.substring(token.start, this.cursor)) : input.substring(token.start + 1, this.cursor - 1); }, lexRegExp: function (ch) { var token = this.token, input = this.source; token.type = REGEXP; do { ch = input[this.cursor++]; if (ch === '\\') { this.cursor++; } else if (ch === '[') { do { if (ch === undefined) throw this.newSyntaxError("Unterminated character class"); if (ch === '\\') this.cursor++; ch = input[this.cursor++]; } while (ch !== ']'); } else if (ch === undefined) { throw this.newSyntaxError("Unterminated regex"); } } while (ch !== '/'); do { ch = input[this.cursor++]; } while (ch >= 'a' && ch <= 'z'); this.cursor--; token.value = eval(input.substring(token.start, this.cursor)); }, lexOp: function (ch) { var token = this.token, input = this.source; // A bit ugly, but it seems wasteful to write a trie lookup routine // for only 3 characters... var node = opTokens[ch]; var next = input[this.cursor]; if (next in node) { node = node[next]; this.cursor++; next = input[this.cursor]; if (next in node) { node = node[next]; this.cursor++; next = input[this.cursor]; } } var op = node.op; if (definitions.assignOps[op] && input[this.cursor] === '=') { this.cursor++; token.type = ASSIGN; token.assignOp = definitions.tokenIds[definitions.opTypeNames[op]]; op += '='; } else { token.type = definitions.tokenIds[definitions.opTypeNames[op]]; token.assignOp = null; } token.value = op; }, // FIXME: Unicode escape sequences lexIdent: function (ch, keywordIsName) { var token = this.token; var id = ch; while ((ch = this.getValidIdentifierChar(false)) !== null) { id += ch; } token.type = IDENTIFIER; token.value = id; if (keywordIsName) return; var kw; if (this.parser.mozillaMode) { kw = definitions.mozillaKeywords[id]; if (kw) { token.type = kw; return; } } if (this.parser.x.strictMode) { kw = definitions.strictKeywords[id]; if (kw) { token.type = kw; return; } } kw = definitions.keywords[id]; if (kw) token.type = kw; }, /* * Tokenizer.get :: ([boolean[, boolean]]) -> token type * * Consume input *only* if there is no lookahead. * Dispatch to the appropriate lexing function depending on the input. */ get: function (scanOperand, keywordIsName) { var token; while (this.lookahead) { --this.lookahead; this.tokenIndex = (this.tokenIndex + 1) & 3; token = this.tokens[this.tokenIndex]; if (token.type !== NEWLINE || this.scanNewlines) return token.type; } this.skip(); this.tokenIndex = (this.tokenIndex + 1) & 3; token = this.tokens[this.tokenIndex]; if (!token) this.tokens[this.tokenIndex] = token = {}; var input = this.source; if (this.cursor >= input.length) return token.type = END; token.start = this.cursor; token.lineno = this.lineno; var ich = this.getValidIdentifierChar(true); var ch = (ich === null) ? input[this.cursor++] : null; if (ich !== null) { this.lexIdent(ich, keywordIsName); } else if (scanOperand && ch === '/') { this.lexRegExp(ch); } else if (ch in opTokens) { this.lexOp(ch); } else if (ch === '.') { this.lexDot(ch); } else if (ch >= '1' && ch <= '9') { this.lexNumber(ch); } else if (ch === '0') { this.lexZeroNumber(ch); } else if (ch === '"' || ch === "'") { this.lexString(ch); } else if (this.scanNewlines && (ch === '\n' || ch === '\r')) { // if this was a \r, look for \r\n if (ch === '\r' && input[this.cursor] === '\n') this.cursor++; token.type = NEWLINE; token.value = '\n'; this.lineno++; } else { throw this.newSyntaxError("Illegal token"); } token.end = this.cursor; return token.type; }, /* * Tokenizer.unget :: void -> undefined * * Match depends on unget returning undefined. */ unget: function () { if (++this.lookahead === 4) throw "PANIC: too much lookahead!"; this.tokenIndex = (this.tokenIndex - 1) & 3; }, newSyntaxError: function (m) { m = (this.filename ? this.filename + ":" : "") + this.lineno + ": " + m; var e = new SyntaxError(m, this.filename, this.lineno); e.source = this.source; e.cursor = this.lookahead ? this.tokens[(this.tokenIndex + this.lookahead) & 3].start : this.cursor; return e; }, /* Gets a single valid identifier char from the input stream, or null * if there is none. */ getValidIdentifierChar: function(first) { var input = this.source; if (this.cursor >= input.length) return null; var ch = input[this.cursor]; // first check for \u escapes if (ch === '\\' && input[this.cursor+1] === 'u') { // get the character value try { ch = String.fromCharCode(parseInt( input.substring(this.cursor + 2, this.cursor + 6), 16)); } catch (ex) { return null; } this.cursor += 5; } var valid = isValidIdentifierChar(ch, first); if (valid) this.cursor++; return (valid ? ch : null); }, }; exports.isIdentifier = isIdentifier; exports.Tokenizer = Tokenizer; }); /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Narcissus JavaScript engine. * * The Initial Developer of the Original Code is * Brendan Eich <brendan@mozilla.org>. * Portions created by the Initial Developer are Copyright (C) 2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Tom Austin <taustin@ucsc.edu> * Brendan Eich <brendan@mozilla.org> * Shu-Yu Guo <shu@rfrn.org> * Dave Herman <dherman@mozilla.com> * Dimitris Vardoulakis <dimvar@ccs.neu.edu> * Patrick Walton <pcwalton@mozilla.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * Narcissus - JS implemented in JS. * * Well-known constants and lookup tables. Many consts are generated from the * tokens table via eval to minimize redundancy, so consumers must be compiled * separately to take advantage of the simple switch-case constant propagation * done by SpiderMonkey. */ define('ace/narcissus/definitions', ['require', 'exports', 'module' ], function(require, exports, module) { var tokens = [ // End of source. "END", // Operators and punctuators. Some pair-wise order matters, e.g. (+, -) // and (UNARY_PLUS, UNARY_MINUS). "\n", ";", ",", "=", "?", ":", "CONDITIONAL", "||", "&&", "|", "^", "&", "==", "!=", "===", "!==", "<", "<=", ">=", ">", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "!", "~", "UNARY_PLUS", "UNARY_MINUS", "++", "--", ".", "[", "]", "{", "}", "(", ")", // Nonterminal tree node type codes. "SCRIPT", "BLOCK", "LABEL", "FOR_IN", "CALL", "NEW_WITH_ARGS", "INDEX", "ARRAY_INIT", "OBJECT_INIT", "PROPERTY_INIT", "GETTER", "SETTER", "GROUP", "LIST", "LET_BLOCK", "ARRAY_COMP", "GENERATOR", "COMP_TAIL", // Contextual keywords. "IMPLEMENTS", "INTERFACE", "LET", "MODULE", "PACKAGE", "PRIVATE", "PROTECTED", "PUBLIC", "STATIC", "USE", "YIELD", // Terminals. "IDENTIFIER", "NUMBER", "STRING", "REGEXP", // Keywords. "break", "case", "catch", "const", "continue", "debugger", "default", "delete", "do", "else", "export", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", ]; var strictKeywords = { __proto__: null, "implements": true, "interface": true, "let": true, //"module": true, "package": true, "private": true, "protected": true, "public": true, "static": true, "use": true, "yield": true }; var statementStartTokens = [ "break", "const", "continue", "debugger", "do", "for", "if", "let", "return", "switch", "throw", "try", "var", "yield", "while", "with", ]; // Whitespace characters (see ECMA-262 7.2) var whitespaceChars = [ // normal whitespace: "\u0009", "\u000B", "\u000C", "\u0020", "\u00A0", "\uFEFF", // high-Unicode whitespace: "\u1680", "\u180E", "\u2000", "\u2001", "\u2002", "\u2003", "\u2004", "\u2005", "\u2006", "\u2007", "\u2008", "\u2009", "\u200A", "\u202F", "\u205F", "\u3000" ]; var whitespace = {}; for (var i = 0; i < whitespaceChars.length; i++) { whitespace[whitespaceChars[i]] = true; } // Operator and punctuator mapping from token to tree node type name. // NB: because the lexer doesn't backtrack, all token prefixes must themselves // be valid tokens (e.g. !== is acceptable because its prefixes are the valid // tokens != and !). var opTypeNames = { '\n': "NEWLINE", ';': "SEMICOLON", ',': "COMMA", '?': "HOOK", ':': "COLON", '||': "OR", '&&': "AND", '|': "BITWISE_OR", '^': "BITWISE_XOR", '&': "BITWISE_AND", '===': "STRICT_EQ", '==': "EQ", '=': "ASSIGN", '!==': "STRICT_NE", '!=': "NE", '<<': "LSH", '<=': "LE", '<': "LT", '>>>': "URSH", '>>': "RSH", '>=': "GE", '>': "GT", '++': "INCREMENT", '--': "DECREMENT", '+': "PLUS", '-': "MINUS", '*': "MUL", '/': "DIV", '%': "MOD", '!': "NOT", '~': "BITWISE_NOT", '.': "DOT", '[': "LEFT_BRACKET", ']': "RIGHT_BRACKET", '{': "LEFT_CURLY", '}': "RIGHT_CURLY", '(': "LEFT_PAREN", ')': "RIGHT_PAREN" }; // Hash of keyword identifier to tokens index. NB: we must null __proto__ to // avoid toString, etc. namespace pollution. var keywords = {__proto__: null}; var mozillaKeywords = {__proto__: null}; // Define const END, etc., based on the token names. Also map name to index. var tokenIds = {}; var hostSupportsEvalConst = (function() { try { return eval("(function(s) { eval(s); return x })('const x = true;')"); } catch (e) { return false; } })(); // Building up a string to be eval'd in different contexts. var consts = hostSupportsEvalConst ? "const " : "var "; for (var i = 0, j = tokens.length; i < j; i++) { if (i > 0) consts += ", "; var t = tokens[i]; var name; if (/^[a-z]/.test(t)) { name = t.toUpperCase(); if (name === "LET" || name === "YIELD") mozillaKeywords[name] = i; if (strictKeywords[name]) strictKeywords[name] = i; keywords[t] = i; } else { name = (/^\W/.test(t) ? opTypeNames[t] : t); } consts += name + " = " + i; tokenIds[name] = i; tokens[t] = i; } consts += ";"; var isStatementStartCode = {__proto__: null}; for (i = 0, j = statementStartTokens.length; i < j; i++) isStatementStartCode[keywords[statementStartTokens[i]]] = true; // Map assignment operators to their indexes in the tokens array. var assignOps = ['|', '^', '&', '<<', '>>', '>>>', '+', '-', '*', '/', '%']; for (i = 0, j = assignOps.length; i < j; i++) { t = assignOps[i]; assignOps[t] = tokens[t]; } function defineGetter(obj, prop, fn, dontDelete, dontEnum) { Object.defineProperty(obj, prop, { get: fn, configurable: !dontDelete, enumerable: !dontEnum }); } function defineGetterSetter(obj, prop, getter, setter, dontDelete, dontEnum) { Object.defineProperty(obj, prop, { get: getter, set: setter, configurable: !dontDelete, enumerable: !dontEnum }); } function defineMemoGetter(obj, prop, fn, dontDelete, dontEnum) { Object.defineProperty(obj, prop, { get: function() { var val = fn(); defineProperty(obj, prop, val, dontDelete, true, dontEnum); return val; }, configurable: true, enumerable: !dontEnum }); } function defineProperty(obj, prop, val, dontDelete, readOnly, dontEnum) { Object.defineProperty(obj, prop, { value: val, writable: !readOnly, configurable: !dontDelete, enumerable: !dontEnum }); } // Returns true if fn is a native function. (Note: SpiderMonkey specific.) function isNativeCode(fn) { // Relies on the toString method to identify native code. return ((typeof fn) === "function") && fn.toString().match(/\[native code\]/); } var Fpapply = Function.prototype.apply; function apply(f, o, a) { return Fpapply.call(f, [o].concat(a)); } var applyNew; // ES5's bind is a simpler way to implement applyNew if (Function.prototype.bind) { applyNew = function applyNew(f, a) { return new (f.bind.apply(f, [,].concat(Array.prototype.slice.call(a))))(); }; } else { applyNew = function applyNew(f, a) { switch (a.length) { case 0: return new f(); case 1: return new f(a[0]); case 2: return new f(a[0], a[1]); case 3: return new f(a[0], a[1], a[2]); default: var argStr = "a[0]"; for (var i = 1, n = a.length; i < n; i++) argStr += ",a[" + i + "]"; return eval("new f(" + argStr + ")"); } }; } function getPropertyDescriptor(obj, name) { while (obj) { if (({}).hasOwnProperty.call(obj, name)) return Object.getOwnPropertyDescriptor(obj, name); obj = Object.getPrototypeOf(obj); } } function getPropertyNames(obj) { var table = Object.create(null, {}); while (obj) { var names = Object.getOwnPropertyNames(obj); for (var i = 0, n = names.length; i < n; i++) table[names[i]] = true; obj = Object.getPrototypeOf(obj); } return Object.keys(table); } function getOwnProperties(obj) { var map = {}; for (var name in Object.getOwnPropertyNames(obj)) map[name] = Object.getOwnPropertyDescriptor(obj, name); return map; } function blacklistHandler(target, blacklist) { var mask = Object.create(null, {}); var redirect = Dict.create(blacklist).mapObject(function(name) { return mask; }); return mixinHandler(redirect, target); } function whitelistHandler(target, whitelist) { var catchall = Object.create(null, {}); var redirect = Dict.create(whitelist).mapObject(function(name) { return target; }); return mixinHandler(redirect, catchall); } /* * Mixin proxies break the single-inheritance model of prototypes, so * the handler treats all properties as own-properties: * * X * | * +------------+------------+ * | O | * | | | * | O O O | * | | | | | * | O O O O | * | | | | | | * | O O O O O | * | | | | | | | * +-(*)--(w)--(x)--(y)--(z)-+ */ function mixinHandler(redirect, catchall) { function targetFor(name) { return hasOwn(redirect, name) ? redirect[name] : catchall; } function getMuxPropertyDescriptor(name) { var desc = getPropertyDescriptor(targetFor(name), name); if (desc) desc.configurable = true; return desc; } function getMuxPropertyNames() { var names1 = Object.getOwnPropertyNames(redirect).filter(function(name) { return name in redirect[name]; }); var names2 = getPropertyNames(catchall).filter(function(name) { return !hasOwn(redirect, name); }); return names1.concat(names2); } function enumerateMux() { var result = Object.getOwnPropertyNames(redirect).filter(function(name) { return name in redirect[name]; }); for (name in catchall) { if (!hasOwn(redirect, name)) result.push(name); }; return result; } function hasMux(name) { return name in targetFor(name); } return { getOwnPropertyDescriptor: getMuxPropertyDescriptor, getPropertyDescriptor: getMuxPropertyDescriptor, getOwnPropertyNames: getMuxPropertyNames, defineProperty: function(name, desc) { Object.defineProperty(targetFor(name), name, desc); }, "delete": function(name) { var target = targetFor(name); return delete target[name]; }, // FIXME: ha ha ha fix: function() { }, has: hasMux, hasOwn: hasMux, get: function(receiver, name) { var target = targetFor(name); return target[name]; }, set: function(receiver, name, val) { var target = targetFor(name); target[name] = val; return true; }, enumerate: enumerateMux, keys: enumerateMux }; } function makePassthruHandler(obj) { // Handler copied from // http://wiki.ecmascript.org/doku.php?id=harmony:proxies&s=proxy%20object#examplea_no-op_forwarding_proxy return { getOwnPropertyDescriptor: function(name) { var desc = Object.getOwnPropertyDescriptor(obj, name); // a trapping proxy's properties must always be configurable desc.configurable = true; return desc; }, getPropertyDescriptor: function(name) { var desc = getPropertyDescriptor(obj, name); // a trapping proxy's properties must always be configurable desc.configurable = true; return desc; }, getOwnPropertyNames: function() { return Object.getOwnPropertyNames(obj); }, defineProperty: function(name, desc) { Object.defineProperty(obj, name, desc); }, "delete": function(name) { return delete obj[name]; }, fix: function() { if (Object.isFrozen(obj)) { return getOwnProperties(obj); } // As long as obj is not frozen, the proxy won't allow itself to be fixed. return undefined; // will cause a TypeError to be thrown }, has: function(name) { return name in obj; }, hasOwn: function(name) { return ({}).hasOwnProperty.call(obj, name); }, get: function(receiver, name) { return obj[name]; }, // bad behavior when set fails in non-strict mode set: function(receiver, name, val) { obj[name] = val; return true; }, enumerate: function() { var result = []; for (name in obj) { result.push(name); }; return result; }, keys: function() { return Object.keys(obj); } }; } var hasOwnProperty = ({}).hasOwnProperty; function hasOwn(obj, name) { return hasOwnProperty.call(obj, name); } function Dict(table, size) { this.table = table || Object.create(null, {}); this.size = size || 0; } Dict.create = function(table) { var init = Object.create(null, {}); var size = 0; var names = Object.getOwnPropertyNames(table); for (var i = 0, n = names.length; i < n; i++) { var name = names[i]; init[name] = table[name]; size++; } return new Dict(init, size); }; Dict.prototype = { has: function(x) { return hasOwnProperty.call(this.table, x); }, set: function(x, v) { if (!hasOwnProperty.call(this.table, x)) this.size++; this.table[x] = v; }, get: function(x) { return this.table[x]; }, getDef: function(x, thunk) { if (!hasOwnProperty.call(this.table, x)) { this.size++; this.table[x] = thunk(); } return this.table[x]; }, forEach: function(f) { var table = this.table; for (var key in table) f.call(this, key, table[key]); }, map: function(f) { var table1 = this.table; var table2 = Object.create(null, {}); this.forEach(function(key, val) { table2[key] = f.call(this, val, key); }); return new Dict(table2, this.size); }, mapObject: function(f) { var table1 = this.table; var table2 = Object.create(null, {}); this.forEach(function(key, val) { table2[key] = f.call(this, val, key); }); return table2; }, toObject: function() { return this.mapObject(function(val) { return val; }); }, choose: function() { return Object.getOwnPropertyNames(this.table)[0]; }, remove: function(x) { if (hasOwnProperty.call(this.table, x)) { this.size--; delete this.table[x]; } }, copy: function() { var table = Object.create(null, {}); for (var key in this.table) table[key] = this.table[key]; return new Dict(table, this.size); }, keys: function() { return Object.keys(this.table); }, toString: function() { return "[object Dict]" } }; var _WeakMap = typeof WeakMap === "function" ? WeakMap : (function() { // shim for ES6 WeakMap with poor asymptotics function WeakMap(array) { this.array = array || []; } function searchMap(map, key, found, notFound) { var a = map.array; for (var i = 0, n = a.length; i < n; i++) { var pair = a[i]; if (pair.key === key) return found(pair, i); } return notFound(); } WeakMap.prototype = { has: function(x) { return searchMap(this, x, function() { return true }, function() { return false }); }, set: function(x, v) { var a = this.array; searchMap(this, x, function(pair) { pair.value = v }, function() { a.push({ key: x, value: v }) }); }, get: function(x) { return searchMap(this, x, function(pair) { return pair.value }, function() { return null }); }, "delete": function(x) { var a = this.array; searchMap(this, x, function(pair, i) { a.splice(i, 1) }, function() { }); }, toString: function() { return "[object WeakMap]" } }; return WeakMap; })(); // non-destructive stack function Stack(elts) { this.elts = elts || null; } Stack.prototype = { push: function(x) { return new Stack({ top: x, rest: this.elts }); }, top: function() { if (!this.elts) throw new Error("empty stack"); return this.elts.top; }, isEmpty: function() { return this.top === null; }, find: function(test) { for (var elts = this.elts; elts; elts = elts.rest) { if (test(elts.top)) return elts.top; } return null; }, has: function(x) { return Boolean(this.find(function(elt) { return elt === x })); }, forEach: function(f) { for (var elts = this.elts; elts; elts = elts.rest) { f(elts.top); } } }; if (!Array.prototype.copy) { defineProperty(Array.prototype, "copy", function() { var result = []; for (var i = 0, n = this.length; i < n; i++) result[i] = this[i]; return result; }, false, false, true); } if (!Array.prototype.top) { defineProperty(Array.prototype, "top", function() { return this.length && this[this.length-1]; }, false, false, true); } exports.tokens = tokens; exports.whitespace = whitespace; exports.opTypeNames = opTypeNames; exports.keywords = keywords; exports.mozillaKeywords = mozillaKeywords; exports.strictKeywords = strictKeywords; exports.isStatementStartCode = isStatementStartCode; exports.tokenIds = tokenIds; exports.consts = consts; exports.assignOps = assignOps; exports.defineGetter = defineGetter; exports.defineGetterSetter = defineGetterSetter; exports.defineMemoGetter = defineMemoGetter; exports.defineProperty = defineProperty; exports.isNativeCode = isNativeCode; exports.apply = apply; exports.applyNew = applyNew; exports.mixinHandler = mixinHandler; exports.whitelistHandler = whitelistHandler; exports.blacklistHandler = blacklistHandler; exports.makePassthruHandler = makePassthruHandler; exports.Dict = Dict; exports.WeakMap = _WeakMap; exports.Stack = Stack; }); /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Narcissus JavaScript engine. * * The Initial Developer of the Original Code is * Brendan Eich <brendan@mozilla.org>. * Portions created by the Initial Developer are Copyright (C) 2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Tom Austin <taustin@ucsc.edu> * Brendan Eich <brendan@mozilla.org> * Shu-Yu Guo <shu@rfrn.org> * Dave Herman <dherman@mozilla.com> * Dimitris Vardoulakis <dimvar@ccs.neu.edu> * Patrick Walton <pcwalton@mozilla.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/narcissus/options', ['require', 'exports', 'module' ], function(require, exports, module) { // Global variables to hide from the interpreter exports.hiddenHostGlobals = { Narcissus: true }; // Desugar SpiderMonkey language extensions? exports.desugarExtensions = false; // Allow HTML comments? exports.allowHTMLComments = false; // Allow non-standard Mozilla extensions? exports.mozillaMode = true; // Allow experimental paren-free mode? exports.parenFreeMode = false; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/worker-javascript.js
JavaScript
asf20
346,904
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Shlomo Zalman Heigh <shlomozalmanheigh AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/ruby', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/ruby_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var RubyHighlightRules = require("./ruby_highlight_rules").RubyHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new RubyHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/ruby_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var RubyHighlightRules = function() { var builtinFunctions = lang.arrayToMap( ("abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" + "assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" + "assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" + "assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" + "assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" + "assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" + "attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" + "caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" + "exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" + "gsub!|get_via_redirect|h|host!|https?|https!|include|Integer|lambda|link_to|" + "link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" + "p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" + "raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|" + "set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" + "throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" + "render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" + "content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" + "fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" + "time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" + "select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" + "file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" + "protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" + "send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" + "validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" + "validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" + "authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" + "filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" + "translate|localize|extract_locale_from_tld|t|l|caches_page|expire_page|caches_action|expire_action|" + "cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" + "has_many|has_one|belongs_to|has_and_belongs_to_many").split("|") ); var keywords = lang.arrayToMap( ("alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" + "__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" + "redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield").split("|") ); var buildinConstants = lang.arrayToMap( ("true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" + "RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING").split("|") ); var builtinVariables = lang.arrayToMap( ("\$DEBUG|\$defout|\$FILENAME|\$LOAD_PATH|\$SAFE|\$stdin|\$stdout|\$stderr|\$VERBOSE|" + "$!|root_url|flash|session|cookies|params|request|response|logger").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "comment", // multi line comment merge : true, regex : "^\=begin$", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // backtick string regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]" }, { token : "text", // namespaces aren't symbols regex : "::" }, { token : "variable.instancce", // instance variable regex : "@{1,2}(?:[a-zA-Z_]|\d)+" }, { token : "variable.class", // class name regex : "[A-Z](?:[a-zA-Z_]|\d)+" }, { token : "string", // symbol regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "self") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinVariables.hasOwnProperty(value)) return "variable.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : "^\=end$", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; }; oop.inherits(RubyHighlightRules, TextHighlightRules); exports.RubyHighlightRules = RubyHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-ruby.js
JavaScript
asf20
13,265
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/merbivore_soft', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-merbivore-soft"; exports.cssText = "\ .ace-merbivore-soft .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-merbivore-soft .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-merbivore-soft .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-merbivore-soft .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-merbivore-soft .ace_scroller {\ background-color: #1C1C1C;\ }\ \ .ace-merbivore-soft .ace_text-layer {\ cursor: text;\ color: #E6E1DC;\ }\ \ .ace-merbivore-soft .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-merbivore-soft .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-merbivore-soft .ace_marker-layer .ace_selection {\ background: #494949;\ }\ \ .ace-merbivore-soft.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #1C1C1C;\ border-radius: 2px;\ }\ \ .ace-merbivore-soft .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-merbivore-soft .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #404040;\ }\ \ .ace-merbivore-soft .ace_marker-layer .ace_active_line {\ background: #333435;\ }\ \ .ace-merbivore-soft .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-merbivore-soft .ace_marker-layer .ace_selected_word {\ border: 1px solid #494949;\ }\ \ .ace-merbivore-soft .ace_invisible {\ color: #404040;\ }\ \ .ace-merbivore-soft .ace_keyword, .ace-merbivore-soft .ace_meta {\ color:#FC803A;\ }\ \ .ace-merbivore-soft .ace_constant, .ace-merbivore-soft .ace_constant.ace_other {\ color:#68C1D8;\ }\ \ .ace-merbivore-soft .ace_constant.ace_character, {\ color:#68C1D8;\ }\ \ .ace-merbivore-soft .ace_constant.ace_character.ace_escape, {\ color:#68C1D8;\ }\ \ .ace-merbivore-soft .ace_constant.ace_language {\ color:#E1C582;\ }\ \ .ace-merbivore-soft .ace_constant.ace_library {\ color:#8EC65F;\ }\ \ .ace-merbivore-soft .ace_constant.ace_numeric {\ color:#7FC578;\ }\ \ .ace-merbivore-soft .ace_invalid {\ color:#FFFFFF;\ background-color:#FE3838;\ }\ \ .ace-merbivore-soft .ace_invalid.ace_deprecated {\ color:#FFFFFF;\ background-color:#FE3838;\ }\ \ .ace-merbivore-soft .ace_support.ace_constant {\ color:#8EC65F;\ }\ \ .ace-merbivore-soft .ace_fold {\ background-color: #FC803A;\ border-color: #E6E1DC;\ }\ \ .ace-merbivore-soft .ace_storage {\ color:#FC803A;\ }\ \ .ace-merbivore-soft .ace_string {\ color:#8EC65F;\ }\ \ .ace-merbivore-soft .ace_comment {\ font-style:italic;\ color:#AC4BB8;\ }\ \ .ace-merbivore-soft .ace_meta {\ font-style:italic;\ color:#AC4BB8;\ }\ \ .ace-merbivore-soft .ace_meta.ace_tag {\ color:#FC803A;\ }\ \ .ace-merbivore-soft .ace_entity.ace_other.ace_attribute-name {\ color:#EAF1A3;\ }\ \ .ace-merbivore-soft .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-merbivore_soft.js
JavaScript
asf20
4,883
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Gastón Kleiman <gaston.kleiman AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/c_cpp', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/c_cpp_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var c_cppHighlightRules = require("./c_cpp_highlight_rules").c_cppHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new c_cppHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/c_cpp_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var c_cppHighlightRules = function() { var keywords = lang.arrayToMap( ("and|double|not_eq|throw|and_eq|dynamic_cast|operator|true|" + "asm|else|or|try|auto|enum|or_eq|typedef|bitand|explicit|private|" + "typeid|bitor|extern|protected|typename|bool|false|public|union|" + "break|float|register|unsigned|case|fro|reinterpret-cast|using|catch|" + "friend|return|virtual|char|goto|short|void|class|if|signed|volatile|" + "compl|inline|sizeof|wchar_t|const|int|static|while|const-cast|long|" + "static_cast|xor|continue|mutable|struct|xor_eq|default|namespace|" + "switch|delete|new|template|do|not|this|for").split("|") ); var buildinConstants = lang.arrayToMap( ("NULL").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant", // <CONSTANT> regex : "<[a-zA-Z0-9.]+>" }, { token : "keyword", // pre-compiler directivs regex : "(?:#include|#pragma|#line|#define|#undef|#ifdef|#else|#elif|#endif|#ifndef)" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(c_cppHighlightRules, TextHighlightRules); exports.c_cppHighlightRules = c_cppHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-c_cpp.js
JavaScript
asf20
23,965
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Kelley van Evert <kelley.vanevert@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/textile', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/textile_highlight_rules', 'ace/mode/matching_brace_outdent'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var TextileHighlightRules = require("./textile_highlight_rules").TextileHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Mode = function() { this.$tokenizer = new Tokenizer(new TextileHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { if (state == "intag") return tab; return ""; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/textile_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var TextileHighlightRules = function() { this.$rules = { "start" : [ { token : function(value) { if (value.match(/^h\d$/)) return "markup.heading." + value.charAt(1); else return "markup.heading"; }, regex : "h1|h2|h3|h4|h5|h6|bq|p|bc|pre", next : "blocktag" }, { token : "keyword", regex : "[\\*]+|[#]+" }, { token : "text", regex : ".+" } ], "blocktag" : [ { token : "keyword", regex : "\\. ", next : "start" }, { token : "keyword", regex : "\\(", next : "blocktagproperties" } ], "blocktagproperties" : [ { token : "keyword", regex : "\\)", next : "blocktag" }, { token : "string", regex : "[a-zA-Z0-9\\-_]+" }, { token : "keyword", regex : "#" } ] }; }; oop.inherits(TextileHighlightRules, TextHighlightRules); exports.TextileHighlightRules = TextileHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-textile.js
JavaScript
asf20
5,745
define('ace/mode/scala', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/javascript', 'ace/tokenizer', 'ace/mode/scala_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var JavaScriptMode = require("./javascript").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ScalaHighlightRules = require("./scala_highlight_rules").ScalaHighlightRules; var Mode = function() { JavaScriptMode.call(this); this.$tokenizer = new Tokenizer(new ScalaHighlightRules().getRules()); }; oop.inherits(Mode, JavaScriptMode); (function() { this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/scala_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ScalaHighlightRules = function() { // taken from http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html var keywords = lang.arrayToMap( ( "case|default|do|else|for|if|match|while|throw|return|try|catch|finally|yield|" + "abstract|class|def|extends|final|forSome|implicit|implicits|import|lazy|new|object|" + "override|package|private|protected|sealed|super|this|trait|type|val|var|with" ).split("|") ); var buildinConstants = lang.arrayToMap( ("true|false").split("|") ); var langClasses = lang.arrayToMap( ("AbstractMethodError|AssertionError|ClassCircularityError|"+ "ClassFormatError|Deprecated|EnumConstantNotPresentException|"+ "ExceptionInInitializerError|IllegalAccessError|"+ "IllegalThreadStateException|InstantiationError|InternalError|"+ "NegativeArraySizeException|NoSuchFieldError|Override|Process|"+ "ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|"+ "SuppressWarnings|TypeNotPresentException|UnknownError|"+ "UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|"+ "InstantiationException|IndexOutOfBoundsException|"+ "ArrayIndexOutOfBoundsException|CloneNotSupportedException|"+ "NoSuchFieldException|IllegalArgumentException|NumberFormatException|"+ "SecurityException|Void|InheritableThreadLocal|IllegalStateException|"+ "InterruptedException|NoSuchMethodException|IllegalAccessException|"+ "UnsupportedOperationException|Enum|StrictMath|Package|Compiler|"+ "Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|"+ "NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|"+ "NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|"+ "Character|Boolean|StackTraceElement|Appendable|StringBuffer|"+ "Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|"+ "StackOverflowError|OutOfMemoryError|VirtualMachineError|"+ "ArrayStoreException|ClassCastException|LinkageError|"+ "NoClassDefFoundError|ClassNotFoundException|RuntimeException|"+ "Exception|ThreadDeath|Error|Throwable|System|ClassLoader|"+ "Cloneable|Class|CharSequence|Comparable|String|Object|" + "Unit|Any|AnyVal|AnyRef|Null|ScalaObject|Singleton|Seq|Iterable|List|" + "Option|Array|Char|Byte|Short|Int|Long|Nothing" ).split("|") ); var importClasses = lang.arrayToMap( ("").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", regex : '"""', next : "tstring" }, { token : "string", regex : '"(?=.)', // " strings can't span multiple lines next : "string" }, { token : "symbol.constant", // single line regex : "'[\\w\\d_]+" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (langClasses.hasOwnProperty(value)) return "support.function"; else if (importClasses.hasOwnProperty(value)) return "support.function"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "string" : [ { token : "escape", regex : '\\\\"', }, { token : "string", merge : true, regex : '"', next : "start" }, { token : "string.invalid", regex : '[^"\\\\]*$', next : "start" }, { token : "string", regex : '[^"\\\\]+', merge : true } ], "tstring" : [ { token : "string", // closing comment regex : '"{3,5}', next : "start" }, { token : "string", // comment spanning whole line merge : true, regex : ".+?" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(ScalaHighlightRules, TextHighlightRules); exports.ScalaHighlightRules = ScalaHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-scala.js
JavaScript
asf20
45,567
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/twilight', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-twilight"; exports.cssText = "\ .ace-twilight .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-twilight .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-twilight .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-twilight .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-twilight .ace_scroller {\ background-color: #141414;\ }\ \ .ace-twilight .ace_text-layer {\ cursor: text;\ color: #F8F8F8;\ }\ \ .ace-twilight .ace_cursor {\ border-left: 2px solid #A7A7A7;\ }\ \ .ace-twilight .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #A7A7A7;\ }\ \ .ace-twilight .ace_marker-layer .ace_selection {\ background: rgba(221, 240, 255, 0.20);\ }\ \ .ace-twilight.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #141414;\ border-radius: 2px;\ }\ \ .ace-twilight .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-twilight .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(255, 255, 255, 0.25);\ }\ \ .ace-twilight .ace_marker-layer .ace_active_line {\ background: rgba(255, 255, 255, 0.031);\ }\ \ .ace-twilight .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-twilight .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(221, 240, 255, 0.20);\ }\ \ .ace-twilight .ace_invisible {\ color: rgba(255, 255, 255, 0.25);\ }\ \ .ace-twilight .ace_keyword, .ace-twilight .ace_meta {\ color:#CDA869;\ }\ \ .ace-twilight .ace_constant, .ace-twilight .ace_constant.ace_other {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_constant.ace_character, {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_constant.ace_character.ace_escape, {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_invalid.ace_illegal {\ color:#F8F8F8;\ background-color:rgba(86, 45, 86, 0.75);\ }\ \ .ace-twilight .ace_invalid.ace_deprecated {\ text-decoration:underline;\ font-style:italic;\ color:#D2A8A1;\ }\ \ .ace-twilight .ace_support {\ color:#9B859D;\ }\ \ .ace-twilight .ace_support.ace_constant {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_fold {\ background-color: #AC885B;\ border-color: #F8F8F8;\ }\ \ .ace-twilight .ace_support.ace_function {\ color:#DAD085;\ }\ \ .ace-twilight .ace_storage {\ color:#F9EE98;\ }\ \ .ace-twilight .ace_variable {\ color:#AC885B;\ }\ \ .ace-twilight .ace_string {\ color:#8F9D6A;\ }\ \ .ace-twilight .ace_string.ace_regexp {\ color:#E9C062;\ }\ \ .ace-twilight .ace_comment {\ font-style:italic;\ color:#5F5A60;\ }\ \ .ace-twilight .ace_variable {\ color:#7587A6;\ }\ \ .ace-twilight .ace_xml_pe {\ color:#494949;\ }\ \ .ace-twilight .ace_meta.ace_tag {\ color:#AC885B;\ }\ \ .ace-twilight .ace_entity.ace_name.ace_function {\ color:#AC885B;\ }\ \ .ace-twilight .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-twilight .ace_markup.ace_heading {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_markup.ace_list {\ color:#F9EE98;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-twilight.js
JavaScript
asf20
4,985
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/eclipse', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssText = ".ace-eclipse .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-eclipse .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-eclipse .ace_gutter {\ background: rgb(227, 227, 227);\ border-right: 1px solid rgb(159, 159, 159);\ color: rgb(136, 136, 136);\ }\ \ .ace-eclipse .ace_print_margin {\ width: 1px;\ background: #b1b4ba;\ }\ \ .ace-eclipse .ace_fold {\ background-color: rgb(60, 76, 114);\ }\ \ .ace-eclipse .ace_text-layer {\ cursor: text;\ }\ \ .ace-eclipse .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-eclipse .ace_line .ace_storage,\ .ace-eclipse .ace_line .ace_keyword,\ .ace-eclipse .ace_line .ace_variable {\ color: rgb(127, 0, 85);\ }\ \ .ace-eclipse .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-eclipse .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-eclipse .ace_line .ace_function {\ color: rgb(60, 76, 114);\ }\ \ .ace-eclipse .ace_line .ace_string {\ color: rgb(42, 0, 255);\ }\ \ .ace-eclipse .ace_line .ace_comment {\ color: rgb(63, 127, 95);\ }\ \ .ace-eclipse .ace_line .ace_comment.ace_doc {\ color: rgb(63, 95, 191);\ }\ \ .ace-eclipse .ace_line .ace_comment.ace_doc.ace_tag {\ color: rgb(127, 159, 191);\ }\ \ .ace-eclipse .ace_line .ace_constant.ace_numeric {\ }\ \ .ace-eclipse .ace_line .ace_tag {\ color: rgb(63, 127, 127);\ }\ \ .ace-eclipse .ace_line .ace_type {\ color: rgb(127, 0, 127);\ }\ \ .ace-eclipse .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-eclipse .ace_marker-layer .ace_selection {\ background: rgb(181, 213, 255);\ }\ \ .ace-eclipse .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgb(192, 192, 192);\ }\ \ .ace-eclipse .ace_line .ace_meta.ace_tag {\ color:rgb(63, 127, 127);\ }\ \ .ace-eclipse .ace_entity.ace_other.ace_attribute-name {\ color:rgb(127, 0, 127);\ }\ .ace-eclipse .ace_marker-layer .ace_step {\ background: rgb(255, 255, 0);\ }\ \ .ace-eclipse .ace_marker-layer .ace_active_line {\ background: rgb(232, 242, 254);\ }"; exports.cssClass = "ace-eclipse"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-eclipse.js
JavaScript
asf20
4,097
define('ace/mode/csharp', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/csharp_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CSharpHighlightRules = require("./csharp_highlight_rules").CSharpHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CSharpHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/csharp_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CSharpHighlightRules = function() { var keywords = lang.arrayToMap( ("abstract|event|new|struct|as|explicit|null|switch|base|extern|object|this|bool|false|operator|throw|break|finally|out|true|byte|fixed|override|try|case|float|params|typeof|catch|for|private|uint|char|foreach|protected|ulong|checked|goto|public|unchecked|class|if|readonly|unsafe|const|implicit|ref|ushort|continue|in|return|using|decimal|int|sbyte|virtual|default|interface|sealed|volatile|delegate|internal|short|void|do|is|sizeof|while|double|lock|stackalloc|else|long|static|enum|namespace|string|var|dynamic").split("|") ); var buildinConstants = lang.arrayToMap( ("null|true|false").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", merge : true, next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(CSharpHighlightRules, TextHighlightRules); exports.CSharpHighlightRules = CSharpHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-csharp.js
JavaScript
asf20
20,130
"no use strict"; var console = { log: function(msg) { postMessage({type: "log", data: msg}); } }; var window = { console: console }; 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("/"); var moduleName = base + "/" + moduleName; while(moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; var moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; var require = function(parentId, id) { var id = normalizeModule(parentId, id); var module = require.modules[id]; if (module) { if (!module.initialized) { module.exports = module.factory().exports; module.initialized = true; } return module.exports; } var chunks = id.split("/"); chunks[0] = require.tlns[chunks[0]] || chunks[0]; var path = chunks.join("/") + ".js"; require.id = id; importScripts(path); return require(parentId, id); }; require.modules = {}; require.tlns = {}; var define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; } else if (arguments.length == 1) { factory = id; id = require.id; } if (id.indexOf("text!") === 0) return; var req = function(deps, factory) { return require(id, deps, factory); }; require.modules[id] = { factory: function() { var module = { exports: {} }; var returnExports = factory(req, module.exports, module); if (returnExports) module.exports = returnExports; return module; } }; }; function initBaseUrls(topLevelNamespaces) { require.tlns = topLevelNamespaces; } function initSender() { var EventEmitter = require(null, "ace/lib/event_emitter").EventEmitter; var oop = require(null, "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; var sender; onmessage = function(e) { var msg = e.data; if (msg.command) { main[msg.command].apply(main, msg.args); } else if (msg.init) { initBaseUrls(msg.tlns); require(null, "ace/lib/fixoldbrowsers"); sender = initSender(); var clazz = require(null, msg.module)[msg.classname]; main = new clazz(sender); } else if (msg.event && sender) { sender._emit(msg.event, msg.data); } }; // vim:set ts=4 sts=4 sw=4 st: // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Irakli Gozalishvili Copyright (C) 2010 MIT License /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) { require("./regexp"); require("./es5-shim"); }); define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) { //--------------------------------- // Private variables //--------------------------------- 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; //--------------------------------- // Overriden native methods //--------------------------------- // Adds named capture support (with backreferences returned as `result.name`), and fixes two // cross-browser issues per ES3: // - Captured values for nonparticipating capturing groups should be returned as `undefined`, // rather than the empty string. // - `lastIndex` should not be incremented after zero-length matches. RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed // matching due to characters outside the match 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; } }); } // Attach named capture properties 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]; } } // Fix browsers that increment `lastIndex` after zero-length matches if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; } return match; }; // Don't override `test` if it won't change anything if (!compliantLastIndexIncrement) { // Fix browser bug in native method RegExp.prototype.test = function (str) { // Use the native `exec` to skip some processing overhead, even though the overriden // `exec` would take care of the `lastIndex` fix var match = real.exec.call(this, str); // Fix browsers that increment `lastIndex` after zero-length matches if (match && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; return !!match; }; } //--------------------------------- // Private helper functions //--------------------------------- 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; }; }); // vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License // -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License // -- kossnocorp Sasha Koss XXX TODO License or CLA // -- bryanforbes Bryan Forbes XXX TODO License or CLA // -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence // -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License // -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License // -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain) // -- iwyg XXX TODO License or CLA // -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License // -- xavierm02 Montillet Xavier XXX TODO License or CLA // -- Raynos Raynos XXX TODO License or CLA // -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License // -- rwldrn Rick Waldron Copyright (C) 2011 MIT License // -- lexer Alexey Zakharov XXX TODO License or CLA /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) { /* * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * * @module */ /*whatsupdoc*/ // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (typeof target != "function") throw new TypeError(); // TODO message // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){}; F.prototype = target.prototype; var self = new F; var result = target.apply( self, args.concat(slice.call(arguments)) ); if (result !== null && Object(result) === result) return result; return self; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(slice.call(arguments)) ); } }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. 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); // If JS engine supports accessors creating shortcuts. 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__); } // // Array // ===== // // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function isArray(obj) { return toString(obj) == "[object Array]"; }; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var self = toObject(this), thisp = arguments[1], i = 0, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object context fun.call(thisp, self[i], i, self); } i++; } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var self = toObject(this), length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, self); } return result; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, result = [], thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) result.push(self[i]); } return result; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, self)) return false; } return true; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) return true; } return false; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value and an empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) throw new TypeError(); // TODO message } while (true); } for (; i < length; i++) { if (i in self) result = fun.call(void 0, result, self[i], i, self); } return result; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value, empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) throw new TypeError(); // TODO message } while (true); } do { if (i in this) result = fun.call(void 0, result, self[i], i, self); } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = toObject(this), length = self.length >>> 0; if (!length) return -1; var i = 0; if (arguments.length > 1) i = toInteger(arguments[1]); // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = 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])); // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) return i; } return -1; }; } // // Object // ====== // // ES5 15.2.3.2 // http://es5.github.com/#x15.2.3.2 if (!Object.getPrototypeOf) { // https://github.com/kriskowal/es5-shim/issues#issue/2 // http://ejohn.org/blog/objectgetprototypeof/ // recommended by fschaefer on github Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } // ES5 15.2.3.3 // http://es5.github.com/#x15.2.3.3 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 object does not owns property return undefined immediately. if (!owns(object, property)) return; var descriptor, getter, setter; // If object has a property then it's for sure both `enumerable` and // `configurable`. descriptor = { enumerable: true, configurable: true }; // If JS engine supports accessor properties then property may be a // getter or setter. if (supportsAccessors) { // Unfortunately `__lookupGetter__` will return a getter even // if object has own non getter property along with a same named // inherited getter. To avoid misbehavior we temporary remove // `__proto__` so that `__lookupGetter__` will return getter only // if it's owned by an object. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); // Once we have getter and setter we can put values back. object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; // If it was accessor property we're done and return here // in order to avoid adding `value` to the descriptor. return descriptor; } } // If we got this far we know that object has an own property that is // not an accessor so we set it as a value and return descriptor. descriptor.value = object[property]; return descriptor; }; } // ES5 15.2.3.4 // http://es5.github.com/#x15.2.3.4 if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!Object.create) { Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = { "__proto__": null }; } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); // IE has no built-in implementation of `Object.getPrototypeOf` // neither `__proto__`, but this manually setting `__proto__` will // guarantee that `Object.getPrototypeOf` will work as expected with // objects created using `Object.create` object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } // ES5 15.2.3.6 // http://es5.github.com/#x15.2.3.6 // Patch for WebKit and IE8 standard mode // Designed by hax <hax.github.com> // related issue: https://github.com/kriskowal/es5-shim/issues#issue/5 // IE8 Reference: // http://msdn.microsoft.com/en-us/library/dd282900.aspx // http://msdn.microsoft.com/en-us/library/dd229916.aspx // WebKit Bugs: // https://bugs.webkit.org/show_bug.cgi?id=36423 function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { // returns falsy } } // check whether defineProperty works if it's given. Otherwise, // shim partially. 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); // make a valiant attempt to use the real defineProperty // for I8's DOM elements. if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { // try the shim if the real one doesn't work } } // If it's a data property. if (owns(descriptor, "value")) { // fail silently if "writable", "enumerable", or "configurable" // are requested but not supported /* // alternate approach: if ( // can't implement these features; allow false but not true !(owns(descriptor, "writable") ? descriptor.writable : true) || !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) || !(owns(descriptor, "configurable") ? descriptor.configurable : true) ) throw new RangeError( "This implementation of Object.defineProperty does not " + "support configurable, enumerable, or writable." ); */ if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { // As accessors are supported only on engines implementing // `__proto__` we can safely override `__proto__` while defining // a property to make sure that we don't hit an inherited // accessor. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; // Deleting a property anyway since getter / setter may be // defined on object itself. delete object[property]; object[property] = descriptor.value; // Setting original `__proto__` back now. object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); // If we got that far then getters and setters can be defined !! if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 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; }; } // ES5 15.2.3.8 // http://es5.github.com/#x15.2.3.8 if (!Object.seal) { Object.seal = function seal(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.9 // http://es5.github.com/#x15.2.3.9 if (!Object.freeze) { Object.freeze = function freeze(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // detect a Rhino bug and patch it 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); } // ES5 15.2.3.10 // http://es5.github.com/#x15.2.3.10 if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.11 // http://es5.github.com/#x15.2.3.11 if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } // ES5 15.2.3.12 // http://es5.github.com/#x15.2.3.12 if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } // ES5 15.2.3.13 // http://es5.github.com/#x15.2.3.13 if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { // 1. If Type(O) is not Object throw a TypeError exception. if (Object(object) === object) { throw new TypeError(); // TODO message } // 2. Return the Boolean value of the [[Extensible]] internal property of O. var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation 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; }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) { Date.prototype.toISOString = function toISOString() { var result, length, value, year; if (!isFinite(this)) throw new RangeError; // the date time string format is specified in 15.9.1.15. result = [this.getUTCMonth() + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = this.getUTCFullYear(); year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two digits. if (value < 10) result[length] = "0" + value; } // pad milliseconds to have three digits. return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z"; } } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). if (!Date.prototype.toJSON) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be ToPrimitive(O, hint Number). // 3. If tv is a Number and is not finite, return null. // XXX // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof this.toISOString != "function") throw new TypeError(); // TODO message // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return this.toISOString(); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function(NativeDate) { // Date.length === 7 var Date = function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length == 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); }; // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:\\.(\\d{3}))?" + // milliseconds capture ")?" + "(?:" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) Date[key] = NativeDate[key]; // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { match.shift(); // kill match[0], the full match // parse months, days, hours, minutes, seconds, and milliseconds for (var i = 1; i < 7; i++) { // provide default values if necessary match[i] = +(match[i] || (i < 3 ? 1 : 0)); // match[1] is the month. Months are 0-11 in JavaScript // `Date` objects, but 1-12 in ISO notation, so we // decrement. if (i == 1) match[i]--; } // parse the UTC offset component var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop(); // compute the explicit time zone offset if specified var offset = 0; if (sign) { // detect invalid offsets and return early if (hourOffset > 23 || minuteOffset > 59) return NaN; // express the provided time zone offset in minutes. The offset is // negative for time zones west of UTC; positive otherwise. offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1); } // Date.UTC for years between 0 and 99 converts year to 1900 + year // The Gregorian calendar has a 400-year cycle, so // to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...), // where 12622780800000 - number of milliseconds in Gregorian calendar 400 years var year = +match[0]; if (0 <= year && year <= 99) { match[0] = year + 400; return NativeDate.UTC.apply(this, match) + offset - 12622780800000; } // compute a new UTC date value, accounting for the optional offset return NativeDate.UTC.apply(this, match) + offset; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // // String // ====== // // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 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()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ 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, ""); }; } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer var toInteger = function (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; }; var prepareString = "a"[0] != "a", // ES5 9.9 // http://es5.github.com/#x9.9 toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError(); // TODO message } // If the implementation doesn't support by-index access of // string characters (ex. IE < 7), split the string if (prepareString && typeof o == "string" && o) { return o.split(""); } return Object(o); }; }); define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) { var EventEmitter = {}; 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; e = e || {}; e.type = eventName; if (!e.stopPropagation) { e.stopPropagation = function() { this.propagationStopped = true; }; } if (!e.preventDefault) { e.preventDefault = function() { this.defaultPrevented = true; }; } for (var i=0; i<listeners.length; i++) { listeners[i](e); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e); }; EventEmitter.setDefaultHandler = function(eventName, callback) { this._defaultHandlers = this._defaultHandlers || {}; if (this._defaultHandlers[eventName]) throw new Error("The default handler for '" + eventName + "' is already set"); this._defaultHandlers[eventName] = callback; }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) var listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners.push(callback); }; EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) { exports.inherits = (function() { var tempCtor = function() {}; return function(ctor, superCtor) { tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor.prototype; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }; }()); exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); define('ace/mode/json_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/mode/json/json_parse'], function(require, exports, module) { var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var parse = require("./json/json_parse"); var JsonWorker = exports.JsonWorker = function(sender) { Mirror.call(this, sender); this.setTimeout(200); }; oop.inherits(JsonWorker, Mirror); (function() { this.onUpdate = function() { var value = this.doc.getValue(); try { var result = parse(value); } catch (e) { var pos = this.charToDocumentPosition(e.at-1); this.sender.emit("error", { row: pos.row, column: pos.column, text: e.message, type: "error" }); return; } this.sender.emit("ok"); }; this.charToDocumentPosition = function(charPos) { var i = 0; var len = this.doc.getLength(); var nl = this.doc.getNewLineCharacter().length; if (!len) { return { row: 0, column: 0}; } var lineStart = 0; while (i < len) { var line = this.doc.getLine(i); var lineLength = line.length + nl; if (lineStart + lineLength > charPos) return { row: i, column: charPos - lineStart }; lineStart += lineLength; i += 1; } return { row: i-1, column: line.length }; }; }).call(JsonWorker.prototype); }); define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) { 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.deferredCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { doc.applyDeltas([e.data]); deferredUpdate.schedule(_self.$timeout); }); }; (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() { // abstract method }; }).call(Mirror.prototype); }); define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; /** * new Document([text]) * - text (String | Array): The starting text * * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * **/ var Document = function(text) { this.$lines = []; // There has to be one line at least in the document. If you pass an empty // string to the insert function, nothing will happen. Workaround. if (text.length == 0) { this.$lines = [""]; } else if (Array.isArray(text)) { this.insertLines(0, text); } else { this.insert({row: 0, column:0}, text); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength(); this.remove(new Range(0, 0, len, this.getLine(len-1).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); }; // check for IE split bug 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); if (match) { this.$autoNewLine = match[1]; } else { this.$autoNewLine = "\n"; } }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; case "auto": return this.$autoNewLine; } }; this.$autoNewLine = "\n"; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; }; 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) { if (range.start.row == range.end.row) { return this.$lines[range.start.row].substring(range.start.column, range.end.column); } else { var lines = this.getLines(range.start.row+1, range.end.row-1); lines.unshift((this.$lines[range.start.row] || "").substring(range.start.column)); lines.push((this.$lines[range.end.row] || "").substring(0, range.end.column)); return lines.join(this.getNewLineCharacter()); } }; 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; } return position; }; this.insert = function(position, text) { if (!text || text.length === 0) return position; position = this.$clipPosition(position); // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); var lines = this.$split(text); var firstLine = lines.splice(0, 1)[0]; var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0]; position = this.insertInLine(position, firstLine); if (lastLine !== null) { position = this.insertNewLine(position); // terminate first line position = this.insertLines(position.row, lines); position = this.insertInLine(position, lastLine || ""); } return position; }; this.insertLines = function(row, lines) { if (lines.length == 0) return {row: row, column: 0}; // apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF) // to circumvent that we have to break huge inserts into smaller chunks here if (lines.length > 0xFFFF) { var end = this.insertLines(row, lines.slice(0xFFFF)); lines = lines.slice(0, 0xFFFF); } var args = [row, 0]; args.push.apply(args, lines); this.$lines.splice.apply(this.$lines, args); var range = new Range(row, 0, row + lines.length, 0); var delta = { action: "insertLines", range: range, lines: lines }; this._emit("change", { data: delta }); return end || range.end; }; this.insertNewLine = function(position) { position = this.$clipPosition(position); var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column); this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length)); var end = { row : position.row + 1, column : 0 }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); return end; }; this.insertInLine = function(position, text) { if (text.length == 0) return position; var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column) + text + line.substring(position.column); var end = { row : position.row, column : position.column + text.length }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: text }; this._emit("change", { data: delta }); return end; }; this.remove = function(range) { // clip to document range.start = this.$clipPosition(range.start); range.end = this.$clipPosition(range.end); if (range.isEmpty()) return range.start; var firstRow = range.start.row; var lastRow = range.end.row; if (range.isMultiLine()) { var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1; var lastFullRow = lastRow - 1; if (range.end.column > 0) this.removeInLine(lastRow, 0, range.end.column); if (lastFullRow >= firstFullRow) this.removeLines(firstFullRow, lastFullRow); if (firstFullRow != firstRow) { this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length); this.removeNewLine(range.start.row); } } else { this.removeInLine(firstRow, range.start.column, range.end.column); } return range.start; }; this.removeInLine = function(row, startColumn, endColumn) { if (startColumn == endColumn) return; var range = new Range(row, startColumn, row, endColumn); var line = this.getLine(row); var removed = line.substring(startColumn, endColumn); var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length); this.$lines.splice(row, 1, newLine); var delta = { action: "removeText", range: range, text: removed }; this._emit("change", { data: delta }); return range.start; }; this.removeLines = function(firstRow, lastRow) { var range = new Range(firstRow, 0, lastRow + 1, 0); var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1); var delta = { action: "removeLines", range: range, nl: this.getNewLineCharacter(), lines: removed }; this._emit("change", { data: delta }); return removed; }; this.removeNewLine = function(row) { var firstLine = this.getLine(row); var secondLine = this.getLine(row+1); var range = new Range(row, firstLine.length, row+1, 0); var line = firstLine + secondLine; this.$lines.splice(row, 2, line); var delta = { action: "removeText", range: range, text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); }; this.replace = function(range, text) { if (text.length == 0 && range.isEmpty()) return range.start; // Shortcut: If the text we want to insert is the same as it is already // in the document, we don't have to replace anything. if (text == this.getTextRange(range)) return range.end; this.remove(range); if (text) { var end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "insertText") this.insert(range.start, delta.text); else if (delta.action == "removeLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "removeText") this.remove(range); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "insertText") this.remove(range); else if (delta.action == "removeLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "removeText") this.insert(range.start, delta.text); } }; }).call(Document.prototype); exports.Document = Document; }); define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class Range * * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. * **/ /** * new Range(startRow, startColumn, endRow, endColumn) * - startRow (Number): The starting row * - startColumn (Number): The starting column * - endRow (Number): The ending row * - endColumn (Number): The ending column * * Creates a new `Range` object with the given starting and ending row and column points. * **/ var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { /** * Range.isEqual(range) -> Boolean * - range (Range): A range to check against * * Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`. * **/ 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; } } } /** related to: Range.compare * Range.comparePoint(p) -> Number * - p (Range): A point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1<br/> * * Checks the row and column points of `p` with the row and column points of the calling range. * * * **/ this.comparePoint = function(p) { return this.compare(p.row, p.column); } /** related to: Range.comparePoint * Range.containsRange(range) -> Boolean * - range (Range): A range to compare with * * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. * **/ this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } /** * Range.intersects(range) -> Boolean * - range (Range): A range to compare with * * Returns `true` if passed in `range` intersects with the one calling this method. * **/ this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); } /** * Range.isEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. * **/ this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } /** * Range.isStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. * **/ this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; } /** * Range.setStart(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** * Range.setEnd(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ 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; } } /** related to: Range.compare * Range.inside(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range. * **/ 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; } /** related to: Range.compare * Range.insideStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's starting points. * **/ this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; } /** related to: Range.compare * Range.insideEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's ending points. * **/ this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; } /** * Range.compare(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal <br/> * * `-1` if `p.row` is less then the calling range <br/> * * `1` if `p.row` is greater than the calling range <br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> * <br/> * If the ending row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0` <br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ 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); } } /** * Range.compareEnd(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } } /** * Range.compareInside(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`<br/> * * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`<br/> * <br/> * Otherwise, it returns the value after calling [[Range.compare `compare()`]]. * * Checks the row and column points with the row and column points of the calling range. * * * **/ 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); } } /** * Range.clipRows(firstRow, lastRow) -> Range * - firstRow (Number): The starting row * - lastRow (Number): The ending row * * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. * **/ this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) { var end = { row: lastRow+1, column: 0 }; } if (this.start.row > lastRow) { var start = { row: lastRow+1, column: 0 }; } if (this.start.row < firstRow) { var start = { row: firstRow, column: 0 }; } if (this.end.row < firstRow) { var end = { 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 ); }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; exports.Range = Range; }); define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; /** * new Anchor(doc, row, column) * - doc (Document): The document to associate with the anchor * - row (Number): The starting row position * - column (Number): The starting column position * * Creates a new `Anchor` and associates it with a document. * **/ var Anchor = exports.Anchor = function(doc, row, column) { this.document = doc; if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); this.$onChange = this.onChange.bind(this); doc.on("change", this.$onChange); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.onChange = function(e) { var delta = e.data; var range = delta.range; if (range.start.row == range.end.row && range.start.row != this.row) return; if (range.start.row > this.row) return; if (range.start.row == this.row && range.start.column > this.column) return; var row = this.row; var column = this.column; if (delta.action === "insertText") { if (range.start.row === row && range.start.column <= column) { if (range.start.row === range.end.row) { column += range.end.column - range.start.column; } else { column -= range.start.column; row += range.end.row - range.start.row; } } else if (range.start.row !== range.end.row && range.start.row < row) { row += range.end.row - range.start.row; } } else if (delta.action === "insertLines") { if (range.start.row <= row) { row += range.end.row - range.start.row; } } else if (delta.action == "removeText") { if (range.start.row == row && range.start.column < column) { if (range.end.column >= column) column = range.start.column; else column = Math.max(0, column - (range.end.column - range.start.column)); } else if (range.start.row !== range.end.row && range.start.row < row) { if (range.end.row == row) { column = Math.max(0, column - range.end.column) + range.start.column; } row -= (range.end.row - range.start.row); } else if (range.end.row == row) { row -= range.end.row - range.start.row; column = Math.max(0, column - range.end.column) + range.start.column; } } else if (delta.action == "removeLines") { if (range.start.row <= row) { if (range.end.row <= row) row -= range.end.row - range.start.row; else { row = range.start.row; column = 0; } } } this.setPosition(row, column, true); }; 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._emit("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("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); }); define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) { exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { return new Array(count + 1).join(string); }; 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<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function (obj) { if (typeof obj != "object") { return obj; } var copy = obj.constructor(); for (var key in obj) { if (typeof obj[key] == "object") { copy[key] = this.deepCopy(obj[key]); } else { copy[key] = obj[key]; } } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; return deferred; }; }); /*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode, hasOwnProperty, message, n, name, push, r, t, text */ define('ace/mode/json/json_parse', ['require', 'exports', 'module' ], function(require, exports, module) { // This is a function that can parse a JSON text, producing a JavaScript // data structure. It is a simple, recursive descent parser. It does not use // eval or regular expressions, so it can be used as a model for implementing // a JSON parser in other languages. // We are defining the function inside of another function to avoid creating // global variables. var at, // The index of the current character ch, // The current character escapee = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }, text, error = function (m) { // Call error when something is wrong. throw { name: 'SyntaxError', message: m, at: at, text: text }; }, next = function (c) { // If a c parameter is provided, verify that it matches the current character. if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } // Get the next character. When there are no more characters, // return the empty string. ch = text.charAt(at); at += 1; return ch; }, number = function () { // Parse a number value. var number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch === 'e' || ch === 'E') { string += ch; next(); if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (isNaN(number)) { error("Bad number"); } else { return number; } }, string = function () { // Parse a string value. var hex, i, string = '', uffff; // When parsing for string values, we must look for " and \ characters. if (ch === '"') { while (next()) { if (ch === '"') { next(); return string; } else if (ch === '\\') { next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { break; } } else { string += ch; } } } error("Bad string"); }, white = function () { // Skip whitespace. while (ch && ch <= ' ') { next(); } }, word = function () { // true, false, or null. switch (ch) { case 't': next('t'); next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); }, value, // Place holder for the value function. array = function () { // Parse an array value. var array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array; // empty array } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error("Bad array"); }, object = function () { // Parse an object value. var key, object = {}; if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object; // empty object } while (ch) { key = string(); white(); next(':'); if (Object.hasOwnProperty.call(object, key)) { error('Duplicate key "' + key + '"'); } object[key] = value(); white(); if (ch === '}') { next('}'); return object; } next(','); white(); } } error("Bad object"); }; value = function () { // Parse a JSON value. It could be an object, an array, a string, a number, // or a word. white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } }; // Return the json_parse function. It will have access to all of the above // functions and variables. return function (source, reviver) { var result; text = source; at = 0; ch = ' '; result = value(); white(); if (ch) { error("Syntax error"); } // If there is a reviver function, we recursively walk the new structure, // passing each name/value pair to the reviver function for possible // transformation, starting with a temporary root object that holds the result // in an empty key. If there is not a reviver function, we simply return the // result. return typeof reviver === 'function' ? function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }({'': result}, '') : result; }; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/worker-json.js
JavaScript
asf20
94,563
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Panagiotis Astithas <pastith AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/perl', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/perl_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var PerlHighlightRules = require("./perl_highlight_rules").PerlHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new PerlHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/perl_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PerlHighlightRules = function() { var keywords = lang.arrayToMap( ("base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|" + "no|package|parent|redo|require|scalar|sub|unless|until|while|use|vars").split("|") ); var buildinConstants = lang.arrayToMap( ("ARGV|ENV|INC|SIG").split("|") ); var builtinFunctions = lang.arrayToMap( ("getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|" + "gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|" + "getpeername|setpriority|getprotoent|setprotoent|getpriority|" + "endprotoent|getservent|setservent|endservent|sethostent|socketpair|" + "getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|" + "localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|" + "closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|" + "shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|" + "dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|" + "setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|" + "lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|" + "waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|" + "chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|" + "unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|" + "length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|" + "undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|" + "sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|" + "BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|" + "join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|" + "keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|" + "eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|" + "map|die|uc|lc|do").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0x[0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(PerlHighlightRules, TextHighlightRules); exports.PerlHighlightRules = PerlHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-perl.js
JavaScript
asf20
15,050
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/monokai', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-monokai"; exports.cssText = "\ .ace-monokai .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-monokai .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-monokai .ace_gutter {\ background: #292a24;\ color: #f1f1f1;\ }\ \ .ace-monokai .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-monokai .ace_scroller {\ background-color: #272822;\ }\ \ .ace-monokai .ace_text-layer {\ cursor: text;\ color: #F8F8F2;\ }\ \ .ace-monokai .ace_cursor {\ border-left: 2px solid #F8F8F0;\ }\ \ .ace-monokai .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #F8F8F0;\ }\ \ .ace-monokai .ace_marker-layer .ace_selection {\ background: #49483E;\ }\ \ .ace-monokai.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #272822;\ border-radius: 2px;\ }\ \ .ace-monokai .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-monokai .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #49483E;\ }\ \ .ace-monokai .ace_marker-layer .ace_active_line {\ background: #49483E;\ }\ .ace-monokai .ace_gutter_active_line {\ background-color: #191916;\ }\ \ .ace-monokai .ace_marker-layer .ace_selected_word {\ border: 1px solid #49483E;\ }\ \ .ace-monokai .ace_invisible {\ color: #49483E;\ }\ \ .ace-monokai .ace_keyword, .ace-monokai .ace_meta {\ color:#F92672;\ }\ \ .ace-monokai .ace_constant.ace_language {\ color:#AE81FF;\ }\ \ .ace-monokai .ace_constant.ace_numeric {\ color:#AE81FF;\ }\ \ .ace-monokai .ace_constant.ace_other {\ color:#AE81FF;\ }\ \ .ace-monokai .ace_invalid {\ color:#F8F8F0;\ background-color:#F92672;\ }\ \ .ace-monokai .ace_invalid.ace_deprecated {\ color:#F8F8F0;\ background-color:#AE81FF;\ }\ \ .ace-monokai .ace_support.ace_constant {\ color:#66D9EF;\ }\ \ .ace-monokai .ace_fold {\ background-color: #A6E22E;\ border-color: #F8F8F2;\ }\ \ .ace-monokai .ace_support.ace_function {\ color:#66D9EF;\ }\ \ .ace-monokai .ace_storage {\ color:#F92672;\ }\ \ .ace-monokai .ace_storage.ace_type, .ace-monokai .ace_support.ace_type{\ font-style:italic;\ color:#66D9EF;\ }\ \ .ace-monokai .ace_variable {\ color:#A6E22E;\ }\ \ .ace-monokai .ace_variable.ace_parameter {\ font-style:italic;\ color:#FD971F;\ }\ \ .ace-monokai .ace_string {\ color:#E6DB74;\ }\ \ .ace-monokai .ace_comment {\ color:#75715E;\ }\ \ .ace-monokai .ace_entity.ace_other.ace_attribute-name {\ color:#A6E22E;\ }\ \ .ace-monokai .ace_entity.ace_name.ace_function {\ color:#A6E22E;\ }\ \ .ace-monokai .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-monokai.js
JavaScript
asf20
4,624
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Sergi Mansilla <sergi AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/ocaml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/ocaml_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var OcamlHighlightRules = require("./ocaml_highlight_rules").OcamlHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new OcamlHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); var indenter = /(?:[({[=:]|[-=]>|\b(?:else|try|with))\s*$/; (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var i, line; var outdent = true; var re = /^\s*\(\*(.*)\*\)/; for (i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } var range = new Range(0, 0, 0, 0); for (i=startRow; i<= endRow; i++) { line = doc.getLine(i); range.start.row = i; range.end.row = i; range.end.column = line.length; doc.replace(range, outdent ? line.match(re)[1] : "(*" + line + "*)"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (!(tokens.length && tokens[tokens.length - 1].type === 'comment') && state === 'start' && indenter.test(line)) indent += tab; return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/ocaml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var OcamlHighlightRules = function() { var keywords = lang.arrayToMap(( "and|as|assert|begin|class|constraint|do|done|downto|else|end|" + "exception|external|for|fun|function|functor|if|in|include|" + "inherit|initializer|lazy|let|match|method|module|mutable|new|" + "object|of|open|or|private|rec|sig|struct|then|to|try|type|val|" + "virtual|when|while|with").split("|") ); var builtinConstants = lang.arrayToMap( ("true|false").split("|") ); var builtinFunctions = lang.arrayToMap(( "abs|abs_big_int|abs_float|abs_num|abstract_tag|accept|access|acos|add|" + "add_available_units|add_big_int|add_buffer|add_channel|add_char|" + "add_initializer|add_int_big_int|add_interfaces|add_num|add_string|" + "add_substitute|add_substring|alarm|allocated_bytes|allow_only|" + "allow_unsafe_modules|always|append|appname_get|appname_set|" + "approx_num_exp|approx_num_fix|arg|argv|arith_status|array|" + "array1_of_genarray|array2_of_genarray|array3_of_genarray|asin|asr|" + "assoc|assq|at_exit|atan|atan2|auto_synchronize|background|basename|" + "beginning_of_input|big_int_of_int|big_int_of_num|big_int_of_string|bind|" + "bind_class|bind_tag|bits|bits_of_float|black|blit|blit_image|blue|bool|" + "bool_of_string|bounded_full_split|bounded_split|bounded_split_delim|" + "bprintf|break|broadcast|bscanf|button_down|c_layout|capitalize|cardinal|" + "cardinal|catch|catch_break|ceil|ceiling_num|channel|char|char_of_int|" + "chdir|check|check_suffix|chmod|choose|chop_extension|chop_suffix|chown|" + "chown|chr|chroot|classify_float|clear|clear_available_units|" + "clear_close_on_exec|clear_graph|clear_nonblock|clear_parser|" + "close|close|closeTk|close_box|close_graph|close_in|close_in_noerr|" + "close_out|close_out_noerr|close_process|close_process|" + "close_process_full|close_process_in|close_process_out|close_subwindow|" + "close_tag|close_tbox|closedir|closedir|closure_tag|code|combine|" + "combine|combine|command|compact|compare|compare_big_int|compare_num|" + "complex32|complex64|concat|conj|connect|contains|contains_from|contents|" + "copy|cos|cosh|count|count|counters|create|create_alarm|create_image|" + "create_matrix|create_matrix|create_matrix|create_object|" + "create_object_and_run_initializers|create_object_opt|create_process|" + "create_process|create_process_env|create_process_env|create_table|" + "current|current_dir_name|current_point|current_x|current_y|curveto|" + "custom_tag|cyan|data_size|decr|decr_num|default_available_units|delay|" + "delete_alarm|descr_of_in_channel|descr_of_out_channel|destroy|diff|dim|" + "dim1|dim2|dim3|dims|dirname|display_mode|div|div_big_int|div_num|" + "double_array_tag|double_tag|draw_arc|draw_char|draw_circle|draw_ellipse|" + "draw_image|draw_poly|draw_poly_line|draw_rect|draw_segments|draw_string|" + "dummy_pos|dummy_table|dump_image|dup|dup2|elements|empty|end_of_input|" + "environment|eprintf|epsilon_float|eq_big_int|eq_num|equal|err_formatter|" + "error_message|escaped|establish_server|executable_name|execv|execve|execvp|" + "execvpe|exists|exists2|exit|exp|failwith|fast_sort|fchmod|fchown|field|" + "file|file_exists|fill|fill_arc|fill_circle|fill_ellipse|fill_poly|fill_rect|" + "filter|final_tag|finalise|find|find_all|first_chars|firstkey|flatten|" + "float|float32|float64|float_of_big_int|float_of_bits|float_of_int|" + "float_of_num|float_of_string|floor|floor_num|flush|flush_all|flush_input|" + "flush_str_formatter|fold|fold_left|fold_left2|fold_right|fold_right2|" + "for_all|for_all2|force|force_newline|force_val|foreground|fork|" + "format_of_string|formatter_of_buffer|formatter_of_out_channel|" + "fortran_layout|forward_tag|fprintf|frexp|from|from_channel|from_file|" + "from_file_bin|from_function|from_string|fscanf|fst|fstat|ftruncate|" + "full_init|full_major|full_split|gcd_big_int|ge_big_int|ge_num|" + "genarray_of_array1|genarray_of_array2|genarray_of_array3|get|" + "get_all_formatter_output_functions|get_approx_printing|get_copy|" + "get_ellipsis_text|get_error_when_null_denominator|get_floating_precision|" + "get_formatter_output_functions|get_formatter_tag_functions|get_image|" + "get_margin|get_mark_tags|get_max_boxes|get_max_indent|get_method|" + "get_method_label|get_normalize_ratio|get_normalize_ratio_when_printing|" + "get_print_tags|get_state|get_variable|getcwd|getegid|getegid|getenv|" + "getenv|getenv|geteuid|geteuid|getgid|getgid|getgrgid|getgrgid|getgrnam|" + "getgrnam|getgroups|gethostbyaddr|gethostbyname|gethostname|getitimer|" + "getlogin|getpeername|getpid|getppid|getprotobyname|getprotobynumber|" + "getpwnam|getpwuid|getservbyname|getservbyport|getsockname|getsockopt|" + "getsockopt_float|getsockopt_int|getsockopt_optint|gettimeofday|getuid|" + "global_replace|global_substitute|gmtime|green|grid|group_beginning|" + "group_end|gt_big_int|gt_num|guard|handle_unix_error|hash|hash_param|" + "hd|header_size|i|id|ignore|in_channel_length|in_channel_of_descr|incr|" + "incr_num|index|index_from|inet_addr_any|inet_addr_of_string|infinity|" + "infix_tag|init|init_class|input|input_binary_int|input_byte|input_char|" + "input_line|input_value|int|int16_signed|int16_unsigned|int32|int64|" + "int8_signed|int8_unsigned|int_of_big_int|int_of_char|int_of_float|" + "int_of_num|int_of_string|integer_num|inter|interactive|inv|invalid_arg|" + "is_block|is_empty|is_implicit|is_int|is_int_big_int|is_integer_num|" + "is_relative|iter|iter2|iteri|join|junk|key_pressed|kill|kind|kprintf|" + "kscanf|land|last_chars|layout|lazy_from_fun|lazy_from_val|lazy_is_val|" + "lazy_tag|ldexp|le_big_int|le_num|length|lexeme|lexeme_char|lexeme_end|" + "lexeme_end_p|lexeme_start|lexeme_start_p|lineto|link|list|listen|lnot|" + "loadfile|loadfile_private|localtime|lock|lockf|log|log10|logand|lognot|" + "logor|logxor|lor|lower_window|lowercase|lseek|lsl|lsr|lstat|lt_big_int|" + "lt_num|lxor|magenta|magic|mainLoop|major|major_slice|make|make_formatter|" + "make_image|make_lexer|make_matrix|make_self_init|map|map2|map_file|mapi|" + "marshal|match_beginning|match_end|matched_group|matched_string|max|" + "max_array_length|max_big_int|max_elt|max_float|max_int|max_num|" + "max_string_length|mem|mem_assoc|mem_assq|memq|merge|min|min_big_int|" + "min_elt|min_float|min_int|min_num|minor|minus_big_int|minus_num|" + "minus_one|mkdir|mkfifo|mktime|mod|mod_big_int|mod_float|mod_num|modf|" + "mouse_pos|moveto|mul|mult_big_int|mult_int_big_int|mult_num|nan|narrow|" + "nat_of_num|nativeint|neg|neg_infinity|new_block|new_channel|new_method|" + "new_variable|next|nextkey|nice|nice|no_scan_tag|norm|norm2|not|npeek|" + "nth|nth_dim|num_digits_big_int|num_dims|num_of_big_int|num_of_int|" + "num_of_nat|num_of_ratio|num_of_string|O|obj|object_tag|ocaml_version|" + "of_array|of_channel|of_float|of_int|of_int32|of_list|of_nativeint|" + "of_string|one|openTk|open_box|open_connection|open_graph|open_hbox|" + "open_hovbox|open_hvbox|open_in|open_in_bin|open_in_gen|open_out|" + "open_out_bin|open_out_gen|open_process|open_process_full|open_process_in|" + "open_process_out|open_subwindow|open_tag|open_tbox|open_temp_file|" + "open_vbox|opendbm|opendir|openfile|or|os_type|out_channel_length|" + "out_channel_of_descr|output|output_binary_int|output_buffer|output_byte|" + "output_char|output_string|output_value|over_max_boxes|pack|params|" + "parent_dir_name|parse|parse_argv|partition|pause|peek|pipe|pixels|" + "place|plot|plots|point_color|polar|poll|pop|pos_in|pos_out|pow|" + "power_big_int_positive_big_int|power_big_int_positive_int|" + "power_int_positive_big_int|power_int_positive_int|power_num|" + "pp_close_box|pp_close_tag|pp_close_tbox|pp_force_newline|" + "pp_get_all_formatter_output_functions|pp_get_ellipsis_text|" + "pp_get_formatter_output_functions|pp_get_formatter_tag_functions|" + "pp_get_margin|pp_get_mark_tags|pp_get_max_boxes|pp_get_max_indent|" + "pp_get_print_tags|pp_open_box|pp_open_hbox|pp_open_hovbox|pp_open_hvbox|" + "pp_open_tag|pp_open_tbox|pp_open_vbox|pp_over_max_boxes|pp_print_as|" + "pp_print_bool|pp_print_break|pp_print_char|pp_print_cut|pp_print_float|" + "pp_print_flush|pp_print_if_newline|pp_print_int|pp_print_newline|" + "pp_print_space|pp_print_string|pp_print_tab|pp_print_tbreak|" + "pp_set_all_formatter_output_functions|pp_set_ellipsis_text|" + "pp_set_formatter_out_channel|pp_set_formatter_output_functions|" + "pp_set_formatter_tag_functions|pp_set_margin|pp_set_mark_tags|" + "pp_set_max_boxes|pp_set_max_indent|pp_set_print_tags|pp_set_tab|" + "pp_set_tags|pred|pred_big_int|pred_num|prerr_char|prerr_endline|" + "prerr_float|prerr_int|prerr_newline|prerr_string|print|print_as|" + "print_bool|print_break|print_char|print_cut|print_endline|print_float|" + "print_flush|print_if_newline|print_int|print_newline|print_space|" + "print_stat|print_string|print_tab|print_tbreak|printf|prohibit|" + "public_method_label|push|putenv|quo_num|quomod_big_int|quote|raise|" + "raise_window|ratio_of_num|rcontains_from|read|read_float|read_int|" + "read_key|read_line|readdir|readdir|readlink|really_input|receive|recv|" + "recvfrom|red|ref|regexp|regexp_case_fold|regexp_string|" + "regexp_string_case_fold|register|register_exception|rem|remember_mode|" + "remove|remove_assoc|remove_assq|rename|replace|replace_first|" + "replace_matched|repr|reset|reshape|reshape_1|reshape_2|reshape_3|rev|" + "rev_append|rev_map|rev_map2|rewinddir|rgb|rhs_end|rhs_end_pos|rhs_start|" + "rhs_start_pos|rindex|rindex_from|rlineto|rmdir|rmoveto|round_num|" + "run_initializers|run_initializers_opt|scanf|search_backward|" + "search_forward|seek_in|seek_out|select|self|self_init|send|sendto|set|" + "set_all_formatter_output_functions|set_approx_printing|" + "set_binary_mode_in|set_binary_mode_out|set_close_on_exec|" + "set_close_on_exec|set_color|set_ellipsis_text|" + "set_error_when_null_denominator|set_field|set_floating_precision|" + "set_font|set_formatter_out_channel|set_formatter_output_functions|" + "set_formatter_tag_functions|set_line_width|set_margin|set_mark_tags|" + "set_max_boxes|set_max_indent|set_method|set_nonblock|set_nonblock|" + "set_normalize_ratio|set_normalize_ratio_when_printing|set_print_tags|" + "set_signal|set_state|set_tab|set_tag|set_tags|set_text_size|" + "set_window_title|setgid|setgid|setitimer|setitimer|setsid|setsid|" + "setsockopt|setsockopt|setsockopt_float|setsockopt_float|setsockopt_int|" + "setsockopt_int|setsockopt_optint|setsockopt_optint|setuid|setuid|" + "shift_left|shift_left|shift_left|shift_right|shift_right|shift_right|" + "shift_right_logical|shift_right_logical|shift_right_logical|show_buckets|" + "shutdown|shutdown|shutdown_connection|shutdown_connection|sigabrt|" + "sigalrm|sigchld|sigcont|sigfpe|sighup|sigill|sigint|sigkill|sign_big_int|" + "sign_num|signal|signal|sigpending|sigpending|sigpipe|sigprocmask|" + "sigprocmask|sigprof|sigquit|sigsegv|sigstop|sigsuspend|sigsuspend|" + "sigterm|sigtstp|sigttin|sigttou|sigusr1|sigusr2|sigvtalrm|sin|singleton|" + "sinh|size|size|size_x|size_y|sleep|sleep|sleep|slice_left|slice_left|" + "slice_left_1|slice_left_2|slice_right|slice_right|slice_right_1|" + "slice_right_2|snd|socket|socket|socket|socketpair|socketpair|sort|sound|" + "split|split_delim|sprintf|sprintf|sqrt|sqrt|sqrt_big_int|square_big_int|" + "square_num|sscanf|stable_sort|stable_sort|stable_sort|stable_sort|stable_sort|" + "stable_sort|stat|stat|stat|stat|stat|stats|stats|std_formatter|stdbuf|" + "stderr|stderr|stderr|stdib|stdin|stdin|stdin|stdout|stdout|stdout|" + "str_formatter|string|string_after|string_before|string_match|" + "string_of_big_int|string_of_bool|string_of_float|string_of_format|" + "string_of_inet_addr|string_of_inet_addr|string_of_int|string_of_num|" + "string_partial_match|string_tag|sub|sub|sub_big_int|sub_left|sub_num|" + "sub_right|subset|subset|substitute_first|substring|succ|succ|" + "succ|succ|succ_big_int|succ_num|symbol_end|symbol_end_pos|symbol_start|" + "symbol_start_pos|symlink|symlink|sync|synchronize|system|system|system|" + "tag|take|tan|tanh|tcdrain|tcdrain|tcflow|tcflow|tcflush|tcflush|" + "tcgetattr|tcgetattr|tcsendbreak|tcsendbreak|tcsetattr|tcsetattr|" + "temp_file|text_size|time|time|time|timed_read|timed_write|times|times|" + "tl|tl|tl|to_buffer|to_channel|to_float|to_hex|to_int|to_int32|to_list|" + "to_list|to_list|to_nativeint|to_string|to_string|to_string|to_string|" + "to_string|top|top|total_size|transfer|transp|truncate|truncate|truncate|" + "truncate|truncate|truncate|try_lock|umask|umask|uncapitalize|uncapitalize|" + "uncapitalize|union|union|unit_big_int|unlink|unlink|unlock|unmarshal|" + "unsafe_blit|unsafe_fill|unsafe_get|unsafe_get|unsafe_set|unsafe_set|" + "update|uppercase|uppercase|uppercase|uppercase|usage|utimes|utimes|wait|" + "wait|wait|wait|wait_next_event|wait_pid|wait_read|wait_signal|" + "wait_timed_read|wait_timed_write|wait_write|waitpid|white|" + "widen|window_id|word_size|wrap|wrap_abort|write|yellow|yield|zero|zero_big_int|" + "Arg|Arith_status|Array|Array1|Array2|Array3|ArrayLabels|Big_int|Bigarray|" + "Buffer|Callback|CamlinternalOO|Char|Complex|Condition|Dbm|Digest|Dynlink|" + "Event|Filename|Format|Gc|Genarray|Genlex|Graphics|GraphicsX11|Hashtbl|" + "Int32|Int64|LargeFile|Lazy|Lexing|List|ListLabels|Make|Map|Marshal|" + "MoreLabels|Mutex|Nativeint|Num|Obj|Oo|Parsing|Pervasives|Printexc|" + "Printf|Queue|Random|Scanf|Scanning|Set|Sort|Stack|State|StdLabels|Str|" + "Stream|String|StringLabels|Sys|Thread|ThreadUnix|Tk|Unix|UnixLabels|Weak" ).split("|")); var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var octInteger = "(?:0[oO]?[0-7]+)"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var binInteger = "(?:0[bB][01]+)"; var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; var exponent = "(?:[eE][+-]?\\d+)"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; this.$rules = { "start" : [ { token : "comment", regex : '\\(\\*.*?\\*\\)\\s*?$' }, { token : "comment", merge : true, regex : '\\(\\*.*', next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single char regex : "'.'" }, { token : "string", // " string merge : true, regex : '"', next : "qstring" }, { token : "constant.numeric", // imaginary regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, 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+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\)", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qstring" : [ { token : "string", regex : '"', next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(OcamlHighlightRules, TextHighlightRules); exports.OcamlHighlightRules = OcamlHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-ocaml.js
JavaScript
asf20
23,775
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/mode/javascript', 'ace/mode/css', 'ace/tokenizer', 'ace/mode/html_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/html'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var Mode = function() { var highlighter = new HtmlHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); this.$behaviour = new XmlBehaviour(); this.$embeds = highlighter.getEmbeds(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { return 0; }; this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("csslint", function(e) { var errors = []; e.data.forEach(function(message) { errors.push({ row: message.line - 1, column: message.col - 1, text: message.message, type: message.type, lint: message }); }); session.setAnnotations(errors); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/html_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var HtmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", merge : true, regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", regex : "<(?=\s*script\\b)", next : "script" }, { token : "meta.tag", regex : "<(?=\s*style\\b)", next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" } ], cdata : [ { token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", merge : true, regex : "\\s+" }, { token : "text", merge : true, regex : ".+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" } ] }; xmlUtil.tag(this.$rules, "tag", "start"); xmlUtil.tag(this.$rules, "style", "css-start"); xmlUtil.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); this.embedRules(CssHighlightRules, "css-", [{ token: "meta.tag", regex: "<\\/(?=style)", next: "tag" }]); }; oop.inherits(HtmlHighlightRules, TextHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/folding/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/mixed', 'ace/mode/folding/xml', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function() { MixedFoldMode.call(this, new XmlFoldMode({ // void elements "area": 1, "base": 1, "br": 1, "col": 1, "command": 1, "embed": 1, "hr": 1, "img": 1, "input": 1, "keygen": 1, "link": 1, "meta": 1, "param": 1, "source": 1, "track": 1, "wbr": 1, // optional tags "li": 1, "dt": 1, "dd": 1, "p": 1, "rt": 1, "rp": 1, "optgroup": 1, "option": 1, "colgroup": 1, "td": 1, "th": 1 }), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); define('ace/mode/folding/mixed', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-html.js
JavaScript
asf20
73,313
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/tomorrow_night_eighties', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-tomorrow-night-eighties"; exports.cssText = "\ .ace-tomorrow-night-eighties .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tomorrow-night-eighties .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tomorrow-night-eighties .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-tomorrow-night-eighties .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tomorrow-night-eighties .ace_scroller {\ background-color: #2D2D2D;\ }\ \ .ace-tomorrow-night-eighties .ace_text-layer {\ cursor: text;\ color: #CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_cursor {\ border-left: 2px solid #CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_selection {\ background: #515151;\ }\ \ .ace-tomorrow-night-eighties.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #2D2D2D;\ border-radius: 2px;\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #6A6A6A;\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_active_line {\ background: #393939;\ }\ \ .ace-tomorrow-night-eighties .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_selected_word {\ border: 1px solid #515151;\ }\ \ .ace-tomorrow-night-eighties .ace_invisible {\ color: #6A6A6A;\ }\ \ .ace-tomorrow-night-eighties .ace_keyword, .ace-tomorrow-night-eighties .ace_meta {\ color:#CC99CC;\ }\ \ .ace-tomorrow-night-eighties .ace_keyword.ace_operator {\ color:#66CCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_constant.ace_language {\ color:#F99157;\ }\ \ .ace-tomorrow-night-eighties .ace_constant.ace_numeric {\ color:#F99157;\ }\ \ .ace-tomorrow-night-eighties .ace_constant.ace_other {\ color:#CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_invalid {\ color:#CDCDCD;\ background-color:#F2777A;\ }\ \ .ace-tomorrow-night-eighties .ace_invalid.ace_deprecated {\ color:#CDCDCD;\ background-color:#CC99CC;\ }\ \ .ace-tomorrow-night-eighties .ace_support.ace_constant {\ color:#F99157;\ }\ \ .ace-tomorrow-night-eighties .ace_fold {\ background-color: #6699CC;\ border-color: #CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_support.ace_function {\ color:#6699CC;\ }\ \ .ace-tomorrow-night-eighties .ace_storage {\ color:#CC99CC;\ }\ \ .ace-tomorrow-night-eighties .ace_storage.ace_type, .ace-tomorrow-night-eighties .ace_support.ace_type{\ color:#CC99CC;\ }\ \ .ace-tomorrow-night-eighties .ace_variable {\ color:#6699CC;\ }\ \ .ace-tomorrow-night-eighties .ace_variable.ace_parameter {\ color:#F99157;\ }\ \ .ace-tomorrow-night-eighties .ace_string {\ color:#99CC99;\ }\ \ .ace-tomorrow-night-eighties .ace_comment {\ color:#999999;\ }\ \ .ace-tomorrow-night-eighties .ace_variable {\ color:#F2777A;\ }\ \ .ace-tomorrow-night-eighties .ace_meta.ace_tag {\ color:#F2777A;\ }\ \ .ace-tomorrow-night-eighties .ace_entity.ace_other.ace_attribute-name {\ color:#F2777A;\ }\ \ .ace-tomorrow-night-eighties .ace_entity.ace_name.ace_function {\ color:#6699CC;\ }\ \ .ace-tomorrow-night-eighties .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-tomorrow-night-eighties .ace_markup.ace_heading {\ color:#99CC99;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-tomorrow_night_eighties.js
JavaScript
asf20
5,494
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/merbivore', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-merbivore"; exports.cssText = "\ .ace-merbivore .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-merbivore .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-merbivore .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-merbivore .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-merbivore .ace_scroller {\ background-color: #161616;\ }\ \ .ace-merbivore .ace_text-layer {\ cursor: text;\ color: #E6E1DC;\ }\ \ .ace-merbivore .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-merbivore .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-merbivore .ace_marker-layer .ace_selection {\ background: #454545;\ }\ \ .ace-merbivore.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #161616;\ border-radius: 2px;\ }\ \ .ace-merbivore .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-merbivore .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #404040;\ }\ \ .ace-merbivore .ace_marker-layer .ace_active_line {\ background: #333435;\ }\ \ .ace-merbivore .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-merbivore .ace_marker-layer .ace_selected_word {\ border: 1px solid #454545;\ }\ \ .ace-merbivore .ace_invisible {\ color: #404040;\ }\ \ .ace-merbivore .ace_keyword, .ace-merbivore .ace_meta {\ color:#FC6F09;\ }\ \ .ace-merbivore .ace_constant, .ace-merbivore .ace_constant.ace_other {\ color:#1EDAFB;\ }\ \ .ace-merbivore .ace_constant.ace_character, {\ color:#1EDAFB;\ }\ \ .ace-merbivore .ace_constant.ace_character.ace_escape, {\ color:#1EDAFB;\ }\ \ .ace-merbivore .ace_constant.ace_language {\ color:#FDC251;\ }\ \ .ace-merbivore .ace_constant.ace_library {\ color:#8DFF0A;\ }\ \ .ace-merbivore .ace_constant.ace_numeric {\ color:#58C554;\ }\ \ .ace-merbivore .ace_invalid {\ color:#FFFFFF;\ background-color:#990000;\ }\ \ .ace-merbivore .ace_support.ace_constant {\ color:#8DFF0A;\ }\ \ .ace-merbivore .ace_fold {\ background-color: #FC6F09;\ border-color: #E6E1DC;\ }\ \ .ace-merbivore .ace_support.ace_function {\ color:#FC6F09;\ }\ \ .ace-merbivore .ace_storage {\ color:#FC6F09;\ }\ \ .ace-merbivore .ace_string {\ color:#8DFF0A;\ }\ \ .ace-merbivore .ace_comment {\ font-style:italic;\ color:#AD2EA4;\ }\ \ .ace-merbivore .ace_meta.ace_tag {\ color:#FC6F09;\ }\ \ .ace-merbivore .ace_entity.ace_other.ace_attribute-name {\ color:#FFFF89;\ }\ \ .ace-merbivore .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-merbivore.js
JavaScript
asf20
4,593
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/idle_fingers', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-idle-fingers"; exports.cssText = "\ .ace-idle-fingers .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-idle-fingers .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-idle-fingers .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-idle-fingers .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-idle-fingers .ace_scroller {\ background-color: #323232;\ }\ \ .ace-idle-fingers .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-idle-fingers .ace_cursor {\ border-left: 2px solid #91FF00;\ }\ \ .ace-idle-fingers .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #91FF00;\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_selection {\ background: rgba(90, 100, 126, 0.88);\ }\ \ .ace-idle-fingers.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #323232;\ border-radius: 2px;\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #404040;\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_active_line {\ background: #353637;\ }\ \ .ace-idle-fingers .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(90, 100, 126, 0.88);\ }\ \ .ace-idle-fingers .ace_invisible {\ color: #404040;\ }\ \ .ace-idle-fingers .ace_keyword, .ace-idle-fingers .ace_meta {\ color:#CC7833;\ }\ \ .ace-idle-fingers .ace_constant, .ace-idle-fingers .ace_constant.ace_other {\ color:#6C99BB;\ }\ \ .ace-idle-fingers .ace_constant.ace_character, {\ color:#6C99BB;\ }\ \ .ace-idle-fingers .ace_constant.ace_character.ace_escape, {\ color:#6C99BB;\ }\ \ .ace-idle-fingers .ace_invalid {\ color:#FFFFFF;\ background-color:#FF0000;\ }\ \ .ace-idle-fingers .ace_support.ace_constant {\ color:#6C99BB;\ }\ \ .ace-idle-fingers .ace_fold {\ background-color: #CC7833;\ border-color: #FFFFFF;\ }\ \ .ace-idle-fingers .ace_support.ace_function {\ color:#B83426;\ }\ \ .ace-idle-fingers .ace_variable.ace_parameter {\ font-style:italic;\ }\ \ .ace-idle-fingers .ace_string {\ color:#A5C261;\ }\ \ .ace-idle-fingers .ace_string.ace_regexp {\ color:#CCCC33;\ }\ \ .ace-idle-fingers .ace_comment {\ font-style:italic;\ color:#BC9458;\ }\ \ .ace-idle-fingers .ace_meta.ace_tag {\ color:#FFE5BB;\ }\ \ .ace-idle-fingers .ace_entity.ace_name {\ color:#FFC66D;\ }\ \ .ace-idle-fingers .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-idle-fingers .ace_collab.ace_user1 {\ color:#323232;\ background-color:#FFF980;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-idle_fingers.js
JavaScript
asf20
4,686
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Skywriter. * * The Initial Developer of the Original Code is * Mozilla. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Julian Viereck (julian.viereck@gmail.com) * Harutyun Amirjanyan (harutyun@c9.io) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/keyboard/emacs', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/keyboard/hash_handler', 'ace/lib/keys'], function(require, exports, module) { var dom = require("../lib/dom"); var screenToTextBlockCoordinates = function(pageX, pageY) { var canvasPos = this.scroller.getBoundingClientRect(); var col = Math.floor( (pageX + this.scrollLeft - canvasPos.left - this.$padding - dom.getPageScrollLeft()) / this.characterWidth ); var row = Math.floor( (pageY + this.scrollTop - canvasPos.top - dom.getPageScrollTop()) / this.lineHeight ); return this.session.screenToDocumentPosition(row, col); }; var HashHandler = require("./hash_handler").HashHandler; exports.handler = new HashHandler(); var initialized = false; exports.handler.attach = function(editor) { if (!initialized) { initialized = true; dom.importCssString('\ .emacs-mode .ace_cursor{\ border: 2px rgba(50,250,50,0.8) solid!important;\ -moz-box-sizing: border-box!important;\ box-sizing: border-box!important;\ background-color: rgba(0,250,0,0.9);\ opacity: 0.5;\ }\ .emacs-mode .ace_cursor.ace_hidden{\ opacity: 1;\ background-color: transparent;\ }\ .emacs-mode .ace_cursor.ace_overwrite {\ 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' ); } editor.renderer.screenToTextCoordinates = screenToTextBlockCoordinates; editor.setStyle("emacs-mode"); }; exports.handler.detach = function(editor) { delete editor.renderer.screenToTextCoordinates; editor.unsetStyle("emacs-mode"); }; var keys = require("../lib/keys").KEY_MODS; var eMods = { C: "ctrl", S: "shift", M: "alt" }; ["S-C-M", "S-C", "S-M", "C-M", "S", "C", "M"].forEach(function(c) { var hashId = 0; c.split("-").forEach(function(c){ hashId = hashId | keys[eMods[c]]; }); eMods[hashId] = c.toLowerCase() + "-"; }); exports.handler.bindKey = function(key, command) { if (!key) return; var ckb = this.commmandKeyBinding; key.split("|").forEach(function(keyPart) { keyPart = keyPart.toLowerCase(); ckb[keyPart] = command; keyPart = keyPart.split(" ")[0]; if (!ckb[keyPart]) ckb[keyPart] = "null"; }, this); }; exports.handler.handleKeyboard = function(data, hashId, key, keyCode) { if (hashId == -1) { if (data.count) { var str = Array(data.count + 1).join(key); data.count = null; return {command: "insertstring", args: str}; } } if (key == "\x00") return; var modifier = eMods[hashId]; if (modifier == "c-" || data.universalArgument) { var count = parseInt(key[key.length - 1]); if (count) { data.count = count; return {command: "null"}; } } data.universalArgument = false; if (modifier) key = modifier + key; if (data.keyChain) key = data.keyChain += " " + key; var command = this.commmandKeyBinding[key]; data.keyChain = command == "null" ? key : ""; if (!command) return; if (command == "null") return {command: "null"}; if (command == "universalArgument") { data.universalArgument = true; return {command: "null"}; } if (typeof command != "string") { var args = command.args; command = command.command; } if (typeof command == "string") { command = this.commands[command] || data.editor.commands.commands[command]; } if (!command.readonly && !command.isYank) data.lastCommand = null; if (data.count) { var count = data.count; data.count = 0; return { args: args, command: { exec: function(editor, args) { for (var i = 0; i < count; i++) command.exec(editor, args); } } }; } return {command: command, args: args}; }; exports.emacsKeys = { // movement "Up|C-p" : "golineup", "Down|C-n" : "golinedown", "Left|C-b" : "gotoleft", "Right|C-f" : "gotoright", "C-Left|M-b" : "gotowordleft", "C-Right|M-f" : "gotowordright", "Home|C-a" : "gotolinestart", "End|C-e" : "gotolineend", "C-Home|S-M-,": "gotostart", "C-End|S-M-." : "gotoend", // selection "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|M-s" : "centerselection", "M-g": "gotoline", "C-x C-p": "selectall", // todo fix these "C-Down": "gotopagedown", "C-Up": "gotopageup", "PageDown|C-v": "gotopagedown", "PageUp|M-v": "gotopageup", "S-C-Down": "selectpagedown", "S-C-Up": "selectpageup", "C-s": "findnext", "C-r": "findprevious", "M-C-s": "findnext", "M-C-r": "findprevious", "S-M-5": "replace", // basic editing "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": "killRegion", "M-w": "killRingSave", "C-Space": "setMark", "C-x C-x": "exchangePointAndMark", "C-t": "transposeletters", "M-u": "touppercase", "M-l": "tolowercase", "M-/": "autocomplete", "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? // vertical editing "C-x r": "selectRectangularRegion" // todo // "M-x" "C-x C-t" "M-t" "M-c" "F11" "C-M- "M-q" }; exports.handler.bindKeys(exports.emacsKeys); exports.handler.addCommands({ selectRectangularRegion: function(editor) { editor.multiSelect.toggleBlockSelection(); }, setMark: function() { }, exchangePointAndMark: { exec: function(editor) { var range = editor.selection.getRange(); editor.selection.setSelectionRange(range, !editor.selection.isBackwards()); }, readonly: 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.selection.selectLine(); var range = editor.getSelectionRange(); var text = editor.session.getTextRange(range); 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.onPaste(exports.killRing.rotate()); editor.keyBinding.$data.lastCommand = "yank"; }, killRegion: function(editor) { exports.killRing.add(editor.getCopyText()); editor.cut(); }, killRingSave: function(editor) { exports.killRing.add(editor.getCopyText()); } }); 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(); }, get: function() { return this.$data[this.$data.length - 1] || ""; }, pop: function() { if (this.$data.length > 1) this.$data.pop(); return this.get(); }, rotate: function() { this.$data.unshift(this.$data.pop()); return this.get(); } }; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/keybinding-emacs.js
JavaScript
asf20
10,882
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/scss', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/scss_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ScssHighlightRules = require("./scss_highlight_rules").ScssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new ScssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/scss_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ScssHighlightRules = function() { var properties = lang.arrayToMap( (function () { var browserPrefix = ("-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-").split("|"); var prefixProperties = ("appearance|background-clip|background-inline-policy|background-origin|" + "background-size|binding|border-bottom-colors|border-left-colors|" + "border-right-colors|border-top-colors|border-end|border-end-color|" + "border-end-style|border-end-width|border-image|border-start|" + "border-start-color|border-start-style|border-start-width|box-align|" + "box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|" + "box-pack|box-sizing|column-count|column-gap|column-width|column-rule|" + "column-rule-width|column-rule-style|column-rule-color|float-edge|" + "font-feature-settings|font-language-override|force-broken-image-icon|" + "image-region|margin-end|margin-start|opacity|outline|outline-color|" + "outline-offset|outline-radius|outline-radius-bottomleft|" + "outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|" + "outline-style|outline-width|padding-end|padding-start|stack-sizing|" + "tab-size|text-blink|text-decoration-color|text-decoration-line|" + "text-decoration-style|transform|transform-origin|transition|" + "transition-delay|transition-duration|transition-property|" + "transition-timing-function|user-focus|user-input|user-modify|user-select|" + "window-shadow|border-radius").split("|"); var properties = ("azimuth|background-attachment|background-color|background-image|" + "background-position|background-repeat|background|border-bottom-color|" + "border-bottom-style|border-bottom-width|border-bottom|border-collapse|" + "border-color|border-left-color|border-left-style|border-left-width|" + "border-left|border-right-color|border-right-style|border-right-width|" + "border-right|border-spacing|border-style|border-top-color|" + "border-top-style|border-top-width|border-top|border-width|border|" + "bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" + "counter-reset|cue-after|cue-before|cue|cursor|direction|display|" + "elevation|empty-cells|float|font-family|font-size-adjust|font-size|" + "font-stretch|font-style|font-variant|font-weight|font|height|left|" + "letter-spacing|line-height|list-style-image|list-style-position|" + "list-style-type|list-style|margin-bottom|margin-left|margin-right|" + "margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" + "min-width|opacity|orphans|outline-color|" + "outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" + "padding-left|padding-right|padding-top|padding|page-break-after|" + "page-break-before|page-break-inside|page|pause-after|pause-before|" + "pause|pitch-range|pitch|play-during|position|quotes|richness|right|" + "size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" + "stress|table-layout|text-align|text-decoration|text-indent|" + "text-shadow|text-transform|top|unicode-bidi|vertical-align|" + "visibility|voice-family|volume|white-space|widows|width|word-spacing|" + "z-index").split("|"); //The return array var ret = []; //All prefixProperties will get the browserPrefix in //the begning by join the prefixProperties array with the value of browserPrefix for (var i=0, ln=browserPrefix.length; i<ln; i++) { Array.prototype.push.apply( ret, (( browserPrefix[i] + prefixProperties.join("|" + browserPrefix[i]) ).split("|")) ); } //Add also prefixProperties and properties without any browser prefix Array.prototype.push.apply(ret, prefixProperties); Array.prototype.push.apply(ret, properties); return ret; })() ); var functions = lang.arrayToMap( ("hsl|hsla|rgb|rgba|url|attr|counter|counters|abs|adjust_color|adjust_hue|" + "alpha|join|blue|ceil|change_color|comparable|complement|darken|desaturate|" + "floor|grayscale|green|hue|if|invert|join|length|lighten|lightness|mix|" + "nth|opacify|opacity|percentage|quote|red|round|saturate|saturation|" + "scale_color|transparentize|type_of|unit|unitless|unqoute").split("|") ); var constants = lang.arrayToMap( ("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" + "block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" + "char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" + "decimal-leading-zero|decimal|default|disabled|disc|" + "distribute-all-lines|distribute-letter|distribute-space|" + "distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" + "hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|" + "ideograph-alpha|ideograph-numeric|ideograph-parenthesis|" + "ideograph-space|inactive|inherit|inline-block|inline|inset|inside|" + "inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|" + "keep-all|left|lighter|line-edge|line-through|line|list-item|loose|" + "lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|" + "medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|" + "nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|" + "overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|" + "ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|" + "solid|square|static|strict|super|sw-resize|table-footer-group|" + "table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|" + "transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|" + "vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|" + "zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var keywords = lang.arrayToMap( ("@mixin|@extend|@include|@import|@media|@debug|@warn|@if|@for|@each|@while|@else|@font-face|@-webkit-keyframes|if|and|!default|module|def|end|declare").split("|") ) var tags = lang.arrayToMap( ("a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdo|" + "big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" + "command|datalist|dd|del|details|dfn|dir|div|dl|dt|em|embed|fieldset|" + "figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|" + "header|hgroup|hr|html|i|iframe|img|input|ins|keygen|kbd|label|legend|li|" + "link|map|mark|menu|meta|meter|nav|noframes|noscript|object|ol|optgroup|" + "option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|" + "small|source|span|strike|strong|style|sub|summary|sup|table|tbody|td|" + "textarea|tfoot|th|thead|time|title|tr|tt|u|ul|var|video|wbr|xmp").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : "constant.numeric", regex : numRe }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) return "support.type"; if (keywords.hasOwnProperty(value)) return "keyword"; else if (constants.hasOwnProperty(value)) return "constant.language"; else if (functions.hasOwnProperty(value)) return "support.function"; else if (colors.hasOwnProperty(value.toLowerCase())) return "support.constant.color"; else if (tags.hasOwnProperty(value.toLowerCase())) return "variable.language"; else return "text"; }, regex : "\\-?[@a-z_][@a-z0-9_\\-]*" }, { token : "variable", regex : "[a-z_\\-$][a-z0-9_\\-$]*\\b" }, { token: "variable.language", regex: "#[a-z0-9-_]+" }, { token: "variable.language", regex: "\\.[a-z0-9-_]+" }, { token: "variable.language", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { token : "keyword.operator", regex : "<|>|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(ScssHighlightRules, TextHighlightRules); exports.ScssHighlightRules = ScssHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-scss.js
JavaScript
asf20
20,972
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/chrome', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.cssClass = "ace-chrome"; exports.cssText = ".ace-chrome .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-chrome .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-chrome .ace_gutter {\ background: #e8e8e8;\ color: #333;\ overflow : hidden;\ }\ \ .ace-chrome .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-chrome .ace_text-layer {\ cursor: text;\ }\ \ .ace-chrome .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-chrome .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid black;\ }\ \ .ace-chrome .ace_line .ace_invisible {\ color: rgb(191, 191, 191);\ }\ \ .ace-chrome .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-chrome .ace_line .ace_constant.ace_language {\ color: rgb(88, 92, 246);\ }\ \ .ace-chrome .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-chrome .ace_line .ace_invalid {\ background-color: rgb(153, 0, 0);\ color: white;\ }\ \ .ace-chrome .ace_line .ace_fold {\ }\ \ .ace-chrome .ace_line .ace_support.ace_function {\ color: rgb(60, 76, 114);\ }\ \ .ace-chrome .ace_line .ace_support.ace_constant {\ color: rgb(6, 150, 14);\ }\ \ .ace-chrome .ace_line .ace_support.ace_type,\ .ace-chrome .ace_line .ace_support.ace_class {\ color: rgb(109, 121, 222);\ }\ \ .ace-chrome .ace_variable.ace_parameter {\ font-style:italic;\ color:#FD971F;\ }\ .ace-chrome .ace_line .ace_keyword.ace_operator {\ color: rgb(104, 118, 135);\ }\ \ .ace-chrome .ace_line .ace_comment {\ color: #236e24;\ }\ \ .ace-chrome .ace_line .ace_comment.ace_doc {\ color: #236e24;\ }\ \ .ace-chrome .ace_line .ace_comment.ace_doc.ace_tag {\ color: #236e24;\ }\ \ .ace-chrome .ace_line .ace_constant.ace_numeric {\ color: rgb(0, 0, 205);\ }\ \ .ace-chrome .ace_line .ace_variable {\ color: rgb(49, 132, 149);\ }\ \ .ace-chrome .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-chrome .ace_entity.ace_name.ace_function {\ color: #0000A2;\ }\ \ .ace-chrome .ace_markup.ace_markupine {\ text-decoration:underline;\ }\ \ .ace-chrome .ace_markup.ace_heading {\ color: rgb(12, 7, 255);\ }\ \ .ace-chrome .ace_markup.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_marker-layer .ace_selected_word {\ background: rgb(250, 250, 255);\ border: 1px solid rgb(200, 200, 250);\ }\ \ .ace-chrome .ace_storage,\ .ace-chrome .ace_line .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_line .ace_string,\ .ace-chrome .ace_entity.ace_other.ace_attribute-name{\ color: #994409;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-chrome.js
JavaScript
asf20
5,094
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/liquid', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/liquid_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var LiquidHighlightRules = require("./liquid_highlight_rules").LiquidHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new LiquidHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var outentedRows = []; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/liquid_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/lib/lang', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var lang = require("../lib/lang"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LiquidHighlightRules = function() { // see: https://developer.mozilla.org/en/Liquid/Reference/Global_Objects var functions = lang.arrayToMap( // Standard Filters ("date|capitalize|downcase|upcase|first|last|join|sort|map|size|escape|" + "escape_once|strip_html|strip_newlines|newline_to_br|replace|replace_first|" + "truncate|truncatewords|prepend|append|minus|plus|times|divided_by|split" ).split("|") ); var keywords = lang.arrayToMap( // Standard Tags ("capture|endcapture|case|endcase|when|comment|endcomment|" + "cycle|for|endfor|in|reversed|if|endif|else|elsif|include|endinclude|unless|endunless|" + // Commonly used tags "style|text|image|widget|plugin|marker|endmarker|tablerow|endtablerow").split("|") ); var builtinVariables = lang.arrayToMap( ['forloop'] // ("forloop\\.(length|index|index0|rindex|rindex0|first|last)|limit|offset|range" + // "tablerowloop\\.(length|index|index0|rindex|rindex0|first|last|col|col0|"+ // "col_first|col_last)").split("|") ); var definitions = lang.arrayToMap(("assign").split("|")); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "variable", regex : "{%", next : "liquid_start" }, { token : "variable", regex : "{{", next : "liquid_start" }, { token : "meta.tag", merge : true, regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "meta.tag", regex : "<(?=\\s*script\\b)", next : "script" }, { token : "meta.tag", regex : "<(?=\\s*style\\b)", next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "[^<]+" } ], cdata : [ { token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", merge : true, regex : "\\s+" }, { token : "text", merge : true, regex : ".+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" } ] , liquid_start : [{ token: "variable", regex: "}}", next: "start" }, { token: "variable", regex: "%}", next: "start" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (functions.hasOwnProperty(value)) return "support.function"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinVariables.hasOwnProperty(value)) return "variable.language"; else if (definitions.hasOwnProperty(value)) return "keyword.definition"; else return "identifier"; }, 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+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); xmlUtil.tag(this.$rules, "style", "css-start"); xmlUtil.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); this.embedRules(CssHighlightRules, "css-", [{ token: "meta.tag", regex: "<\\/(?=style)", next: "tag" }]); }; oop.inherits(LiquidHighlightRules, TextHighlightRules); exports.LiquidHighlightRules = LiquidHighlightRules; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-liquid.js
JavaScript
asf20
47,556
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Sergi Mansilla <sergi AT c9 DOT io> * Harutyun Amirjanyan <harutyun AT c9 DOT io> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/keyboard/vim', ['require', 'exports', 'module' , 'ace/lib/keys', 'ace/keyboard/vim/commands', 'ace/keyboard/vim/maps/util'], function(require, exports, module) { var keyUtil = require("../lib/keys"); var cmds = require("./vim/commands"); var coreCommands = cmds.coreCommands; var util = require("./vim/maps/util"); var startCommands = { "i": { command: coreCommands.start }, "I": { command: coreCommands.startBeginning }, "a": { command: coreCommands.append }, "A": { command: coreCommands.appendEnd }, "ctrl-f": { command: "gotopagedown" }, "ctrl-b": { command: "gotopageup" }, }; exports.handler = { handleKeyboard: function(data, hashId, key, keyCode, e) { // ignore command keys (shift, ctrl etc.) if (hashId != 0 && (key == "" || key == "\x00")) return null; if (hashId == 1) key = "ctrl-" + key; if (data.state == "start") { if (hashId == -1 || hashId == 1) { if (cmds.inputBuffer.idle && startCommands[key]) return startCommands[key]; return { command: { exec: function(editor) {cmds.inputBuffer.push(editor, key);} } }; } // wait for input else if (key.length == 1 && (hashId == 0 || hashId == 4)) { //no modifier || shift return {command: "null", passEvent: true}; } else if (key == "esc") { return {command: coreCommands.stop}; } } else { if (key == "esc" || key == "ctrl-[") { data.state = "start"; return {command: coreCommands.stop}; } else if (key == "ctrl-w") { return {command: "removewordleft"}; } } }, attach: function(editor) { editor.on("click", exports.onCursorMove); if (util.currentMode !== "insert") cmds.coreCommands.stop.exec(editor); }, detach: function(editor) { editor.removeListener("click", exports.onCursorMove); util.noMode(editor); util.currentMode = "normal"; }, actions: cmds.actions }; exports.onCursorMove = function(e) { cmds.onCursorMove(e.editor, e); exports.onCursorMove.scheduled = false; }; }); define('ace/keyboard/vim/commands', ['require', 'exports', 'module' , 'ace/keyboard/vim/maps/util', 'ace/keyboard/vim/maps/motions', 'ace/keyboard/vim/maps/operators', 'ace/keyboard/vim/maps/aliases', 'ace/keyboard/vim/registers'], function(require, exports, module) { "never use strict"; var util = require("./maps/util"); var motions = require("./maps/motions"); var operators = require("./maps/operators"); var alias = require("./maps/aliases"); var registers = require("./registers"); var NUMBER = 1; var OPERATOR = 2; var MOTION = 3; var ACTION = 4; var HMARGIN = 8; // Minimum amount of line separation between margins; var repeat = function repeat(fn, count, args) { while (0 < count--) fn.apply(this, args); }; var ensureScrollMargin = function(editor) { var renderer = editor.renderer; var pos = renderer.$cursorLayer.getPixelPosition(); var top = pos.top; var margin = HMARGIN * renderer.layerConfig.lineHeight; if (2 * margin > renderer.$size.scrollerHeight) margin = renderer.$size.scrollerHeight / 2; if (renderer.scrollTop > top - margin) { renderer.session.setScrollTop(top - margin); } if (renderer.scrollTop + renderer.$size.scrollerHeight < top + margin + renderer.lineHeight) { renderer.session.setScrollTop(top + margin + renderer.lineHeight - renderer.$size.scrollerHeight); } }; var actions = exports.actions = { "z": { param: true, fn: function(editor, range, count, param) { switch (param) { case "z": editor.alignCursor(null, 0.5); break; case "t": editor.alignCursor(null, 0); break; case "b": editor.alignCursor(null, 1); break; } } }, "r": { param: true, fn: function(editor, range, count, param) { if (param && param.length) { repeat(function() { editor.insert(param); }, count || 1); editor.navigateLeft(); } } }, "R": { fn: function(editor, range, count, param) { util.insertMode(editor); editor.setOverwrite(true); } }, "~": { fn: function(editor, range, count) { repeat(function() { var range = editor.selection.getRange(); if (range.isEmpty()) range.end.column++; var text = editor.session.getTextRange(range); var toggled = text.toUpperCase(); if (toggled == text) editor.navigateRight(); else editor.session.replace(range, toggled); }, count || 1); } }, "*": { fn: function(editor, range, count, param) { editor.selection.selectWord(); editor.findNext(); ensureScrollMargin(editor); var r = editor.selection.getRange(); editor.selection.setSelectionRange(r, true); } }, "#": { fn: function(editor, range, count, param) { editor.selection.selectWord(); editor.findPrevious(); ensureScrollMargin(editor); var r = editor.selection.getRange(); editor.selection.setSelectionRange(r, true); } }, "n": { fn: function(editor, range, count, param) { var options = editor.getLastSearchOptions(); options.backwards = false; editor.selection.moveCursorRight(); editor.selection.clearSelection(); editor.findNext(options); ensureScrollMargin(editor); var r = editor.selection.getRange(); r.end.row = r.start.row; r.end.column = r.start.column; editor.selection.setSelectionRange(r, true); } }, "N": { fn: function(editor, range, count, param) { var options = editor.getLastSearchOptions(); options.backwards = true; editor.findPrevious(options); ensureScrollMargin(editor); var r = editor.selection.getRange(); r.end.row = r.start.row; r.end.column = r.start.column; editor.selection.setSelectionRange(r, true); } }, "v": { fn: function(editor, range, count, param) { editor.selection.selectRight(); util.visualMode(editor, false); }, acceptsMotion: true }, "V": { fn: function(editor, range, count, param) { //editor.selection.selectLine(); //editor.selection.selectLeft(); var row = editor.getCursorPosition().row; editor.selection.clearSelection(); editor.selection.moveCursorTo(row, 0); editor.selection.selectLineEnd(); editor.selection.visualLineStart = row; util.visualMode(editor, true); }, acceptsMotion: true }, "Y": { fn: function(editor, range, count, param) { util.copyLine(editor); } }, "p": { fn: function(editor, range, count, param) { var defaultReg = registers._default; editor.setOverwrite(false); if (defaultReg.isLine) { var pos = editor.getCursorPosition(); var lines = defaultReg.text.split("\n"); editor.session.getDocument().insertLines(pos.row + 1, lines); editor.moveCursorTo(pos.row + 1, 0); } else { editor.navigateRight(); editor.insert(defaultReg.text); editor.navigateLeft(); } editor.setOverwrite(true); editor.selection.clearSelection(); } }, "P": { fn: function(editor, range, count, param) { var defaultReg = registers._default; editor.setOverwrite(false); if (defaultReg.isLine) { var pos = editor.getCursorPosition(); var lines = defaultReg.text.split("\n"); editor.session.getDocument().insertLines(pos.row, lines); editor.moveCursorTo(pos.row, 0); } else { editor.insert(defaultReg.text); } editor.setOverwrite(true); editor.selection.clearSelection(); } }, "J": { fn: function(editor, range, count, param) { var session = editor.session; range = editor.getSelectionRange(); var pos = {row: range.start.row, column: range.start.column}; count = count || range.end.row - range.start.row; var maxRow = Math.min(pos.row + (count || 1), session.getLength() - 1); range.start.column = session.getLine(pos.row).length; range.end.column = session.getLine(maxRow).length; range.end.row = maxRow; var text = ""; for (var i = pos.row; i < maxRow; i++) { var nextLine = session.getLine(i + 1); text += " " + /^\s*(.*)$/.exec(nextLine)[1] || ""; } session.replace(range, text); editor.moveCursorTo(pos.row, pos.column); } }, "u": { fn: function(editor, range, count, param) { count = parseInt(count || 1, 10); for (var i = 0; i < count; i++) { editor.undo(); } editor.selection.clearSelection(); } }, "ctrl-r": { fn: function(editor, range, count, param) { count = parseInt(count || 1, 10); for (var i = 0; i < count; i++) { editor.redo(); } editor.selection.clearSelection(); } }, ":": { fn: function(editor, range, count, param) { // not implemented } }, "/": { fn: function(editor, range, count, param) { // not implemented } }, "?": { fn: function(editor, range, count, param) { // not implemented } }, ".": { fn: function(editor, range, count, param) { util.onInsertReplaySequence = inputBuffer.lastInsertCommands; var previous = inputBuffer.previous; if (previous) // If there is a previous action inputBuffer.exec(editor, previous.action, previous.param); } } }; var inputBuffer = exports.inputBuffer = { accepting: [NUMBER, OPERATOR, MOTION, ACTION], currentCmd: null, //currentMode: 0, currentCount: "", // Types operator: null, motion: null, lastInsertCommands: [], push: function(editor, char, keyId) { this.idle = false; var wObj = this.waitingForParam; if (wObj) { this.exec(editor, wObj, char); } // If input is a number (that doesn't start with 0) else if (!(char === "0" && !this.currentCount.length) && (char.match(/^\d+$/) && this.isAccepting(NUMBER))) { // Assuming that char is always of type String, and not Number this.currentCount += char; this.currentCmd = NUMBER; this.accepting = [NUMBER, OPERATOR, MOTION, ACTION]; } else if (!this.operator && this.isAccepting(OPERATOR) && operators[char]) { this.operator = { char: char, count: this.getCount() }; this.currentCmd = OPERATOR; this.accepting = [NUMBER, MOTION, ACTION]; this.exec(editor, { operator: this.operator }); } else if (motions[char] && this.isAccepting(MOTION)) { this.currentCmd = MOTION; var ctx = { operator: this.operator, motion: { char: char, count: this.getCount() } }; if (motions[char].param) this.waitForParam(ctx); else this.exec(editor, ctx); } else if (alias[char] && this.isAccepting(MOTION)) { alias[char].operator.count = this.getCount(); this.exec(editor, alias[char]); } else if (actions[char] && this.isAccepting(ACTION)) { var actionObj = { action: { fn: actions[char].fn, count: this.getCount() } }; if (actions[char].param) { this.waitForParam(actionObj); } else { this.exec(editor, actionObj); } if (actions[char].acceptsMotion) this.idle = false; } else if (this.operator) { this.exec(editor, { operator: this.operator }, char); } else { this.reset(); } }, waitForParam: function(cmd) { this.waitingForParam = cmd; }, getCount: function() { var count = this.currentCount; this.currentCount = ""; return count && parseInt(count, 10); }, exec: function(editor, action, param) { var m = action.motion; var o = action.operator; var a = action.action; if (!param) param = action.param; if (o) { this.previous = { action: action, param: param }; } if (o && !editor.selection.isEmpty()) { if (operators[o.char].selFn) { operators[o.char].selFn(editor, editor.getSelectionRange(), o.count, param); this.reset(); } return; } // There is an operator, but no motion or action. We try to pass the // current char to the operator to see if it responds to it (an example // of this is the 'dd' operator). else if (!m && !a && o && param) { operators[o.char].fn(editor, null, o.count, param); this.reset(); } else if (m) { var run = function(fn) { if (fn && typeof fn === "function") { // There should always be a motion if (m.count && !motionObj.handlesCount) repeat(fn, m.count, [editor, null, m.count, param]); else fn(editor, null, m.count, param); } }; var motionObj = motions[m.char]; var selectable = motionObj.sel; if (!o) { if ((util.onVisualMode || util.onVisualLineMode) && selectable) run(motionObj.sel); else run(motionObj.nav); } else if (selectable) { repeat(function() { run(motionObj.sel); operators[o.char].fn(editor, editor.getSelectionRange(), o.count, param); }, o.count || 1); } this.reset(); } else if (a) { a.fn(editor, editor.getSelectionRange(), a.count, param); this.reset(); } handleCursorMove(editor); }, isAccepting: function(type) { return this.accepting.indexOf(type) !== -1; }, reset: function() { this.operator = null; this.motion = null; this.currentCount = ""; this.accepting = [NUMBER, OPERATOR, MOTION, ACTION]; this.idle = true; this.waitingForParam = null; } }; function setPreviousCommand(fn) { inputBuffer.previous = { action: { action: { fn: fn } } }; } exports.coreCommands = { start: { exec: function start(editor) { util.insertMode(editor); setPreviousCommand(start); } }, startBeginning: { exec: function startBeginning(editor) { editor.navigateLineStart(); util.insertMode(editor); setPreviousCommand(startBeginning); } }, // Stop Insert mode as soon as possible. Works like typing <Esc> in // insert mode. stop: { exec: function stop(editor) { inputBuffer.reset(); util.onVisualMode = false; util.onVisualLineMode = false; inputBuffer.lastInsertCommands = util.normalMode(editor); } }, append: { exec: function append(editor) { var pos = editor.getCursorPosition(); var lineLen = editor.session.getLine(pos.row).length; if (lineLen) editor.navigateRight(); util.insertMode(editor); setPreviousCommand(append); } }, appendEnd: { exec: function appendEnd(editor) { editor.navigateLineEnd(); util.insertMode(editor); setPreviousCommand(appendEnd); } } }; var handleCursorMove = exports.onCursorMove = function(editor, e) { if (util.currentMode === 'insert' || handleCursorMove.running) return; else if(!editor.selection.isEmpty()) { handleCursorMove.running = true; if (util.onVisualLineMode) { var originRow = editor.selection.visualLineStart; var cursorRow = editor.getCursorPosition().row; if(originRow <= cursorRow) { var endLine = editor.session.getLine(cursorRow); editor.selection.clearSelection(); editor.selection.moveCursorTo(originRow, 0); editor.selection.selectTo(cursorRow, endLine.length); } else { var endLine = editor.session.getLine(originRow); editor.selection.clearSelection(); editor.selection.moveCursorTo(originRow, endLine.length); editor.selection.selectTo(cursorRow, 0); } } handleCursorMove.running = false; return; } else { if (e && (util.onVisualLineMode || util.onVisualMode)) { editor.selection.clearSelection(); util.normalMode(editor); } handleCursorMove.running = true; var pos = editor.getCursorPosition(); var lineLen = editor.session.getLine(pos.row).length; if (lineLen && pos.column === lineLen) editor.navigateLeft(); handleCursorMove.running = false; } }; }); define('ace/keyboard/vim/maps/util', ['require', 'exports', 'module' , 'ace/keyboard/vim/registers', 'ace/lib/dom'], function(require, exports, module) { var registers = require("../registers"); var dom = require("../../../lib/dom"); dom.importCssString('.insert-mode. ace_cursor{\ border-left: 2px solid #333333;\ }\ .ace_dark.insert-mode .ace_cursor{\ border-left: 2px solid #eeeeee;\ }\ .normal-mode .ace_cursor{\ border: 0!important;\ background-color: red;\ opacity: 0.5;\ }', 'vimMode'); module.exports = { onVisualMode: false, onVisualLineMode: false, currentMode: 'normal', noMode: function(editor) { editor.unsetStyle('insert-mode'); editor.unsetStyle('normal-mode'); if (editor.commands.recording) editor.commands.toggleRecording(); editor.setOverwrite(false); }, insertMode: function(editor) { this.currentMode = 'insert'; // Switch editor to insert mode editor.setStyle('insert-mode'); editor.unsetStyle('normal-mode'); editor.setOverwrite(false); editor.keyBinding.$data.buffer = ""; editor.keyBinding.$data.state = "insertMode"; this.onVisualMode = false; this.onVisualLineMode = false; if(this.onInsertReplaySequence) { // Ok, we're apparently replaying ("."), so let's do it editor.commands.macro = this.onInsertReplaySequence; editor.commands.replay(editor); this.onInsertReplaySequence = null; this.normalMode(editor); } else { editor._emit("vimMode", "insert"); // Record any movements, insertions in insert mode if(!editor.commands.recording) editor.commands.toggleRecording(); } }, normalMode: function(editor) { // Switch editor to normal mode this.currentMode = 'normal'; editor.unsetStyle('insert-mode'); editor.setStyle('normal-mode'); editor.clearSelection(); var pos; if (!editor.getOverwrite()) { pos = editor.getCursorPosition(); if (pos.column > 0) editor.navigateLeft(); } editor.setOverwrite(true); editor.keyBinding.$data.buffer = ""; editor.keyBinding.$data.state = "start"; this.onVisualMode = false; this.onVisualLineMode = false; editor._emit("changeVimMode", "normal"); // Save recorded keystrokes if (editor.commands.recording) { editor.commands.toggleRecording(); return editor.commands.macro; } else { return []; } }, visualMode: function(editor, lineMode) { if ( (this.onVisualLineMode && lineMode) || (this.onVisualMode && !lineMode) ) { this.normalMode(editor); return; } editor.setStyle('insert-mode'); editor.unsetStyle('normal-mode'); editor._emit("changeVimMode", "visual"); if (lineMode) { this.onVisualLineMode = true; } else { this.onVisualMode = true; this.onVisualLineMode = false; } }, getRightNthChar: function(editor, cursor, char, n) { var line = editor.getSession().getLine(cursor.row); var matches = line.substr(cursor.column + 1).split(char); return n < matches.length ? matches.slice(0, n).join(char).length : null; }, getLeftNthChar: function(editor, cursor, char, n) { var line = editor.getSession().getLine(cursor.row); var matches = line.substr(0, cursor.column).split(char); return n < matches.length ? matches.slice(-1 * n).join(char).length : null; }, toRealChar: function(char) { if (char.length === 1) return char; if (/^shift-./.test(char)) return char[char.length - 1].toUpperCase(); else return ""; }, copyLine: function(editor) { var pos = editor.getCursorPosition(); editor.selection.clearSelection(); editor.moveCursorTo(pos.row, pos.column); editor.selection.selectLine(); registers._default.isLine = true; registers._default.text = editor.getCopyText().replace(/\n$/, ""); editor.selection.clearSelection(); editor.moveCursorTo(pos.row, pos.column); } }; }); define('ace/keyboard/vim/registers', ['require', 'exports', 'module' ], function(require, exports, module) { "never use strict"; module.exports = { _default: { text: "", isLine: false } }; }); "use strict" define('ace/keyboard/vim/maps/motions', ['require', 'exports', 'module' , 'ace/keyboard/vim/maps/util', 'ace/search', 'ace/range'], function(require, exports, module) { var util = require("./util"); var keepScrollPosition = function(editor, fn) { var scrollTopRow = editor.renderer.getScrollTopRow(); var initialRow = editor.getCursorPosition().row; var diff = initialRow - scrollTopRow; fn && fn.call(editor); editor.renderer.scrollToRow(editor.getCursorPosition().row - diff); }; function Motion(getRange, type){ if (type == 'extend') var extend = true; else var reverse = type; this.nav = function(editor) { var r = getRange(editor); if (!r) return; if (!r.end) var a = r; else if (reverse) var a = r.start; else var a = r.end; editor.clearSelection(); editor.moveCursorTo(a.row, a.column); } this.sel = function(editor){ var r = getRange(editor); if (!r) return; if (extend) return editor.selection.setSelectionRange(r); if (!r.end) var a = r; else if (reverse) var a = r.start; else var a = r.end; editor.selection.selectTo(a.row, a.column); } } var nonWordRe = /[\s.\/\\()\"'-:,.;<>~!@#$%^&*|+=\[\]{}`~?]/; var wordSeparatorRe = /[.\/\\()\"'-:,.;<>~!@#$%^&*|+=\[\]{}`~?]/; var whiteRe = /\s/; var StringStream = function(editor, cursor) { var sel = editor.selection; this.range = sel.getRange(); cursor = cursor || sel.selectionLead; this.row = cursor.row; this.col = cursor.column; var line = editor.session.getLine(this.row); var maxRow = editor.session.getLength() this.ch = line[this.col] || '\n' this.skippedLines = 0; this.next = function() { this.ch = line[++this.col] || this.handleNewLine(1); //this.debug() return this.ch; } this.prev = function() { this.ch = line[--this.col] || this.handleNewLine(-1); //this.debug() return this.ch; } this.peek = function(dir) { var ch = line[this.col + dir]; if (ch) return ch; if (dir == -1) return '\n'; if (this.col == line.length - 1) return '\n'; return editor.session.getLine(this.row + 1)[0] || '\n'; } this.handleNewLine = function(dir) { if (dir == 1){ if (this.col == line.length) return '\n'; if (this.row == maxRow - 1) return ''; this.col = 0; this.row ++; line = editor.session.getLine(this.row); this.skippedLines++; return line[0] || '\n'; } if (dir == -1) { if (this.row == 0) return ''; this.row --; line = editor.session.getLine(this.row); this.col = line.length; this.skippedLines--; return '\n'; } } this.debug = function() { console.log(line.substring(0, this.col)+'|'+this.ch+'\''+this.col+'\''+line.substr(this.col+1)); } } var Search = require("ace/search").Search; var search = new Search(); function find(editor, needle, dir) { search.$options.needle = needle; search.$options.backwards = dir == -1; return search.find(editor.session); } var Range = require("ace/range").Range; module.exports = { "w": new Motion(function(editor) { var str = new StringStream(editor); if (str.ch && wordSeparatorRe.test(str.ch)) { while (str.ch && wordSeparatorRe.test(str.ch)) str.next(); } else { while (str.ch && !nonWordRe.test(str.ch)) str.next(); } while (str.ch && whiteRe.test(str.ch) && str.skippedLines < 2) str.next(); str.skippedLines == 2 && str.prev(); return {column: str.col, row: str.row}; }), "W": new Motion(function(editor) { var str = new StringStream(editor); while(str.ch && !(whiteRe.test(str.ch) && !whiteRe.test(str.peek(1))) && str.skippedLines < 2) str.next(); if (str.skippedLines == 2) str.prev(); else str.next(); return {column: str.col, row: str.row} }), "b": new Motion(function(editor) { var str = new StringStream(editor); str.prev(); while (str.ch && whiteRe.test(str.ch) && str.skippedLines > -2) str.prev(); if (str.ch && wordSeparatorRe.test(str.ch)) { while (str.ch && wordSeparatorRe.test(str.ch)) str.prev(); } else { while (str.ch && !nonWordRe.test(str.ch)) str.prev(); } str.ch && str.next(); return {column: str.col, row: str.row}; }), "B": new Motion(function(editor) { var str = new StringStream(editor) str.prev(); while(str.ch && !(!whiteRe.test(str.ch) && whiteRe.test(str.peek(-1))) && str.skippedLines > -2) str.prev(); if (str.skippedLines == -2) str.next(); return {column: str.col, row: str.row}; }, true), "e": new Motion(function(editor) { var str = new StringStream(editor); str.next(); while (str.ch && whiteRe.test(str.ch)) str.next(); if (str.ch && wordSeparatorRe.test(str.ch)) { while (str.ch && wordSeparatorRe.test(str.ch)) str.next(); } else { while (str.ch && !nonWordRe.test(str.ch)) str.next(); } str.ch && str.prev(); return {column: str.col, row: str.row}; }), "E": new Motion(function(editor) { var str = new StringStream(editor); str.next(); while(str.ch && !(!whiteRe.test(str.ch) && whiteRe.test(str.peek(1)))) str.next(); return {column: str.col, row: str.row}; }), "l": { nav: function(editor) { editor.navigateRight(); }, sel: function(editor) { var pos = editor.getCursorPosition(); var col = pos.column; var lineLen = editor.session.getLine(pos.row).length; // Solving the behavior at the end of the line due to the // different 0 index-based colum positions in ACE. if (lineLen && col !== lineLen) //In selection mode you can select the newline editor.selection.selectRight(); } }, "h": { nav: function(editor) { var pos = editor.getCursorPosition(); if (pos.column > 0) editor.navigateLeft(); }, sel: function(editor) { var pos = editor.getCursorPosition(); if (pos.column > 0) editor.selection.selectLeft(); } }, "k": { nav: function(editor) { editor.navigateUp(); }, sel: function(editor) { editor.selection.selectUp(); } }, "j": { nav: function(editor) { editor.navigateDown(); }, sel: function(editor) { editor.selection.selectDown(); } }, "i": { param: true, sel: function(editor, range, count, param) { switch (param) { case "w": editor.selection.selectWord(); break; case "W": editor.selection.selectAWord(); break; case "(": case "{": case "[": var cursor = editor.getCursorPosition() var end = editor.session.$findClosingBracket(param, cursor, /paren/) if (!end) return; var start = editor.session.$findOpeningBracket(editor.session.$brackets[param], cursor, /paren/) if (!start) return; start.column ++; editor.selection.setSelectionRange(Range.fromPoints(start, end)) break case "'": case "\"": case "/": var end = find(editor, param, 1) if (!end) return; var start = find(editor, param, -1) if (!start) return; editor.selection.setSelectionRange(Range.fromPoints(start.end, end.start)) break } } }, "a": { param: true, sel: function(editor, range, count, param) { switch (param) { case "w": editor.selection.selectAWord(); break; case "W": editor.selection.selectAWord(); break; case "(": case "{": case "[": var cursor = editor.getCursorPosition(); var end = editor.session.$findClosingBracket(param, cursor, /paren/); if (!end) return; var start = editor.session.$findOpeningBracket(editor.session.$brackets[param], cursor, /paren/); if (!start) return; end.column ++; editor.selection.setSelectionRange(Range.fromPoints(start, end)); break; case "'": case "\"": case "/": var end = find(editor, param, 1); if (!end) return; var start = find(editor, param, -1); if (!start) return; end.column ++; editor.selection.setSelectionRange(Range.fromPoints(start.start, end.end)); break; } } }, "f": { param: true, handlesCount: true, nav: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getRightNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.selection.clearSelection(); // Why does it select in the first place? ed.moveCursorTo(cursor.row, column + cursor.column + 1); } }, sel: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getRightNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.moveCursorTo(cursor.row, column + cursor.column + 1); } } }, "F": { param: true, handlesCount: true, nav: function(editor, range, count, param) { count = parseInt(count, 10) || 1; var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getLeftNthChar(editor, cursor, param, count); if (typeof column === "number") { ed.selection.clearSelection(); // Why does it select in the first place? ed.moveCursorTo(cursor.row, cursor.column - column - 1); } }, sel: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getLeftNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.moveCursorTo(cursor.row, cursor.column - column - 1); } } }, "t": { param: true, handlesCount: true, nav: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getRightNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.selection.clearSelection(); // Why does it select in the first place? ed.moveCursorTo(cursor.row, column + cursor.column); } }, sel: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getRightNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.moveCursorTo(cursor.row, column + cursor.column); } } }, "T": { param: true, handlesCount: true, nav: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getLeftNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.selection.clearSelection(); // Why does it select in the first place? ed.moveCursorTo(cursor.row, -column + cursor.column); } }, sel: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getLeftNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.moveCursorTo(cursor.row, -column + cursor.column); } } }, "^": { nav: function(editor) { editor.navigateLineStart(); }, sel: function(editor) { editor.selection.selectLineStart(); } }, "$": { nav: function(editor) { editor.navigateLineEnd(); }, sel: function(editor) { editor.selection.selectLineEnd(); } }, "0": { nav: function(editor) { var ed = editor; ed.navigateTo(ed.selection.selectionLead.row, 0); }, sel: function(editor) { var ed = editor; ed.selectTo(ed.selection.selectionLead.row, 0); } }, "G": { nav: function(editor, range, count, param) { if (!count && count !== 0) { // Stupid JS count = editor.session.getLength(); } editor.gotoLine(count); }, sel: function(editor, range, count, param) { if (!count && count !== 0) { // Stupid JS count = editor.session.getLength(); } editor.selection.selectTo(count, 0); } }, "g": { param: true, nav: function(editor, range, count, param) { switch(param) { case "m": console.log("Middle line"); break; case "e": console.log("End of prev word"); break; case "g": editor.gotoLine(count || 0); case "u": editor.gotoLine(count || 0); case "U": editor.gotoLine(count || 0); } }, sel: function(editor, range, count, param) { switch(param) { case "m": console.log("Middle line"); break; case "e": console.log("End of prev word"); break; case "g": editor.selection.selectTo(count || 0, 0); } } }, "o": { nav: function(editor, range, count, param) { count = count || 1; var content = ""; while (0 < count--) content += "\n"; if (content.length) { editor.navigateLineEnd() editor.insert(content); util.insertMode(editor); } } }, "O": { nav: function(editor, range, count, param) { var row = editor.getCursorPosition().row; count = count || 1; var content = ""; while (0 < count--) content += "\n"; if (content.length) { if(row > 0) { editor.navigateUp(); editor.navigateLineEnd() editor.insert(content); } else { editor.session.insert({row: 0, column: 0}, content); editor.navigateUp(); } util.insertMode(editor); } } }, "%": new Motion(function(editor){ var brRe = /[\[\]{}()]/g; var cursor = editor.getCursorPosition(); var ch = editor.session.getLine(cursor.row)[cursor.column]; if (!brRe.test(ch)) { var range = find(editor, brRe); if (!range) return; cursor = range.start; } var match = editor.session.findMatchingBracket({ row: cursor.row, column: cursor.column + 1 }); return match; }), "ctrl-d": { nav: function(editor, range, count, param) { editor.selection.clearSelection(); keepScrollPosition(editor, editor.gotoPageDown); }, sel: function(editor, range, count, param) { keepScrollPosition(editor, editor.selectPageDown); } }, "ctrl-u": { nav: function(editor, range, count, param) { editor.selection.clearSelection(); keepScrollPosition(editor, editor.gotoPageUp); }, sel: function(editor, range, count, param) { keepScrollPosition(editor, editor.selectPageUp); } }, }; module.exports.backspace = module.exports.left = module.exports.h; module.exports.right = module.exports.l; module.exports.up = module.exports.k; module.exports.down = module.exports.j; module.exports.pagedown = module.exports["ctrl-d"]; module.exports.pageup = module.exports["ctrl-u"]; }); define('ace/keyboard/vim/maps/operators', ['require', 'exports', 'module' , 'ace/keyboard/vim/maps/util', 'ace/keyboard/vim/registers'], function(require, exports, module) { "never use strict"; var util = require("./util"); var registers = require("../registers"); module.exports = { "d": { selFn: function(editor, range, count, param) { registers._default.text = editor.getCopyText(); registers._default.isLine = util.onVisualLineMode; if(util.onVisualLineMode) editor.removeLines(); else editor.session.remove(range); util.normalMode(editor); }, fn: function(editor, range, count, param) { count = count || 1; switch (param) { case "d": registers._default.text = ""; registers._default.isLine = true; for (var i = 0; i < count; i++) { editor.selection.selectLine(); registers._default.text += editor.getCopyText(); var selRange = editor.getSelectionRange(); editor.session.remove(selRange); editor.selection.clearSelection(); } registers._default.text = registers._default.text.replace(/\n$/, ""); break; default: if (range) { editor.selection.setSelectionRange(range); registers._default.text = editor.getCopyText(); registers._default.isLine = false; editor.session.remove(range); editor.selection.clearSelection(); } } } }, "c": { selFn: function(editor, range, count, param) { editor.session.remove(range); util.insertMode(editor); }, fn: function(editor, range, count, param) { count = count || 1; switch (param) { case "c": for (var i = 0; i < count; i++) { editor.removeLines(); util.insertMode(editor); } break; default: if (range) { // range.end.column ++; editor.session.remove(range); util.insertMode(editor); } } } }, "y": { selFn: function(editor, range, count, param) { registers._default.text = editor.getCopyText(); registers._default.isLine = util.onVisualLineMode; editor.selection.clearSelection(); util.normalMode(editor); }, fn: function(editor, range, count, param) { count = count || 1; switch (param) { case "y": var pos = editor.getCursorPosition(); editor.selection.selectLine(); for (var i = 0; i < count - 1; i++) { editor.selection.moveCursorDown(); } registers._default.text = editor.getCopyText().replace(/\n$/, ""); editor.selection.clearSelection(); registers._default.isLine = true; editor.moveCursorToPosition(pos); break; default: if (range) { var pos = editor.getCursorPosition(); editor.selection.setSelectionRange(range); registers._default.text = editor.getCopyText(); registers._default.isLine = false; editor.selection.clearSelection(); editor.moveCursorTo(pos.row, pos.column); } } } }, ">": { selFn: function(editor, range, count, param) { count = count || 1; for (var i = 0; i < count; i++) { editor.indent(); } util.normalMode(editor); }, fn: function(editor, range, count, param) { count = parseInt(count || 1, 10); switch (param) { case ">": var pos = editor.getCursorPosition(); editor.selection.selectLine(); for (var i = 0; i < count - 1; i++) { editor.selection.moveCursorDown(); } editor.indent(); editor.selection.clearSelection(); editor.moveCursorToPosition(pos); editor.navigateLineEnd(); editor.navigateLineStart(); break; } } }, "<": { selFn: function(editor, range, count, param) { count = count || 1; for (var i = 0; i < count; i++) { editor.blockOutdent(); } util.normalMode(editor); }, fn: function(editor, range, count, param) { count = count || 1; switch (param) { case "<": var pos = editor.getCursorPosition(); editor.selection.selectLine(); for (var i = 0; i < count - 1; i++) { editor.selection.moveCursorDown(); } editor.blockOutdent(); editor.selection.clearSelection(); editor.moveCursorToPosition(pos); editor.navigateLineEnd(); editor.navigateLineStart(); break; } } } }; }); "use strict" define('ace/keyboard/vim/maps/aliases', ['require', 'exports', 'module' ], function(require, exports, module) { module.exports = { "x": { operator: { char: "d", count: 1 }, motion: { char: "l", count: 1 } }, "X": { operator: { char: "d", count: 1 }, motion: { char: "h", count: 1 } }, "D": { operator: { char: "d", count: 1 }, motion: { char: "$", count: 1 } }, "C": { operator: { char: "c", count: 1 }, motion: { char: "$", count: 1 } }, "s": { operator: { char: "c", count: 1 }, motion: { char: "l", count: 1 } }, "S": { operator: { char: "c", count: 1 }, param: "c" } }; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/keybinding-vim.js
JavaScript
asf20
50,851
define('ace/mode/groovy', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/javascript', 'ace/tokenizer', 'ace/mode/groovy_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var JavaScriptMode = require("./javascript").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var GroovyHighlightRules = require("./groovy_highlight_rules").GroovyHighlightRules; var Mode = function() { JavaScriptMode.call(this); this.$tokenizer = new Tokenizer(new GroovyHighlightRules().getRules()); }; oop.inherits(Mode, JavaScriptMode); (function() { this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/groovy_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var GroovyHighlightRules = function() { var keywords = lang.arrayToMap( ("assert|with|abstract|continue|for|new|switch|" + "assert|default|goto|package|synchronized|" + "boolean|do|if|private|this|" + "break|double|implements|protected|throw|" + "byte|else|import|public|throws|" + "case|enum|instanceof|return|transient|" + "catch|extends|int|short|try|" + "char|final|interface|static|void|" + "class|finally|long|strictfp|volatile|" + "def|float|native|super|while").split("|") ); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var langClasses = lang.arrayToMap( ("AbstractMethodError|AssertionError|ClassCircularityError|"+ "ClassFormatError|Deprecated|EnumConstantNotPresentException|"+ "ExceptionInInitializerError|IllegalAccessError|"+ "IllegalThreadStateException|InstantiationError|InternalError|"+ "NegativeArraySizeException|NoSuchFieldError|Override|Process|"+ "ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|"+ "SuppressWarnings|TypeNotPresentException|UnknownError|"+ "UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|"+ "InstantiationException|IndexOutOfBoundsException|"+ "ArrayIndexOutOfBoundsException|CloneNotSupportedException|"+ "NoSuchFieldException|IllegalArgumentException|NumberFormatException|"+ "SecurityException|Void|InheritableThreadLocal|IllegalStateException|"+ "InterruptedException|NoSuchMethodException|IllegalAccessException|"+ "UnsupportedOperationException|Enum|StrictMath|Package|Compiler|"+ "Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|"+ "NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|"+ "NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|"+ "Character|Boolean|StackTraceElement|Appendable|StringBuffer|"+ "Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|"+ "StackOverflowError|OutOfMemoryError|VirtualMachineError|"+ "ArrayStoreException|ClassCastException|LinkageError|"+ "NoClassDefFoundError|ClassNotFoundException|RuntimeException|"+ "Exception|ThreadDeath|Error|Throwable|System|ClassLoader|"+ "Cloneable|Class|CharSequence|Comparable|String|Object").split("|") ); var importClasses = lang.arrayToMap( ("").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", regex : '"""', next : "qqstring" }, { token : "string", regex : "'''", next : "qstring" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (langClasses.hasOwnProperty(value)) return "support.function"; else if (importClasses.hasOwnProperty(value)) return "support.function"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\?:|\\?\\.|\\*\\.|<=>|=~|==~|\\.@|\\*\\.@|\\.&|as|in|is|!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : /\\(?:u[0-9A-Fa-f]{4}|.|$)/ }, { token : "constant.language.escape", regex : /\$[\w\d]+/ }, { token : "constant.language.escape", regex : /\$\{[^"\}]+\}?/ }, { token : "string", regex : '"{3,5}', next : "start" }, { token : "string", regex : '.+?' } ], "qstring" : [ { token : "constant.language.escape", regex : /\\(?:u[0-9A-Fa-f]{4}|.|$)/ }, { token : "string", regex : "'{3,5}", next : "start" }, { token : "string", regex : ".+?" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(GroovyHighlightRules, TextHighlightRules); exports.GroovyHighlightRules = GroovyHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-groovy.js
JavaScript
asf20
45,720
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/textmate', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-tm"; exports.cssText = ".ace-tm .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tm .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tm .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-tm .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tm .ace_fold {\ background-color: #6B72E6;\ }\ \ .ace-tm .ace_text-layer {\ cursor: text;\ }\ \ .ace-tm .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-tm .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid black;\ }\ \ .ace-tm .ace_line .ace_invisible {\ color: rgb(191, 191, 191);\ }\ \ .ace-tm .ace_line .ace_storage,\ .ace-tm .ace_line .ace_keyword {\ color: blue;\ }\ \ .ace-tm .ace_line .ace_constant {\ color: rgb(197, 6, 11);\ }\ \ .ace-tm .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-tm .ace_line .ace_constant.ace_language {\ color: rgb(88, 92, 246);\ }\ \ .ace-tm .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-tm .ace_line .ace_invalid {\ background-color: rgba(255, 0, 0, 0.1);\ color: red;\ }\ \ .ace-tm .ace_line .ace_support.ace_function {\ color: rgb(60, 76, 114);\ }\ \ .ace-tm .ace_line .ace_support.ace_constant {\ color: rgb(6, 150, 14);\ }\ \ .ace-tm .ace_line .ace_support.ace_type,\ .ace-tm .ace_line .ace_support.ace_class {\ color: rgb(109, 121, 222);\ }\ \ .ace-tm .ace_line .ace_keyword.ace_operator {\ color: rgb(104, 118, 135);\ }\ \ .ace-tm .ace_line .ace_string {\ color: rgb(3, 106, 7);\ }\ \ .ace-tm .ace_line .ace_comment {\ color: rgb(76, 136, 107);\ }\ \ .ace-tm .ace_line .ace_comment.ace_doc {\ color: rgb(0, 102, 255);\ }\ \ .ace-tm .ace_line .ace_comment.ace_doc.ace_tag {\ color: rgb(128, 159, 191);\ }\ \ .ace-tm .ace_line .ace_constant.ace_numeric {\ color: rgb(0, 0, 205);\ }\ \ .ace-tm .ace_line .ace_variable {\ color: rgb(49, 132, 149);\ }\ \ .ace-tm .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-tm .ace_entity.ace_name.ace_function {\ color: #0000A2;\ }\ \ .ace-tm .ace_markup.ace_markupine {\ text-decoration:underline;\ }\ \ .ace-tm .ace_markup.ace_heading {\ color: rgb(12, 7, 255);\ }\ \ .ace-tm .ace_markup.ace_list {\ color:rgb(185, 6, 144);\ }\ \ .ace-tm .ace_marker-layer .ace_selection {\ background: rgb(181, 213, 255);\ }\ .ace-tm.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px white;\ border-radius: 2px;\ }\ .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_meta.ace_tag {\ color:rgb(0, 50, 198);\ }\ \ .ace-tm .ace_string.ace_regex {\ color: rgb(255, 0, 0)\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-textmate.js
JavaScript
asf20
5,139
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Jimenez <adam AT shiftcreate DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/dreamweaver', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-dreamweaver"; exports.cssText = ".ace-dreamweaver .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-dreamweaver .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-dreamweaver .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-dreamweaver .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-dreamweaver .ace_fold {\ background-color: #00F;\ }\ \ .ace-dreamweaver .ace_text-layer {\ cursor: text;\ }\ \ .ace-dreamweaver .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-dreamweaver .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid black;\ }\ \ .ace-dreamweaver .ace_line .ace_invisible {\ color: rgb(191, 191, 191);\ }\ \ .ace-dreamweaver .ace_line .ace_storage,\ .ace-dreamweaver .ace_line .ace_keyword {\ color: blue;\ }\ \ .ace-dreamweaver .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-dreamweaver .ace_line .ace_constant.ace_language {\ color: rgb(88, 92, 246);\ }\ \ .ace-dreamweaver .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-dreamweaver .ace_line .ace_invalid {\ background-color: rgb(153, 0, 0);\ color: white;\ }\ \ .ace-dreamweaver .ace_line .ace_support.ace_function {\ color: rgb(60, 76, 114);\ }\ \ .ace-dreamweaver .ace_line .ace_support.ace_constant {\ color: rgb(6, 150, 14);\ }\ \ .ace-dreamweaver .ace_line .ace_support.ace_type,\ .ace-dreamweaver .ace_line .ace_support.ace_class {\ color: #009;\ }\ \ .ace-dreamweaver .ace_line .ace_support.ace_php_tag {\ color: #f00;\ }\ \ .ace-dreamweaver .ace_line .ace_keyword.ace_operator {\ color: rgb(104, 118, 135);\ }\ \ .ace-dreamweaver .ace_line .ace_string {\ color: #00F;\ }\ \ .ace-dreamweaver .ace_line .ace_comment {\ color: rgb(76, 136, 107);\ }\ \ .ace-dreamweaver .ace_line .ace_comment.ace_doc {\ color: rgb(0, 102, 255);\ }\ \ .ace-dreamweaver .ace_line .ace_comment.ace_doc.ace_tag {\ color: rgb(128, 159, 191);\ }\ \ .ace-dreamweaver .ace_line .ace_constant.ace_numeric {\ color: rgb(0, 0, 205);\ }\ \ .ace-dreamweaver .ace_line .ace_variable {\ color: #06F\ }\ \ .ace-dreamweaver .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-dreamweaver .ace_entity.ace_name.ace_function {\ color: #00F;\ }\ \ .ace-dreamweaver .ace_markup.ace_markupine {\ text-decoration:underline;\ }\ \ .ace-dreamweaver .ace_markup.ace_heading {\ color: rgb(12, 7, 255);\ }\ \ .ace-dreamweaver .ace_markup.ace_list {\ color:rgb(185, 6, 144);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_selection {\ background: rgb(181, 213, 255);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_step {\ background: rgb(252, 255, 0);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_stack {\ background: rgb(164, 229, 101);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgb(192, 192, 192);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_active_line {\ background: rgba(0, 0, 0, 0.07);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_selected_word {\ background: rgb(250, 250, 255);\ border: 1px solid rgb(200, 200, 250);\ }\ \ .ace-dreamweaver .ace_meta.ace_tag {\ color:#009;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_anchor {\ color:#060;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_form {\ color:#F90;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_image {\ color:#909;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_script {\ color:#900;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_style {\ color:#909;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_table {\ color:#099;\ }\ \ .ace-dreamweaver .ace_string.ace_regex {\ color: rgb(255, 0, 0)\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-dreamweaver.js
JavaScript
asf20
5,691
/* ***** BEGIN LICENSE BLOCK ***** * The Original Code is Ajax.org Code Editor (ACE). * * Contributor(s): * Jonathan Camile <jonathan.camile AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/sql', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/sql_highlight_rules', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var SqlHighlightRules = require("./sql_highlight_rules").SqlHighlightRules; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new SqlHighlightRules().getRules()); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var outentedRows = []; var re = /^(\s*)--/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "--"); } }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/sql_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var SqlHighlightRules = function() { var keywords = lang.arrayToMap( ("select|from|where|and|or|group|by|order|limit|offset|having|as|case|" + "when|else|end|type|left|right|join|on|outer|desc|asc").split("|") ); var builtinConstants = lang.arrayToMap( ("true|false|null").split("|") ); var builtinFunctions = lang.arrayToMap( ("count|min|max|avg|sum|rank|now|coalesce").split("|") ); this.$rules = { "start" : [ { token : "comment", regex : "--.*$" }, { token : "string", // " string regex : '".*"' }, { token : "string", // ' string regex : "'.*'" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : function(value) { value = value.toLowerCase(); if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, 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+" } ] }; }; oop.inherits(SqlHighlightRules, TextHighlightRules); exports.SqlHighlightRules = SqlHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-sql.js
JavaScript
asf20
4,709
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/solarized_dark', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-solarized-dark"; exports.cssText = "\ .ace-solarized-dark .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-solarized-dark .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-solarized-dark .ace_gutter {\ background: #09222b;\ color: #d0edf7;\ }\ \ .ace-solarized-dark .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-solarized-dark .ace_scroller {\ background-color: #002B36;\ }\ \ .ace-solarized-dark .ace_text-layer {\ cursor: text;\ color: #93A1A1;\ }\ \ .ace-solarized-dark .ace_cursor {\ border-left: 2px solid #D30102;\ }\ \ .ace-solarized-dark .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #D30102;\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_selection {\ background: #073642;\ }\ \ .ace-solarized-dark.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #002B36;\ border-radius: 2px;\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(147, 161, 161, 0.50);\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_active_line {\ background: #073642;\ }\ \ .ace-solarized-dark .ace_gutter_active_line {\ background-color: #0d3440;\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_selected_word {\ border: 1px solid #073642;\ }\ \ .ace-solarized-dark .ace_invisible {\ color: rgba(147, 161, 161, 0.50);\ }\ \ .ace-solarized-dark .ace_keyword, .ace-solarized-dark .ace_meta {\ color:#859900;\ }\ \ .ace-solarized-dark .ace_constant.ace_language {\ color:#B58900;\ }\ \ .ace-solarized-dark .ace_constant.ace_numeric {\ color:#D33682;\ }\ \ .ace-solarized-dark .ace_constant.ace_other {\ color:#CB4B16;\ }\ \ .ace-solarized-dark .ace_fold {\ background-color: #268BD2;\ border-color: #93A1A1;\ }\ \ .ace-solarized-dark .ace_support.ace_function {\ color:#268BD2;\ }\ \ .ace-solarized-dark .ace_storage {\ color:#93A1A1;\ }\ \ .ace-solarized-dark .ace_variable {\ color:#268BD2;\ }\ \ .ace-solarized-dark .ace_string {\ color:#2AA198;\ }\ \ .ace-solarized-dark .ace_string.ace_regexp {\ color:#D30102;\ }\ \ .ace-solarized-dark .ace_comment {\ font-style:italic;\ color:#657B83;\ }\ \ .ace-solarized-dark .ace_variable.ace_language {\ color:#268BD2;\ }\ \ .ace-solarized-dark .ace_entity.ace_other.ace_attribute-name {\ color:#93A1A1;\ }\ \ .ace-solarized-dark .ace_entity.ace_name.ace_function {\ color:#268BD2;\ }\ \ .ace-solarized-dark .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-solarized_dark.js
JavaScript
asf20
4,606
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/crimson_editor', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssText = ".ace-crimson-editor .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-crimson-editor .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-crimson-editor .ace_gutter {\ background: #e8e8e8;\ color: #333;\ overflow : hidden;\ }\ \ .ace-crimson-editor .ace_gutter-layer {\ width: 100%;\ text-align: right;\ }\ \ .ace-crimson-editor .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-crimson-editor .ace_text-layer {\ cursor: text;\ color: rgb(64, 64, 64);\ }\ \ .ace-crimson-editor .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-crimson-editor .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid black;\ }\ \ .ace-crimson-editor .ace_line .ace_invisible {\ color: rgb(191, 191, 191);\ }\ \ .ace-crimson-editor .ace_line .ace_identifier {\ color: black;\ }\ \ .ace-crimson-editor .ace_line .ace_keyword {\ color: blue;\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_language {\ color: rgb(255, 156, 0);\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-crimson-editor .ace_line .ace_invalid {\ text-decoration: line-through;\ color: rgb(224, 0, 0);\ }\ \ .ace-crimson-editor .ace_line .ace_fold {\ }\ \ .ace-crimson-editor .ace_line .ace_support.ace_function {\ color: rgb(192, 0, 0);\ }\ \ .ace-crimson-editor .ace_line .ace_support.ace_constant {\ color: rgb(6, 150, 14);\ }\ \ .ace-crimson-editor .ace_line .ace_support.ace_type,\ .ace-crimson-editor .ace_line .ace_support.ace_class {\ color: rgb(109, 121, 222);\ }\ \ .ace-crimson-editor .ace_line .ace_keyword.ace_operator {\ color: rgb(49, 132, 149);\ }\ \ .ace-crimson-editor .ace_line .ace_string {\ color: rgb(128, 0, 128);\ }\ \ .ace-crimson-editor .ace_line .ace_comment {\ color: rgb(76, 136, 107);\ }\ \ .ace-crimson-editor .ace_line .ace_comment.ace_doc {\ color: rgb(0, 102, 255);\ }\ \ .ace-crimson-editor .ace_line .ace_comment.ace_doc.ace_tag {\ color: rgb(128, 159, 191);\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_numeric {\ color: rgb(0, 0, 64);\ }\ \ .ace-crimson-editor .ace_line .ace_variable {\ color: rgb(0, 64, 128);\ }\ \ .ace-crimson-editor .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_selection {\ background: rgb(181, 213, 255);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_step {\ background: rgb(252, 255, 0);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_stack {\ background: rgb(164, 229, 101);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgb(192, 192, 192);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_active_line {\ background: rgb(232, 242, 254);\ }\ \ .ace-crimson-editor .ace_meta.ace_tag {\ color:rgb(28, 2, 255);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_selected_word {\ background: rgb(250, 250, 255);\ border: 1px solid rgb(200, 200, 250);\ }\ \ .ace-crimson-editor .ace_string.ace_regex {\ color: rgb(192, 0, 192);\ }"; exports.cssClass = "ace-crimson-editor"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-crimson_editor.js
JavaScript
asf20
5,192
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-javascript.js
JavaScript
asf20
39,310
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/mono_industrial', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-mono-industrial"; exports.cssText = "\ .ace-mono-industrial .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-mono-industrial .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-mono-industrial .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-mono-industrial .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-mono-industrial .ace_scroller {\ background-color: #222C28;\ }\ \ .ace-mono-industrial .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-mono-industrial .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-mono-industrial .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_selection {\ background: rgba(145, 153, 148, 0.40);\ }\ \ .ace-mono-industrial.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #222C28;\ border-radius: 2px;\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(102, 108, 104, 0.50);\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_active_line {\ background: rgba(12, 13, 12, 0.25);\ }\ \ .ace-mono-industrial .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(145, 153, 148, 0.40);\ }\ \ .ace-mono-industrial .ace_invisible {\ color: rgba(102, 108, 104, 0.50);\ }\ \ .ace-mono-industrial .ace_keyword, .ace-mono-industrial .ace_meta {\ color:#A39E64;\ }\ \ .ace-mono-industrial .ace_keyword.ace_operator {\ color:#A8B3AB;\ }\ \ .ace-mono-industrial .ace_constant, .ace-mono-industrial .ace_constant.ace_other {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_constant.ace_character, {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_constant.ace_character.ace_escape, {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_constant.ace_numeric {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_invalid {\ color:#FFFFFF;\ background-color:rgba(153, 0, 0, 0.68);\ }\ \ .ace-mono-industrial .ace_support.ace_constant {\ color:#C87500;\ }\ \ .ace-mono-industrial .ace_fold {\ background-color: #A8B3AB;\ border-color: #FFFFFF;\ }\ \ .ace-mono-industrial .ace_support.ace_function {\ color:#588E60;\ }\ \ .ace-mono-industrial .ace_storage {\ color:#C23B00;\ }\ \ .ace-mono-industrial .ace_variable {\ color:#A8B3AB;\ }\ \ .ace-mono-industrial .ace_variable.ace_parameter {\ color:#648BD2;\ }\ \ .ace-mono-industrial .ace_comment {\ color:#666C68;\ background-color:#151C19;\ }\ \ .ace-mono-industrial .ace_variable.ace_language {\ color:#648BD2;\ }\ \ .ace-mono-industrial .ace_entity.ace_other.ace_attribute-name {\ color:#909993;\ }\ \ .ace-mono-industrial .ace_entity.ace_name {\ color:#5778B6;\ }\ \ .ace-mono-industrial .ace_entity.ace_name.ace_function {\ color:#A8B3AB;\ }\ \ .ace-mono-industrial .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-mono_industrial.js
JavaScript
asf20
5,084
define('ace/mode/golang', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/golang_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var GolangHighlightRules = require("./golang_highlight_rules").GolangHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new GolangHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var outentedRows = []; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; };//end getNextLineIndent this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/golang_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var GolangHighlightRules = function() { var keywords = lang.arrayToMap( ("true|else|false|break|case|return|goto|if|const|" + "continue|struct|default|switch|for|" + "func|import|package|chan|defer|fallthrough|go|interface|map|range" + "select|type|var").split("|") ); var buildinConstants = lang.arrayToMap( ("nit|true|false|iota").split("|") ); this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant", // <CONSTANT> regex : "<[a-zA-Z0-9.]+>" }, { token : "keyword", // pre-compiler directivs regex : "(?:#include|#pragma|#line|#define|#undef|#ifdef|#else|#elif|#endif|#ifndef)" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); } oop.inherits(GolangHighlightRules, TextHighlightRules); exports.GolangHighlightRules = GolangHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-golang.js
JavaScript
asf20
22,083
define('ace/mode/haxe', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/haxe_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HaxeHighlightRules = require("./haxe_highlight_rules").HaxeHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new HaxeHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/haxe_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var HaxeHighlightRules = function() { var keywords = lang.arrayToMap( ("break|case|cast|catch|class|continue|default|else|enum|extends|for|function|if|implements|import|in|inline|interface|new|override|package|private|public|return|static|super|switch|this|throw|trace|try|typedef|untyped|var|while|Array|Void|Bool|Int|UInt|Float|Dynamic|String|List|Hash|IntHash|Error|Unknown|Type|Std").split("|") ); var buildinConstants = lang.arrayToMap( ("null|true|false").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", merge : true, next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({<]" }, { token : "paren.rparen", regex : "[\\])}>]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(HaxeHighlightRules, TextHighlightRules); exports.HaxeHighlightRules = HaxeHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-haxe.js
JavaScript
asf20
19,934
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/tomorrow_night_bright', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-tomorrow-night-bright"; exports.cssText = "\ .ace-tomorrow-night-bright .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tomorrow-night-bright .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tomorrow-night-bright .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-tomorrow-night-bright .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tomorrow-night-bright .ace_scroller {\ background-color: #000000;\ }\ \ .ace-tomorrow-night-bright .ace_text-layer {\ cursor: text;\ color: #DEDEDE;\ }\ \ .ace-tomorrow-night-bright .ace_cursor {\ border-left: 2px solid #9F9F9F;\ }\ \ .ace-tomorrow-night-bright .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #9F9F9F;\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_selection {\ background: #424242;\ }\ \ .ace-tomorrow-night-bright.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #000000;\ border-radius: 2px;\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #343434;\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_active_line {\ background: #2A2A2A;\ }\ \ .ace-tomorrow-night-bright .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_selected_word {\ border: 1px solid #424242;\ }\ \ .ace-tomorrow-night-bright .ace_invisible {\ color: #343434;\ }\ \ .ace-tomorrow-night-bright .ace_keyword, .ace-tomorrow-night-bright .ace_meta {\ color:#C397D8;\ }\ \ .ace-tomorrow-night-bright .ace_keyword.ace_operator {\ color:#70C0B1;\ }\ \ .ace-tomorrow-night-bright .ace_constant.ace_language {\ color:#E78C45;\ }\ \ .ace-tomorrow-night-bright .ace_constant.ace_numeric {\ color:#E78C45;\ }\ \ .ace-tomorrow-night-bright .ace_constant.ace_other {\ color:#EEEEEE;\ }\ \ .ace-tomorrow-night-bright .ace_invalid {\ color:#CED2CF;\ background-color:#DF5F5F;\ }\ \ .ace-tomorrow-night-bright .ace_invalid.ace_deprecated {\ color:#CED2CF;\ background-color:#B798BF;\ }\ \ .ace-tomorrow-night-bright .ace_support.ace_constant {\ color:#E78C45;\ }\ \ .ace-tomorrow-night-bright .ace_fold {\ background-color: #7AA6DA;\ border-color: #DEDEDE;\ }\ \ .ace-tomorrow-night-bright .ace_support.ace_function {\ color:#7AA6DA;\ }\ \ .ace-tomorrow-night-bright .ace_storage {\ color:#C397D8;\ }\ \ .ace-tomorrow-night-bright .ace_storage.ace_type, .ace-tomorrow-night-bright .ace_support.ace_type{\ color:#C397D8;\ }\ \ .ace-tomorrow-night-bright .ace_variable {\ color:#7AA6DA;\ }\ \ .ace-tomorrow-night-bright .ace_variable.ace_parameter {\ color:#E78C45;\ }\ \ .ace-tomorrow-night-bright .ace_string {\ color:#B9CA4A;\ }\ \ .ace-tomorrow-night-bright .ace_string.ace_regexp {\ color:#D54E53;\ }\ \ .ace-tomorrow-night-bright .ace_comment {\ color:#969896;\ }\ \ .ace-tomorrow-night-bright .ace_variable {\ color:#D54E53;\ }\ \ .ace-tomorrow-night-bright .ace_meta.ace_tag {\ color:#D54E53;\ }\ \ .ace-tomorrow-night-bright .ace_entity.ace_other.ace_attribute-name {\ color:#D54E53;\ }\ \ .ace-tomorrow-night-bright .ace_entity.ace_name.ace_function {\ color:#7AA6DA;\ }\ \ .ace-tomorrow-night-bright .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-tomorrow-night-bright .ace_markup.ace_heading {\ color:#B9CA4A;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-tomorrow_night_bright.js
JavaScript
asf20
5,486
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Wolfgang Meier * William Candillon <wcandillon AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/xquery', ['require', 'exports', 'module' , 'ace/worker/worker_client', 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xquery_highlight_rules', 'ace/mode/behaviour/xquery', 'ace/range'], function(require, exports, module) { var WorkerClient = require("../worker/worker_client").WorkerClient; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XQueryHighlightRules = require("./xquery_highlight_rules").XQueryHighlightRules; var XQueryBehaviour = require("./behaviour/xquery").XQueryBehaviour; //var XQueryBackgroundHighlighter = require("./xquery_background_highlighter").XQueryBackgroundHighlighter; var Range = require("../range").Range; var Mode = function(parent) { this.$tokenizer = new Tokenizer(new XQueryHighlightRules().getRules()); this.$behaviour = new XQueryBehaviour(parent); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var match = line.match(/\s*(?:then|else|return|[{\(]|<\w+>)\s*$/); if (match) indent += tab; return indent; }; this.checkOutdent = function(state, line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*[\}\)]/.test(input); }; this.autoOutdent = function(state, doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*[\}\)])/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; this.toggleCommentLines = function(state, doc, startRow, endRow) { var i, line; var outdent = true; var re = /^\s*\(:(.*):\)/; for (i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } var range = new Range(0, 0, 0, 0); for (i=startRow; i<= endRow; i++) { line = doc.getLine(i); range.start.row = i; range.end.row = i; range.end.column = line.length; doc.replace(range, outdent ? line.match(re)[1] : "(:" + line + ":)"); } }; this.createWorker = function(session) { this.$deltas = []; var worker = new WorkerClient(["ace"], "worker-xquery.js", "ace/mode/xquery_worker", "XQueryWorker"); var that = this; session.getDocument().on('change', function(evt){ that.$deltas.push(evt.data); }); worker.attachToDocument(session.getDocument()); worker.on("start", function(e) { //console.log("start"); that.$deltas = []; }); worker.on("error", function(e) { session.setAnnotations([e.data]); }); worker.on("ok", function(e) { session.clearAnnotations(); }); worker.on("highlight", function(tokens) { var firstRow = 0; var lastRow = session.getLength() - 1; var lines = tokens.data.lines; var states = tokens.data.states; for(var i=0; i < that.$deltas.length; i++) { var delta = that.$deltas[i]; if (delta.action === "insertLines") { var newLineCount = delta.lines.length; for (var i = 0; i < newLineCount; i++) { lines.splice(delta.range.start.row + i, 0, undefined); states.splice(delta.range.start.row + i, 0, undefined); } } else if (delta.action === "insertText") { if (session.getDocument().isNewLine(delta.text)) { lines.splice(delta.range.end.row, 0, undefined); states.splice(delta.range.end.row, 0, undefined); } else { lines[delta.range.start.row] = undefined; states[delta.range.start.row] = undefined; } } else if (delta.action === "removeLines") { var oldLineCount = delta.lines.length; lines.splice(delta.range.start.row, oldLineCount); states.splice(delta.range.start.row, oldLineCount); } else if (delta.action === "removeText") { if (session.getDocument().isNewLine(delta.text)) { lines[delta.range.start.row] = undefined; lines.splice(delta.range.end.row, 1); states[delta.range.start.row] = undefined; states.splice(delta.range.end.row, 1); } else { lines[delta.range.start.row] = undefined; states[delta.range.start.row] = undefined; } } } session.bgTokenizer.lines = lines; session.bgTokenizer.states = states; session.bgTokenizer.fireUpdateEvent(firstRow, lastRow); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xquery_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XQueryHighlightRules = function() { var keywords = lang.arrayToMap( ("after|ancestor|ancestor-or-self|and|as|ascending|attribute|before|case|cast|castable|child|collation|comment|copy|count|declare|default|delete|descendant|descendant-or-self|descending|div|document|document-node|element|else|empty|empty-sequence|end|eq|every|except|first|following|following-sibling|for|function|ge|group|gt|idiv|if|import|insert|instance|intersect|into|is|item|last|le|let|lt|mod|modify|module|namespace|namespace-node|ne|node|only|or|order|ordered|parent|preceding|preceding-sibling|processing-instruction|rename|replace|return|satisfies|schema-attribute|schema-element|self|some|stable|start|switch|text|to|treat|try|typeswitch|union|unordered|validate|where|with|xquery|contains|paragraphs|sentences|times|words|by|collectionreturn|variable|version|option|when|encoding|toswitch|catch|tumbling|sliding|window|at|using|stemming|collection|schema|while|on|nodes|index|external|then|in|updating|value|of|containsbreak|loop|continue|exit|returning").split("|") ); // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [ { token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", regex : "<\\!--", next : "comment" }, { token : "comment", regex : "\\(:", next : "comment" }, { token : "text", // opening tag regex : "<\\/?", next : "tag" }, { token : "constant", // number regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "variable", // variable regex : "\\$[a-zA-Z_][a-zA-Z0-9_\\-:]*\\b" }, { token: "string", regex : '".*?"' }, { token: "string", regex : "'.*?'" }, { token : "text", regex : "\\s+" }, { token: "support.function", regex: "\\w[\\w+_\\-:]+(?=\\()" }, { token : function(value) { if (keywords[value]) return "keyword"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token: "keyword.operator", regex: "\\*|=|<|>|\\-|\\+" }, { token: "lparen", regex: "[[({]" }, { token: "rparen", regex: "[\\])}]" } ], tag : [ { token : "text", regex : ">", next : "start" }, { token : "meta.tag", regex : "[-_a-zA-Z0-9:]+" }, { token : "text", regex : "\\s+" }, { token : "string", regex : '".*?"' }, { token : "string", regex : "'.*?'" } ], cdata : [ { token : "comment", regex : "\\]\\]>", next : "start" }, { token : "comment", regex : "\\s+" }, { token : "comment", regex : "(?:[^\\]]|\\](?!\\]>))+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token: "comment", regex : ".*:\\)", next : "start" }, { token : "comment", regex : ".+" } ] }; }; oop.inherits(XQueryHighlightRules, TextHighlightRules); exports.XQueryHighlightRules = XQueryHighlightRules; }); define('ace/mode/behaviour/xquery', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require('../behaviour').Behaviour; var CstyleBehaviour = require('./cstyle').CstyleBehaviour; var XQueryBehaviour = function (parent) { this.inherit(CstyleBehaviour, ["braces", "parens", "string_dquotes"]); // Get string behaviour this.parent = parent; this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } return false; }); // Check for open tag if user enters / and auto-close it. this.add("slash", "insertion", function (state, action, editor, session, text) { if (text == "/") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (cursor.column > 0 && line.charAt(cursor.column - 1) == "<") { line = line.substring(0, cursor.column) + "/" + line.substring(cursor.column); var lines = session.doc.getAllLines(); lines[cursor.row] = line; // call mode helper to close the tag if possible parent.exec("closeTag", lines.join(session.doc.getNewLineCharacter()), cursor.row); } } return false; }); } oop.inherits(XQueryBehaviour, Behaviour); exports.XQueryBehaviour = XQueryBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-xquery.js
JavaScript
asf20
20,973
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/clouds_midnight', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-clouds-midnight"; exports.cssText = "\ .ace-clouds-midnight .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-clouds-midnight .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-clouds-midnight .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-clouds-midnight .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-clouds-midnight .ace_scroller {\ background-color: #191919;\ }\ \ .ace-clouds-midnight .ace_text-layer {\ cursor: text;\ color: #929292;\ }\ \ .ace-clouds-midnight .ace_cursor {\ border-left: 2px solid #7DA5DC;\ }\ \ .ace-clouds-midnight .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #7DA5DC;\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_selection {\ background: #000000;\ }\ \ .ace-clouds-midnight.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #191919;\ border-radius: 2px;\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #BFBFBF;\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_active_line {\ background: rgba(215, 215, 215, 0.031);\ }\ \ .ace-clouds-midnight .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_selected_word {\ border: 1px solid #000000;\ }\ \ .ace-clouds-midnight .ace_invisible {\ color: #BFBFBF;\ }\ \ .ace-clouds-midnight .ace_keyword, .ace-clouds-midnight .ace_meta {\ color:#927C5D;\ }\ \ .ace-clouds-midnight .ace_keyword.ace_operator {\ color:#4B4B4B;\ }\ \ .ace-clouds-midnight .ace_constant.ace_language {\ color:#39946A;\ }\ \ .ace-clouds-midnight .ace_constant.ace_numeric {\ color:#46A609;\ }\ \ .ace-clouds-midnight .ace_invalid {\ color:#FFFFFF;\ background-color:#E92E2E;\ }\ \ .ace-clouds-midnight .ace_fold {\ background-color: #927C5D;\ border-color: #929292;\ }\ \ .ace-clouds-midnight .ace_support.ace_function {\ color:#E92E2E;\ }\ \ .ace-clouds-midnight .ace_storage {\ color:#E92E2E;\ }\ \ .ace-clouds-midnight .ace_string {\ color:#5D90CD;\ }\ \ .ace-clouds-midnight .ace_comment {\ color:#3C403B;\ }\ \ .ace-clouds-midnight .ace_entity.ace_other.ace_attribute-name {\ color:#606060;\ }\ \ .ace-clouds-midnight .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/theme-clouds_midnight.js
JavaScript
asf20
4,404
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules()); this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" }], cdata : [{ token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "(?:[^\\]]|\\](?!\\]>))+" }], comment : [{ token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); }; oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-xml.js
JavaScript
asf20
26,375
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/coldfusion', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml', 'ace/mode/javascript', 'ace/mode/css', 'ace/tokenizer', 'ace/mode/coldfusion_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var XmlMode = require("./xml").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ColdfusionHighlightRules = require("./coldfusion_highlight_rules").ColdfusionHighlightRules; var Mode = function() { XmlMode.call(this); var highlighter = new ColdfusionHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); this.$embeds = highlighter.getEmbeds(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); }; oop.inherits(Mode, XmlMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules()); this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" }], cdata : [{ token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "(?:[^\\]]|\\](?!\\]>))+" }], comment : [{ token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); }; oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("csslint", function(e) { var errors = []; e.data.forEach(function(message) { errors.push({ row: message.line - 1, column: message.col - 1, text: message.message, type: message.type, lint: message }); }); session.setAnnotations(errors); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/coldfusion_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/text_highlight_rules', 'ace/mode/xml_util'], function(require, exports, module) { var oop = require("../lib/oop"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var xml_util = require("./xml_util"); var ColdfusionHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [ { token : "text", merge : true, regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "meta.tag", regex : "<(?=\s*script)", next : "script" }, { token : "meta.tag", regex : "<(?=\s*style)", next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "[^<]+" } ], cdata : [ { token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", merge : true, regex : "\\s+" }, { token : "text", merge : true, regex : ".+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" } ] }; xml_util.tag(this.$rules, "tag", "start"); xml_util.tag(this.$rules, "style", "css-start"); xml_util.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); this.embedRules(CssHighlightRules, "css-", [{ token: "meta.tag", regex: "<\\/(?=style)", next: "tag" }]); }; oop.inherits(ColdfusionHighlightRules, TextHighlightRules); exports.ColdfusionHighlightRules = ColdfusionHighlightRules; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-coldfusion.js
JavaScript
asf20
72,811
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Colin Gourlay <colin DOT j DOT gourlay AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/python', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/python_highlight_rules', 'ace/mode/folding/pythonic', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var PythonHighlightRules = require("./python_highlight_rules").PythonHighlightRules; var PythonFoldMode = require("./folding/pythonic").FoldMode; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new PythonHighlightRules().getRules()); this.foldingRules = new PythonFoldMode("\\:"); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; var outdents = { "pass": 1, "return": 1, "raise": 1, "break": 1, "continue": 1 }; this.checkOutdent = function(state, line, input) { if (input !== "\r\n" && input !== "\r" && input !== "\n") return false; var tokens = this.$tokenizer.getLineTokens(line.trim(), state).tokens; if (!tokens) return false; // ignore trailing comments do { var last = tokens.pop(); } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); if (!last) return false; return (last.type == "keyword" && outdents[last.value]); }; this.autoOutdent = function(state, doc, row) { // outdenting in python is slightly different because it always applies // to the next line and only of a new line is inserted row += 1; var indent = this.$getIndent(doc.getLine(row)); var tab = doc.getTabString(); if (indent.slice(-tab.length) == tab) doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/python_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PythonHighlightRules = function() { var keywords = lang.arrayToMap( ("and|as|assert|break|class|continue|def|del|elif|else|except|exec|" + "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" + "raise|return|try|while|with|yield").split("|") ); var builtinConstants = lang.arrayToMap( ("True|False|None|NotImplemented|Ellipsis|__debug__").split("|") ); var builtinFunctions = lang.arrayToMap( ("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" + "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" + "binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" + "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" + "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" + "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" + "__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" + "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern").split("|") ); var futureReserved = lang.arrayToMap( ("").split("|") ); var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?"; var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var octInteger = "(?:0[oO]?[0-7]+)"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var binInteger = "(?:0[bB][01]+)"; var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; var exponent = "(?:[eE][+-]?\\d+)"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string", // """ string regex : strPre + '"{3}(?:[^\\\\]|\\\\.)*?"{3}' }, { token : "string", // multi line """ string start merge : true, regex : strPre + '"{3}.*$', next : "qqstring" }, { token : "string", // " string regex : strPre + '"(?:[^\\\\]|\\\\.)*?"' }, { token : "string", // ''' string regex : strPre + "'{3}(?:[^\\\\]|\\\\.)*?'{3}" }, { token : "string", // multi line ''' string start merge : true, regex : strPre + "'{3}.*$", next : "qstring" }, { token : "string", // ' string regex : strPre + "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // imaginary regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // long integer regex : integer + "[lL]\\b" }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, 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+" } ], "qqstring" : [ { token : "string", // multi line """ string end regex : '(?:[^\\\\]|\\\\.)*?"{3}', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", // multi line ''' string end regex : "(?:[^\\\\]|\\\\.)*?'{3}", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(PythonHighlightRules, TextHighlightRules); exports.PythonHighlightRules = PythonHighlightRules; }); define('ace/mode/folding/pythonic', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(markers) { this.foldingStartMarker = new RegExp("(?:([\\[{])|(" + markers + "))(?:\\s*)(?:#.*)?$"); }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { if (match[1]) return this.openingBracketBlock(session, match[1], row, match.index); if (match[2]) return this.indentationBlock(session, row, match.index + match[2].length); return this.indentationBlock(session, row); } } }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching 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 startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) 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, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-python.js
JavaScript
asf20
13,629
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Shlomo Zalman Heigh <shlomozalmanheigh AT gmail DOT com> * Carin Meier * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/clojure', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/clojure_highlight_rules', 'ace/mode/matching_parens_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ClojureHighlightRules = require("./clojure_highlight_rules").ClojureHighlightRules; var MatchingParensOutdent = require("./matching_parens_outdent").MatchingParensOutdent; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new ClojureHighlightRules().getRules()); this.$outdent = new MatchingParensOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, ";"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/[\(\[]/); if (match) { indent += " "; } match = line.match(/[\)]/); if (match) { indent = ""; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/clojure_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ClojureHighlightRules = function() { var builtinFunctions = lang.arrayToMap( ('* *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* ' + '*command-line-args* *compile-files* *compile-path* *e *err* *file* ' + '*flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* ' + '*print-dup* *print-length* *print-level* *print-meta* *print-readably* ' + '*read-eval* *source-path* *use-context-classloader* ' + '*warn-on-reflection* + - -> -&gt; ->> -&gt;&gt; .. / < &lt; <= &lt;= = ' + '== > &gt; >= &gt;= accessor aclone ' + 'add-classpath add-watch agent agent-errors aget alength alias all-ns ' + 'alter alter-meta! alter-var-root amap ancestors and apply areduce ' + 'array-map aset aset-boolean aset-byte aset-char aset-double aset-float ' + 'aset-int aset-long aset-short assert assoc assoc! assoc-in associative? ' + 'atom await await-for await1 bases bean bigdec bigint binding bit-and ' + 'bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left ' + 'bit-shift-right bit-test bit-xor boolean boolean-array booleans ' + 'bound-fn bound-fn* butlast byte byte-array bytes cast char char-array ' + 'char-escape-string char-name-string char? chars chunk chunk-append ' + 'chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? ' + 'class class? clear-agent-errors clojure-version coll? comment commute ' + 'comp comparator compare compare-and-set! compile complement concat cond ' + 'condp conj conj! cons constantly construct-proxy contains? count ' + 'counted? create-ns create-struct cycle dec decimal? declare definline ' + 'defmacro defmethod defmulti defn defn- defonce defstruct delay delay? ' + 'deliver deref derive descendants destructure disj disj! dissoc dissoc! ' + 'distinct distinct? doall doc dorun doseq dosync dotimes doto double ' + 'double-array doubles drop drop-last drop-while empty empty? ensure ' + 'enumeration-seq eval even? every? false? ffirst file-seq filter find ' + 'find-doc find-ns find-var first float float-array float? floats flush ' + 'fn fn? fnext for force format future future-call future-cancel ' + 'future-cancelled? future-done? future? gen-class gen-interface gensym ' + 'get get-in get-method get-proxy-class get-thread-bindings get-validator ' + 'hash hash-map hash-set identical? identity if-let if-not ifn? import ' + 'in-ns inc init-proxy instance? int int-array integer? interleave intern ' + 'interpose into into-array ints io! isa? iterate iterator-seq juxt key ' + 'keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list ' + 'list* list? load load-file load-reader load-string loaded-libs locking ' + 'long long-array longs loop macroexpand macroexpand-1 make-array ' + 'make-hierarchy map map? mapcat max max-key memfn memoize merge ' + 'merge-with meta method-sig methods min min-key mod name namespace neg? ' + 'newline next nfirst nil? nnext not not-any? not-empty not-every? not= ' + 'ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ' + 'ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? ' + 'or parents partial partition pcalls peek persistent! pmap pop pop! ' + 'pop-thread-bindings pos? pr pr-str prefer-method prefers ' + 'primitives-classnames print print-ctor print-doc print-dup print-method ' + 'print-namespace-doc print-simple print-special-doc print-str printf ' + 'println println-str prn prn-str promise proxy proxy-call-with-super ' + 'proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot ' + 'rand rand-int range ratio? rational? rationalize re-find re-groups ' + 're-matcher re-matches re-pattern re-seq read read-line read-string ' + 'reduce ref ref-history-count ref-max-history ref-min-history ref-set ' + 'refer refer-clojure release-pending-sends rem remove remove-method ' + 'remove-ns remove-watch repeat repeatedly replace replicate require ' + 'reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq ' + 'rsubseq second select-keys send send-off seq seq? seque sequence ' + 'sequential? set set-validator! set? short short-array shorts ' + 'shutdown-agents slurp some sort sort-by sorted-map sorted-map-by ' + 'sorted-set sorted-set-by sorted? special-form-anchor special-symbol? ' + 'split-at split-with str stream? string? struct struct-map subs subseq ' + 'subvec supers swap! symbol symbol? sync syntax-symbol-anchor take ' + 'take-last take-nth take-while test the-ns time to-array to-array-2d ' + 'trampoline transient tree-seq true? type unchecked-add unchecked-dec ' + 'unchecked-divide unchecked-inc unchecked-multiply unchecked-negate ' + 'unchecked-remainder unchecked-subtract underive unquote ' + 'unquote-splicing update-in update-proxy use val vals var-get var-set ' + 'var? vary-meta vec vector vector? when when-first when-let when-not ' + 'while with-bindings with-bindings* with-in-str with-loading-context ' + 'with-local-vars with-meta with-open with-out-str with-precision xml-seq ' + 'zero? zipmap ').split(" ") ); var keywords = lang.arrayToMap( ('def do fn if let loop monitor-enter monitor-exit new quote recur set! ' + 'throw try var').split(" ") ); var buildinConstants = lang.arrayToMap( ("true false nil").split(" ") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : ";.*$" }, { token : "comment", // multi line comment regex : "^=begin$", next : "comment" }, { token : "keyword", //parens regex : "[\\(|\\)]" }, { token : "keyword", //lists regex : "[\\'\\(]" }, { token : "keyword", //vectors regex : "[\\[|\\]]" }, { token : "keyword", //sets and maps regex : "[\\{|\\}|\\#\\{|\\#\\}]" }, { token : "keyword", // ampersands regex : '[\\&]' }, { token : "keyword", // metadata regex : '[\\#\\^\\{]' }, { token : "keyword", // anonymous fn syntactic sugar regex : '[\\%]' }, { token : "keyword", // deref reader macro regex : '[@]' }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language", regex : '[!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+||=|!=|<=|>=|<>|<|>|!|&&]' }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?$', next: "string" }, { token : "string", // symbol regex : "[:](?:[a-zA-Z]|\\d)+" }, { token : "string.regexp", //Regular Expressions regex : '/#"(?:\\.|(?:\\\")|[^\""\n])*"/g' } ], "comment" : [ { token : "comment", // closing comment regex : "^=end$", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "string" : [ { token : "string", merge : true, regex : "\\\\." }, { token : "string", regex : '[^"\\\\]*?"', next : "start" } ] }; }; oop.inherits(ClojureHighlightRules, TextHighlightRules); exports.ClojureHighlightRules = ClojureHighlightRules; }); define('ace/mode/matching_parens_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingParensOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\)/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\))/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingParensOutdent.prototype); exports.MatchingParensOutdent = MatchingParensOutdent; });
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/ace/mode-clojure.js
JavaScript
asf20
15,408
'use strict'; var module = angular.module('app.directives', []); module.directive('aceEditor', function (editor) { return { retrict:'A', link:function (scope, element) { editor.rebind(element[0]); } }; }); module.directive('star', function () { return { restrict:'E', replace:true, scope:{ val:'=value', // Value bound to eventFn:'&click' // Optional expression evaluated on click }, link:function (scope, element) { element.bind('click', function () { scope.$apply(function () { scope.val = !scope.val; }); scope.$eval(scope.eventFn, scope.val); }); }, template:'<i class="star" ng-class="{\'icon-star\' : val, \'icon-star-empty\' : !val}" ng-click="toggle()"></i>' } }); module.directive('alert', function ($rootScope) { return { restrict:'E', replace:true, link:function (scope, element) { $rootScope.$on('error', function (event, data) { scope.message = data.message; element.show(); }); scope.close = function () { element.hide(); }; }, template:'<div class="hide alert alert-error">' + ' <span class="close" ng-click="close()">×</span>' + ' {{message}}' + '</div>' } })
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Scripts/directives.js
JavaScript
asf20
1,774
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Views/_ViewStart.cshtml
HTML+Razor
asf20
55
@{ ViewBag.Title = "Index"; } <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="#">DrEdit</a> <ul class="nav pull-right" ng-controller="UserCtrl"> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> {{user.email}} <!--<img class="profile-picture" src="{{user.picture}}"/>--> </a> <ul class="dropdown-menu"> <li><a href="{{user.link}}" target="_blank">Profile</a></li> </ul> </li> </ul> </div> </div> </div> <div ng-view></div> <div id="editor" ace-editor></div> <alert id="error"></alert>
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Views/Drive/Index.cshtml
HTML+Razor
asf20
869
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Error</title> </head> <body> <h2> Sorry, an error occurred while processing your request. </h2> </body> </html>
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Views/Shared/Error.cshtml
HTML+Razor
asf20
210
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>@ViewBag.Title</title> <link href="@Url.Content("~/Content/css/bootstrap.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/css/font-awesome.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/css/bootstrap-responsive.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/css/app.css")" rel="stylesheet" type="text/css" /> <script src="https://www.google.com/jsapi" charset="utf-8"></script> <script src="https://apis.google.com/js/api.js"></script> <script src="@Url.Content("~/Scripts/jquery/jquery-1.7.2.min.js")"></script> <script src="@Url.Content("~/Scripts/ace/ace.js")"></script> <script src="@Url.Content("~/Scripts/bootstrap/bootstrap.js")"></script> <script src="@Url.Content("~/Scripts/angular-1.0.0/angular-1.0.0.js")"></script> <script src="@Url.Content("~/Scripts/app.js")"></script> <script src="@Url.Content("~/Scripts/services.js")"></script> <script src="@Url.Content("~/Scripts/controllers.js")"></script> <script src="@Url.Content("~/Scripts/filters.js")"></script> <script src="@Url.Content("~/Scripts/directives.js")"></script> </head> <body ng-cloak ng-app="app"> @RenderBody() </body> </html>
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Views/Shared/_Layout.cshtml
HTML+Razor
asf20
1,335
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Data.Entity; using DrEdit.Models; namespace DrEdit { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "svc", // Route name "svc", // URL with parameters new { controller = "svc", action = "svc" } // Parameter defaults ); routes.MapRoute( "user", // Route name "user", // URL with parameters new { controller = "user", action = "user" } // Parameter defaults ); routes.MapRoute( "about", // Route name "about", // URL with parameters new { controller = "about", action = "about" } // Parameter defaults ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Drive", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { // Database initializer to support changes in the model Database.SetInitializer<StoredCredentialsDBContext>(new StoredCredentialsInitializer()); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } }
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Global.asax.cs
C#
asf20
2,666
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DrEdit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DrEdit")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d77af74b-0ab2-48c4-a557-16950231bd7b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Properties/AssemblyInfo.cs
C#
asf20
1,982
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Google.Apis.Authentication; using Google.Apis.Drive.v2; using DrEdit.Models; using Google.Apis.Oauth2.v2.Data; namespace DrEdit.Controllers { public class userController : Controller { // // GET: /user public JsonResult user() { IAuthenticator authenticator = Session["authenticator"] as IAuthenticator; Userinfo userInfo = Utils.GetUserInfo(authenticator); JsonResult result = Json(new { email = userInfo.Email, link = userInfo.Link, picture = userInfo.Picture }); result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return result; } } }
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Controllers/userController.cs
C#
asf20
1,413
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using DrEdit.Models; using Google.Apis.Drive.v2; using Google.Apis.Authentication; namespace DrEdit.Controllers { public class DriveController : Controller { // // GET: /Drive public ActionResult Index(string state, string code) { try { IAuthenticator authenticator = Utils.GetCredentials(code, state); // Store the authenticator and the authorized service in session Session["authenticator"] = authenticator; Session["service"] = Utils.BuildService(authenticator); } catch (CodeExchangeException) { if (Session["service"] == null || Session["authenticator"] == null) { Response.Redirect(Utils.GetAuthorizationUrl("", state)); } } catch (NoRefreshTokenException e) { Response.Redirect(e.AuthorizationUrl); } DriveState driveState = new DriveState(); if (!string.IsNullOrEmpty(state)) { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); driveState = jsonSerializer.Deserialize<DriveState>(state); } if (driveState.action == "open") { return OpenWith(driveState); } else { return CreateNew(driveState); } } private ActionResult OpenWith(DriveState state) { ViewBag.FileIds = state.ids; return View(); } private ActionResult CreateNew(DriveState state) { ViewBag.FileIds = new string[] {""}; return View(); } } }
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Controllers/DriveController.cs
C#
asf20
2,643
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Google.Apis.Authentication; using Google.Apis.Drive.v2; using DrEdit.Models; namespace DrEdit.Controllers { public class svcController : Controller { // // GET: /svc public JsonResult svc(string file_id) { if (string.IsNullOrWhiteSpace(file_id)) { return Json(null, JsonRequestBehavior.AllowGet); } IAuthenticator authenticator = Session["authenticator"] as IAuthenticator; DriveService service = Session["service"] as DriveService; if (authenticator == null || service == null) { // redirect user to authentication } Google.Apis.Drive.v2.Data.File file = service.Files.Get(file_id).Fetch(); string data = Utils.DownloadFile(authenticator, file.DownloadUrl); DriveFile df = new DriveFile(file, data); return Json(df, JsonRequestBehavior.AllowGet); } // // POST: /svc [HttpPost, ActionName("svc")] public JsonResult svcPost(string title, string description, string mimeType, string content) { IAuthenticator authenticator = Session["authenticator"] as IAuthenticator; DriveService service = Session["service"] as DriveService; if (authenticator == null || service == null) { // redirect user to authentication } Google.Apis.Drive.v2.Data.File file = Utils.InsertResource(service, authenticator, title, description, mimeType, content); return Json(file.Id); } // // PUT: /svc [HttpPut, ActionName("svc")] public JsonResult svcPut(string title, string description, string mimeType, string content, string resource_id, bool newRevision) { IAuthenticator authenticator = Session["authenticator"] as IAuthenticator; DriveService service = Session["service"] as DriveService; if (authenticator == null || service == null) { // redirect user to authentication } Google.Apis.Drive.v2.Data.File file; if (string.IsNullOrWhiteSpace(resource_id)) { file = Utils.InsertResource(service, authenticator, title, description, mimeType, content); } else { file = Utils.UpdateResource(service, authenticator, resource_id, title, description, mimeType, content, newRevision); } return Json(file.Id); } } }
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Controllers/svcController.cs
C#
asf20
3,429
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Google.Apis.Authentication; using Google.Apis.Drive.v2; using DrEdit.Models; namespace DrEdit.Controllers { public class aboutController : Controller { // // GET: /about public JsonResult about() { DriveService service = Session["service"] as DriveService; if (service == null) { // redirect user to authentication } Google.Apis.Drive.v2.Data.About about = service.About.Get().Fetch(); JsonResult result = Json(new { quotaBytesTotal = about.QuotaBytesTotal, quotaBytesUsed = about.QuotaBytesUsed }); result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return result; } } }
zzangtest123-google-drive-sdk-samples
dotnet/DrEdit/Controllers/aboutController.cs
C#
asf20
1,507
#!/usr/bin/python # # Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'afshar@google.com (Ali Afshar)' import os import httplib2 import sessions from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build_from_document from apiclient.http import MediaUpload from oauth2client import client from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json APIS_BASE = 'https://www.googleapis.com' ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') CODE_PARAMETER = 'code' STATE_PARAMETER = 'state' SESSION_SECRET = open('session.secret').read() DRIVE_DISCOVERY_DOC = open('drive.json').read() USERS_DISCOVERY_DOC = open('users.json').read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials.""" credentials = CredentialsProperty() def CreateOAuthFlow(request): """Create OAuth2.0 flow controller Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = client.flow_from_clientsecrets('client-debug.json', scope='') flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/') return flow def GetCodeCredentials(request): """Create OAuth2.0 credentials by extracting a code and performing OAuth2.0. Args: request: HTTP request used for extracting an authorization code. Returns: OAuth2.0 credentials suitable for authorizing clients. """ code = request.get(CODE_PARAMETER) if code: oauth_flow = CreateOAuthFlow(request) creds = oauth_flow.step2_exchange(code) users_service = CreateService(USERS_DISCOVERY_DOC, creds) userid = users_service.userinfo().get().execute().get('id') request.session.set_secure_cookie(name='userid', value=userid) StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(request): """Get OAuth2.0 credentials for an HTTP session. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ userid = request.session.get_secure_cookie(name='userid') if userid: creds = StorageByKeyName(Credentials, userid, 'credentials').get() if creds and not creds.invalid: return creds def CreateService(discovery_doc, creds): """Create a Google API service. Args: discovery_doc: Discovery doc used to configure service. creds: Credentials used to authorize service. Returns: Authorized Google API service. """ http = httplib2.Http() creds.authorize(http) return build_from_document(discovery_doc, APIS_BASE, http=http) def RedirectAuth(handler): """Redirect a handler to an authorization page. Args: handler: webapp.RequestHandler to redirect. """ flow = CreateOAuthFlow(handler.request) flow.scope = ALL_SCOPES uri = flow.step1_get_authorize_url(flow.redirect_uri) handler.redirect(uri) def CreateDrive(handler): """Create a fully authorized drive service for this handler. Args: handler: RequestHandler from which drive service is generated. Returns: Authorized drive service, generated from the handler request. """ request = handler.request request.session = sessions.LilCookies(handler, SESSION_SECRET) creds = GetCodeCredentials(request) or GetSessionCredentials(request) if creds: return CreateService(DRIVE_DISCOVERY_DOC, creds) else: RedirectAuth(handler) def ServiceEnabled(view): """Decorator to inject an authorized service into an HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) response_data = view(handler, service) handler.response.headers['Content-Type'] = 'text/html' handler.response.out.write(response_data) return ServiceDecoratedView def ServiceEnabledJson(view): """Decorator to inject an authorized service into a JSON HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) if handler.request.body: data = json.loads(handler.request.body) else: data = None response_data = json.dumps(view(handler, service, data)) handler.response.headers['Content-Type'] = 'application/json' handler.response.out.write(response_data) return ServiceDecoratedView class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): self.ParseState(state) @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get(STATE_PARAMETER)) def ParseState(self, state): """Parse a state parameter and set internal values. Args: state: State parameter to parse. """ if state.startswith('{'): self.ParseJsonState(state) else: self.ParsePlainState(state) def ParseJsonState(self, state): """Parse a state parameter that is JSON. Args: state: State parameter to parse """ state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) def ParsePlainState(self, state): """Parse a state parameter that is a plain resource id or missing. Args: state: State parameter to parse """ if state: self.action = 'open' self.ids = [state] else: self.action = 'create' self.ids = [] class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] def RenderTemplate(name, **context): """Render a named template in a context. Args: name: Template name. context: Keyword arguments to render as template variables. """ return template.render(name, context)
zzangtest123-google-drive-sdk-samples
python/utils.py
Python
asf20
8,523
'use strict'; var EditorState = { CLEAN:0, // NO CHANGES DIRTY:1, // UNSAVED CHANGES SAVE:2, // SAVE IN PROGRESS LOAD:3, // LOADING READONLY:4 }; google.load('picker', '1'); //gapi.load('drive-share'); angular.module('app', ['app.filters', 'app.services', 'app.directives']) .constant('saveInterval', 15000) .constant('appId', [[YOUR_APP_ID]]) // Please replace this with your Application ID. .config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/edit/:id', {templateUrl:'partials/editor.html', controller:EditorCtrl}) .otherwise({redirectTo:'/edit/'}); }]);
zzangtest123-google-drive-sdk-samples
python/static/js/app.js
JavaScript
asf20
638
'use strict'; function UserCtrl($scope, backend) { $scope.user = null; $scope.login = function () { backend.user().then(function (response) { $scope.user = response.data; }); } $scope.login(); } function EditorCtrl($scope, $location, $routeParams, $timeout, editor, doc, autosaver) { console.log($routeParams); $scope.editor = editor; $scope.doc = doc; $scope.$on('saved', function (event) { $location.path('/edit/' + doc.resource_id); }); if ($routeParams.id) { editor.load($routeParams.id); } else { // New doc, but defer to next event cycle to ensure init $timeout(function () { editor.create(); }, 1); } } function ShareCtrl($scope, appId, doc) { /* var client = gapi.drive.share.ShareClient(appId); $scope.enabled = function() { return doc.resource_id != null; }; $scope.share = function() { client.setItemIds([doc.resource_id]); client.showSharingSettings(); } */ } function MenuCtrl($scope, $location, appId) { var onFilePicked = function (data) { $scope.$apply(function () { if (data.action == 'picked') { var id = data.docs[0].id; $location.path('/edit/' + id); } }); }; $scope.open = function () { var view = new google.picker.View(google.picker.ViewId.DOCS); view.setMimeTypes('text/plain'); var picker = new google.picker.PickerBuilder() .setAppId(appId) .addView(view) .setCallback(angular.bind(this, onFilePicked)) .build(); picker.setVisible(true); }; $scope.create = function () { this.editor.create(); }; $scope.save = function () { this.editor.save(true); } } function RenameCtrl($scope, doc) { $('#rename-dialog').on('show', function () { $scope.$apply(function () { $scope.newFileName = doc.info.title; }); }); $scope.save = function () { doc.info.title = $scope.newFileName; $('#rename-dialog').modal('hide'); }; } function AboutCtrl($scope, backend) { $('#about-dialog').on('show', function () { backend.about().then(function (result) { $scope.info = result.data; }); }); }
zzangtest123-google-drive-sdk-samples
python/static/js/controllers.js
JavaScript
asf20
2,458
'use strict'; /* Filters */ angular.module('app.filters', []) .filter('saveStateFormatter', function () { return function (state) { if (state == EditorState.DIRTY) { return 'You have unsaved changes'; } else if (state == EditorState.SAVE) { return 'Saving...'; } else if (state == EditorState.LOAD) { return 'Loading...'; } else if (state == EditorState.READONLY) { return "Read only" } else { return 'All changes saved'; } }; }) .filter('bytes', function () { return function (bytes) { bytes = parseInt(bytes); if (isNaN(bytes)) { return "..."; } var units = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB']; var p = bytes > 0 ? Math.floor(Math.log(bytes) / Math.LN2 / 10) : 0; var u = Math.round(bytes / Math.pow(2, 10 * p)); return u + units[p]; } });
zzangtest123-google-drive-sdk-samples
python/static/js/filters.js
JavaScript
asf20
1,084
'use strict'; var module = angular.module('app.services', []); var ONE_HOUR_IN_MS = 1000 * 60 * 60; // Shared model for current document module.factory('doc', function ($rootScope) { var service = $rootScope.$new(true); service.dirty = false; service.lastSave = 0; service.timeSinceLastSave = function () { return new Date().getTime() - this.lastSave; }; service.$watch('info', function (newValue, oldValue) { if (oldValue != null && newValue === oldValue) { service.dirty = true; } }, true); return service; }); module.factory('editor', function (doc, backend, $q, $rootScope, $log) { var editor = null; var EditSession = require("ace/edit_session").EditSession; var service = { loading:false, saving:false, rebind:function (element) { editor = ace.edit(element); }, snapshot:function () { doc.dirty = false; var data = angular.extend({}, doc.info); data.resource_id = doc.resource_id; if (doc.info.editable) { data.content = editor.getSession().getValue(); } return data; }, create:function () { $log.info("Creating new doc"); this.updateEditor({ content:'', labels:{ starred:false }, editable:true, title:'Untitled document', description:'', mimeType:'text/plain', resource_id:null }); }, load:function (id, reload) { $log.info("Loading resource", id, doc.resource_id); if (!reload && doc.info && id == doc.resource_id) { return $q.when(doc.info); } this.loading = true; return backend.load(id).then(angular.bind(this, function (result) { this.loading = false; this.updateEditor(result.data); $rootScope.$broadcast('loaded', doc.info); return result; }), angular.bind(this, function (result) { $log.warn("Error loading", result); this.loading = false; $rootScope.$broadcast('error', { action:'load', message:"An error occured while loading the file" }); return result; })); }, save:function (newRevision) { $log.info("Saving file", newRevision); if (this.saving || this.loading) { throw 'Save called from incorrect state'; } this.saving = true; var file = this.snapshot(); // Force revision if first save of the session newRevision = newRevision || doc.timeSinceLastSave() > ONE_HOUR_IN_MS; var promise = backend.save(file, newRevision); promise.then(angular.bind(this, function (result) { $log.info("Saved file", result); this.saving = false; doc.resource_id = result.data; doc.lastSave = new Date().getTime(); $rootScope.$broadcast('saved', doc.info); return doc.info; }), angular.bind(this, function (result) { this.saving = false; doc.dirty = true; $rootScope.$broadcast('error', { action:'save', message:"An error occured while saving the file" }); return result; })); return promise; }, updateEditor:function (fileInfo) { $log.info("Updating editor", fileInfo); var session = new EditSession(fileInfo.content); session.on('change', function () { doc.dirty = true; $rootScope.$apply(); }); fileInfo.content = null; doc.lastSave = 0; doc.info = fileInfo; doc.resource_id = fileInfo.id; editor.setSession(session); editor.setReadOnly(!doc.info.editable); editor.focus(); }, state:function () { if (this.loading) { return EditorState.LOAD; } else if (this.saving) { return EditorState.SAVE; } else if (doc.dirty) { return EditorState.DIRTY; } else if (!doc.info.editable) { return EditorState.READONLY; } return EditorState.CLEAN; } }; return service; }); module.factory('backend', function ($http, $log) { var jsonTransform = function (data, headers) { return angular.fromJson(data); }; var service = { user:function () { return $http.get('/user', {transformResponse:jsonTransform}); }, about:function () { return $http.get('/about', {transformResponse:jsonTransform}); }, load:function (id) { return $http.get('/svc', { transformResponse:jsonTransform, params:{ 'file_id':id } }); }, save:function (fileInfo, newRevision) { $log.info('Saving', fileInfo); return $http({ url:'/svc', method:fileInfo.resource_id ? 'PUT' : 'POST', headers:{ 'Content-Type':'application/json' }, params:{ 'newRevision':newRevision }, transformResponse:jsonTransform, data:JSON.stringify(fileInfo) }); } }; return service; }); module.factory('autosaver', function (editor, saveInterval, $timeout) { var saveFn = function () { if (editor.state() == EditorState.DIRTY) { editor.save(false); } }; var createTimeout = function () { return $timeout(saveFn, saveInterval).then(createTimeout); } return createTimeout(); });
zzangtest123-google-drive-sdk-samples
python/static/js/services.js
JavaScript
asf20
7,161
'use strict'; var module = angular.module('app.directives', []); module.directive('aceEditor', function (editor) { return { retrict:'A', link:function (scope, element) { editor.rebind(element[0]); } }; }); module.directive('star', function () { return { restrict:'E', replace:true, scope:{ val:'=value', // Value bound to eventFn:'&click' // Optional expression evaluated on click }, link:function (scope, element) { element.bind('click', function () { scope.$apply(function () { scope.val = !scope.val; }); scope.$eval(scope.eventFn, scope.val); }); }, template:'<i class="star" ng-class="{\'icon-star\' : val, \'icon-star-empty\' : !val}" ng-click="toggle()"></i>' } }); module.directive('alert', function ($rootScope) { return { restrict:'E', replace:true, link:function (scope, element) { $rootScope.$on('error', function (event, data) { scope.message = data.message; element.show(); }); scope.close = function () { element.hide(); }; }, template:'<div class="hide alert alert-error">' + ' <span class="close" ng-click="close()">×</span>' + ' {{message}}' + '</div>' } })
zzangtest123-google-drive-sdk-samples
python/static/js/directives.js
JavaScript
asf20
1,774
<div class="container-fluid"> <div id="doc-bar" class="row-fluid"> <span class="span4"> <h3 ng-show="doc.info.editable" class="doc-title" data-toggle="modal" href="#rename-dialog">{{doc.info.title}}</h3> <h3 ng-hide="doc.info.editable" class="doc-title">{{doc.info.title}}</h3> <star value="doc.info.labels.starred" click="editor.dirty(true)"></star></span> <span class="span4">{{editor.state() | saveStateFormatter }}</span> <span class="span4" ng-controller="ShareCtrl"><a class="btn pull-right" href click="share"> Share</a></span> </div> <div class="navbar subnav"> <ul ng-controller="MenuCtrl" class="nav"> <li class="dropdown"> <a href class="dropdown-toggle" data-toggle="dropdown"> File <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a target="_blank" href="#/edit">New</a></li> <li><a ng-click="open()" href>Open</a></li> <li> <a ng-show="doc.info.editable" data-toggle="modal" href="#rename-dialog">Rename</a> <span ng-hide="doc.info.editable">Rename</span> </li> <li><a ng-click="save()" href>Save</a></li> </ul> </li> <li><a href="#about-dialog" data-toggle="modal">About</a></li> </ul> </div> </div> <div class="modal hide" id="rename-dialog" ng-controller="RenameCtrl"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h3>Rename File</h3> </div> <div class="modal-body"> <form> <label>Enter a new file name:</label> <input type="text" ng-model="newFileName" autofocus required/> </form> </div> <div class="modal-footer"> <a href class="btn" data-dismiss="modal">Cancel</a> <a href ng-click="save()" class="btn btn-primary">Save</a> </div> </div> <div class="modal hide" id="about-dialog" ng-controller="AboutCtrl"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h3>About</h3> </div> <div class="modal-body"> <div><b>Total Drive Quota:</b> {{info.quotaBytesTotal | bytes}}</div> <div><b>Drive Quota Used:</b> {{info.quotaBytesUsed | bytes}}</div> </div> <div class="modal-footer"> <a href class="btn btn-primary" data-dismiss="modal">Close</a> </div> </div>
zzangtest123-google-drive-sdk-samples
python/static/partials/editor.html
HTML
asf20
2,381
/* app css stylesheet */ #editor { position: absolute; top: 120px; bottom: 0px; left: 0px; right: 0px; } #doc-bar { line-height: 27px; } .doc-title { display:inline; padding-right: 12px; } .star { font-size: 22px; color: black; } .icon-star { color: yellow; -webkit-text-stroke: 1px black; } .profile-picture { width: 22px; } #error { position: absolute; bottom: 10px; right: 10px; } body { height: 100%; } .subnav { margin-bottom: 0px; } .subnav .nav > li > a { color: #333; padding-top: 2px; padding-bottom: 2px; } .subnav .nav > li > a:hover { background-color: #F5F5F5; color: #333; } .dropdown-menu span { display: block; padding: 3px 15px; clear: both; font-weight: normal; line-height: 18px; color: #333333; white-space: nowrap; }
zzangtest123-google-drive-sdk-samples
python/static/css/app.css
CSS
asf20
792
/** * @license AngularJS v1.0.0 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; var directive = {}; var service = { value: {} }; var DEPENDENCIES = { 'angular.js': 'http://code.angularjs.org/angular-' + angular.version.full + '.min.js', 'angular-resource.js': 'http://code.angularjs.org/angular-resource-' + angular.version.full + '.min.js', 'angular-sanitize.js': 'http://code.angularjs.org/angular-sanitize-' + angular.version.full + '.min.js', 'angular-cookies.js': 'http://code.angularjs.org/angular-cookies-' + angular.version.full + '.min.js' }; function escape(text) { return text. replace(/\&/g, '&amp;'). replace(/\</g, '&lt;'). replace(/\>/g, '&gt;'). replace(/"/g, '&quot;'); } /** * http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie * http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript */ function setHtmlIe8SafeWay(element, html) { var newElement = angular.element('<pre>' + html + '</pre>'); element.html(''); element.append(newElement.contents()); return element; } directive.jsFiddle = function(getEmbeddedTemplate, escape, script) { return { terminal: true, link: function(scope, element, attr) { var name = '', stylesheet = '<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">\n', fields = { html: '', css: '', js: '' }; angular.forEach(attr.jsFiddle.split(' '), function(file, index) { var fileType = file.split('.')[1]; if (fileType == 'html') { if (index == 0) { fields[fileType] += '<div ng-app' + (attr.module ? '="' + attr.module + '"' : '') + '>\n' + getEmbeddedTemplate(file, 2); } else { fields[fileType] += '\n\n\n <!-- CACHE FILE: ' + file + ' -->\n' + ' <script type="text/ng-template" id="' + file + '">\n' + getEmbeddedTemplate(file, 4) + ' </script>\n'; } } else { fields[fileType] += getEmbeddedTemplate(file) + '\n'; } }); fields.html += '</div>\n'; setHtmlIe8SafeWay(element, '<form class="jsfiddle" method="post" action="http://jsfiddle.net/api/post/library/pure/" target="_blank">' + hiddenField('title', 'AngularJS Example: ' + name) + hiddenField('css', '</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> \n' + stylesheet + script.angular + (attr.resource ? script.resource : '') + '<style>\n' + fields.css) + hiddenField('html', fields.html) + hiddenField('js', fields.js) + '<button class="btn btn-primary"><i class="icon-white icon-pencil"></i> Edit Me</button>' + '</form>'); function hiddenField(name, value) { return '<input type="hidden" name="' + name + '" value="' + escape(value) + '">'; } } } }; directive.code = function() { return {restrict: 'E', terminal: true}; }; directive.prettyprint = ['reindentCode', function(reindentCode) { return { restrict: 'C', terminal: true, compile: function(element) { element.html(window.prettyPrintOne(reindentCode(element.html()), undefined, true)); } }; }]; directive.ngSetText = ['getEmbeddedTemplate', function(getEmbeddedTemplate) { return { restrict: 'CA', priority: 10, compile: function(element, attr) { setHtmlIe8SafeWay(element, escape(getEmbeddedTemplate(attr.ngSetText))); } } }] directive.ngHtmlWrap = ['reindentCode', 'templateMerge', function(reindentCode, templateMerge) { return { compile: function(element, attr) { var properties = { head: '', module: '', body: element.text() }, html = "<!doctype html>\n<html ng-app{{module}}>\n <head>\n{{head:4}} </head>\n <body>\n{{body:4}} </body>\n</html>"; angular.forEach((attr.ngHtmlWrap || '').split(' '), function(dep) { if (!dep) return; dep = DEPENDENCIES[dep] || dep; var ext = dep.split(/\./).pop(); if (ext == 'css') { properties.head += '<link rel="stylesheet" href="' + dep + '" type="text/css">\n'; } else if(ext == 'js') { properties.head += '<script src="' + dep + '"></script>\n'; } else { properties.module = '="' + dep + '"'; } }); setHtmlIe8SafeWay(element, escape(templateMerge(html, properties))); } } }]; directive.ngSetHtml = ['getEmbeddedTemplate', function(getEmbeddedTemplate) { return { restrict: 'CA', priority: 10, compile: function(element, attr) { setHtmlIe8SafeWay(element, getEmbeddedTemplate(attr.ngSetHtml)); } } }]; directive.ngEvalJavascript = ['getEmbeddedTemplate', function(getEmbeddedTemplate) { return { compile: function (element, attr) { var script = getEmbeddedTemplate(attr.ngEvalJavascript); try { if (window.execScript) { // IE window.execScript(script || '""'); // IE complains when evaling empty string } else { window.eval(script); } } catch (e) { if (window.console) { window.console.log(script, '\n', e); } else { window.alert(e); } } } }; }]; directive.ngEmbedApp = ['$templateCache', '$browser', '$rootScope', '$location', function($templateCache, $browser, docsRootScope, $location) { return { terminal: true, link: function(scope, element, attrs) { var modules = []; modules.push(['$provide', function($provide) { $provide.value('$templateCache', $templateCache); $provide.value('$anchorScroll', angular.noop); $provide.value('$browser', $browser); $provide.provider('$location', function() { this.$get = ['$rootScope', function($rootScope) { docsRootScope.$on('$locationChangeSuccess', function(event, oldUrl, newUrl) { $rootScope.$broadcast('$locationChangeSuccess', oldUrl, newUrl); }); return $location; }]; this.html5Mode = angular.noop; }); $provide.decorator('$timeout', ['$rootScope', '$delegate', function($rootScope, $delegate) { return angular.extend(function(fn, delay) { if (delay && delay > 50) { return setTimeout(function() { $rootScope.$apply(fn); }, delay); } else { return $delegate.apply(this, arguments); } }, $delegate); }]); $provide.decorator('$rootScope', ['$delegate', function(embedRootScope) { docsRootScope.$watch(function() { embedRootScope.$digest(); }); return embedRootScope; }]); }]); if (attrs.ngEmbedApp) modules.push(attrs.ngEmbedApp); element.bind('click', function(event) { if (event.target.attributes.getNamedItem('ng-click')) { event.preventDefault(); } }); angular.bootstrap(element, modules); } }; }]; service.reindentCode = function() { return function (text, spaces) { if (!text) return text; var lines = text.split(/\r?\n/); var prefix = ' '.substr(0, spaces || 0); var i; // remove any leading blank lines while (lines.length && lines[0].match(/^\s*$/)) lines.shift(); // remove any trailing blank lines while (lines.length && lines[lines.length - 1].match(/^\s*$/)) lines.pop(); var minIndent = 999; for (i = 0; i < lines.length; i++) { var line = lines[0]; var reindentCode = line.match(/^\s*/)[0]; if (reindentCode !== line && reindentCode.length < minIndent) { minIndent = reindentCode.length; } } for (i = 0; i < lines.length; i++) { lines[i] = prefix + lines[i].substring(minIndent); } lines.push(''); return lines.join('\n'); } }; service.templateMerge = ['reindentCode', function(indentCode) { return function(template, properties) { return template.replace(/\{\{(\w+)(?:\:(\d+))?\}\}/g, function(_, key, indent) { var value = properties[key]; if (indent) { value = indentCode(value, indent); } return value == undefined ? '' : value; }); }; }]; service.getEmbeddedTemplate = ['reindentCode', function(reindentCode) { return function (id) { var element = document.getElementById(id); if (!element) { return null; } return reindentCode(angular.element(element).html(), 0); } }]; angular.module('bootstrapPrettify', []).directive(directive).factory(service); // Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * * <p> * For a fairly comprehensive set of languages see the * <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a> * file that came with this source. At a minimum, the lexer should work on a * number of languages including C and friends, Java, Python, Bash, SQL, HTML, * XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk * and a subset of Perl, but, because of commenting conventions, doesn't work on * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class. * <p> * Usage: <ol> * <li> include this source file in an html page via * {@code <script type="text/javascript" src="/path/to/prettify.js"></script>} * <li> define style rules. See the example page for examples. * <li> mark the {@code <pre>} and {@code <code>} tags in your source with * {@code class=prettyprint.} * You can also use the (html deprecated) {@code <xmp>} tag, but the pretty * printer needs to do more substantial DOM manipulations to support that, so * some css styles may not be preserved. * </ol> * That's it. I wanted to keep the API as simple as possible, so there's no * need to specify which language the code is in, but if you wish, you can add * another class to the {@code <pre>} or {@code <code>} element to specify the * language, as in {@code <pre class="prettyprint lang-java">}. Any class that * starts with "lang-" followed by a file extension, specifies the file type. * See the "lang-*.js" files in this directory for code that implements * per-language file handlers. * <p> * Change log:<br> * cbeust, 2006/08/22 * <blockquote> * Java annotations (start with "@") are now captured as literals ("lit") * </blockquote> * @requires console */ // JSLint declarations /*global console, document, navigator, setTimeout, window, define */ /** * Split {@code prettyPrint} into multiple timeouts so as not to interfere with * UI events. * If set to {@code false}, {@code prettyPrint()} is synchronous. */ window['PR_SHOULD_USE_CONTINUATION'] = true; /** * Find all the {@code <pre>} and {@code <code>} tags in the DOM with * {@code class=prettyprint} and prettify them. * * @param {Function?} opt_whenDone if specified, called when the last entry * has been finished. */ var prettyPrintOne; /** * Pretty print a chunk of code. * * @param {string} sourceCodeHtml code as html * @return {string} code as html, but prettier */ var prettyPrint; (function () { var win = window; // Keyword lists for various languages. // We use things that coerce to strings to make them compact when minified // and to defeat aggressive optimizers that fold large string constants. var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"]; var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," + "double,enum,extern,float,goto,int,long,register,short,signed,sizeof," + "static,struct,switch,typedef,union,unsigned,void,volatile"]; var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," + "new,operator,private,protected,public,this,throw,true,try,typeof"]; var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," + "concept,concept_map,const_cast,constexpr,decltype," + "dynamic_cast,explicit,export,friend,inline,late_check," + "mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast," + "template,typeid,typename,using,virtual,where"]; var JAVA_KEYWORDS = [COMMON_KEYWORDS, "abstract,boolean,byte,extends,final,finally,implements,import," + "instanceof,null,native,package,strictfp,super,synchronized,throws," + "transient"]; var CSHARP_KEYWORDS = [JAVA_KEYWORDS, "as,base,by,checked,decimal,delegate,descending,dynamic,event," + "fixed,foreach,from,group,implicit,in,interface,internal,into,is,let," + "lock,object,out,override,orderby,params,partial,readonly,ref,sbyte," + "sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort," + "var,virtual,where"]; var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," + "for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," + "throw,true,try,unless,until,when,while,yes"; var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS, "debugger,eval,export,function,get,null,set,undefined,var,with," + "Infinity,NaN"]; var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," + "goto,if,import,last,local,my,next,no,our,print,package,redo,require," + "sub,undef,unless,until,use,wantarray,while,BEGIN,END"; var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," + "elif,except,exec,finally,from,global,import,in,is,lambda," + "nonlocal,not,or,pass,print,raise,try,with,yield," + "False,True,None"]; var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," + "def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," + "rescue,retry,self,super,then,true,undef,unless,until,when,yield," + "BEGIN,END"]; var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," + "function,in,local,set,then,until"]; var ALL_KEYWORDS = [ CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS + PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS]; var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/; // token style names. correspond to css classes /** * token style for a string literal * @const */ var PR_STRING = 'str'; /** * token style for a keyword * @const */ var PR_KEYWORD = 'kwd'; /** * token style for a comment * @const */ var PR_COMMENT = 'com'; /** * token style for a type * @const */ var PR_TYPE = 'typ'; /** * token style for a literal value. e.g. 1, null, true. * @const */ var PR_LITERAL = 'lit'; /** * token style for a punctuation string. * @const */ var PR_PUNCTUATION = 'pun'; /** * token style for plain text. * @const */ var PR_PLAIN = 'pln'; /** * token style for an sgml tag. * @const */ var PR_TAG = 'tag'; /** * token style for a markup declaration such as a DOCTYPE. * @const */ var PR_DECLARATION = 'dec'; /** * token style for embedded source. * @const */ var PR_SOURCE = 'src'; /** * token style for an sgml attribute name. * @const */ var PR_ATTRIB_NAME = 'atn'; /** * token style for an sgml attribute value. * @const */ var PR_ATTRIB_VALUE = 'atv'; /** * A class that indicates a section of markup that is not code, e.g. to allow * embedding of line numbers within code listings. * @const */ var PR_NOCODE = 'nocode'; /** * A set of tokens that can precede a regular expression literal in * javascript * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html * has the full list, but I've removed ones that might be problematic when * seen in languages that don't support regular expression literals. * * <p>Specifically, I've removed any keywords that can't precede a regexp * literal in a syntactically legal javascript program, and I've removed the * "in" keyword since it's not a keyword in many languages, and might be used * as a count of inches. * * <p>The link above does not accurately describe EcmaScript rules since * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works * very well in practice. * * @private * @const */ var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*'; // CAVEAT: this does not properly handle the case where a regular // expression immediately follows another since a regular expression may // have flags for case-sensitivity and the like. Having regexp tokens // adjacent is not valid in any language I'm aware of, so I'm punting. // TODO: maybe style special characters inside a regexp as punctuation. /** * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally * matches the union of the sets of strings matched by the input RegExp. * Since it matches globally, if the input strings have a start-of-input * anchor (/^.../), it is ignored for the purposes of unioning. * @param {Array.<RegExp>} regexs non multiline, non-global regexs. * @return {RegExp} a global regex. */ function combinePrefixPatterns(regexs) { var capturedGroupIndex = 0; var needToFoldCase = false; var ignoreCase = false; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.ignoreCase) { ignoreCase = true; } else if (/[a-z]/i.test(regex.source.replace( /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) { needToFoldCase = true; ignoreCase = false; break; } } var escapeCharToCodeUnit = { 'b': 8, 't': 9, 'n': 0xa, 'v': 0xb, 'f': 0xc, 'r': 0xd }; function decodeEscape(charsetPart) { var cc0 = charsetPart.charCodeAt(0); if (cc0 !== 92 /* \\ */) { return cc0; } var c1 = charsetPart.charAt(1); cc0 = escapeCharToCodeUnit[c1]; if (cc0) { return cc0; } else if ('0' <= c1 && c1 <= '7') { return parseInt(charsetPart.substring(1), 8); } else if (c1 === 'u' || c1 === 'x') { return parseInt(charsetPart.substring(2), 16); } else { return charsetPart.charCodeAt(1); } } function encodeEscape(charCode) { if (charCode < 0x20) { return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16); } var ch = String.fromCharCode(charCode); return (ch === '\\' || ch === '-' || ch === ']' || ch === '^') ? "\\" + ch : ch; } function caseFoldCharset(charSet) { var charsetParts = charSet.substring(1, charSet.length - 1).match( new RegExp( '\\\\u[0-9A-Fa-f]{4}' + '|\\\\x[0-9A-Fa-f]{2}' + '|\\\\[0-3][0-7]{0,2}' + '|\\\\[0-7]{1,2}' + '|\\\\[\\s\\S]' + '|-' + '|[^-\\\\]', 'g')); var ranges = []; var inverse = charsetParts[0] === '^'; var out = ['[']; if (inverse) { out.push('^'); } for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) { var p = charsetParts[i]; if (/\\[bdsw]/i.test(p)) { // Don't muck with named groups. out.push(p); } else { var start = decodeEscape(p); var end; if (i + 2 < n && '-' === charsetParts[i + 1]) { end = decodeEscape(charsetParts[i + 2]); i += 2; } else { end = start; } ranges.push([start, end]); // If the range might intersect letters, then expand it. // This case handling is too simplistic. // It does not deal with non-latin case folding. // It works for latin source code identifiers though. if (!(end < 65 || start > 122)) { if (!(end < 65 || start > 90)) { ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]); } if (!(end < 97 || start > 122)) { ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]); } } } } // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]] // -> [[1, 12], [14, 14], [16, 17]] ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); }); var consolidatedRanges = []; var lastRange = []; for (var i = 0; i < ranges.length; ++i) { var range = ranges[i]; if (range[0] <= lastRange[1] + 1) { lastRange[1] = Math.max(lastRange[1], range[1]); } else { consolidatedRanges.push(lastRange = range); } } for (var i = 0; i < consolidatedRanges.length; ++i) { var range = consolidatedRanges[i]; out.push(encodeEscape(range[0])); if (range[1] > range[0]) { if (range[1] + 1 > range[0]) { out.push('-'); } out.push(encodeEscape(range[1])); } } out.push(']'); return out.join(''); } function allowAnywhereFoldCaseAndRenumberGroups(regex) { // Split into character sets, escape sequences, punctuation strings // like ('(', '(?:', ')', '^'), and runs of characters that do not // include any of the above. var parts = regex.source.match( new RegExp( '(?:' + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set + '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape + '|\\\\x[A-Fa-f0-9]{2}' // a hex escape + '|\\\\[0-9]+' // a back-reference or octal escape + '|\\\\[^ux0-9]' // other escape sequence + '|\\(\\?[:!=]' // start of a non-capturing group + '|[\\(\\)\\^]' // start/end of a group, or line start + '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters + ')', 'g')); var n = parts.length; // Maps captured group numbers to the number they will occupy in // the output or to -1 if that has not been determined, or to // undefined if they need not be capturing in the output. var capturedGroups = []; // Walk over and identify back references to build the capturedGroups // mapping. for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { // groups are 1-indexed, so max group index is count of '(' ++groupIndex; } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue) { if (decimalValue <= groupIndex) { capturedGroups[decimalValue] = -1; } else { // Replace with an unambiguous escape sequence so that // an octal escape sequence does not turn into a backreference // to a capturing group from an earlier regex. parts[i] = encodeEscape(decimalValue); } } } } // Renumber groups and reduce capturing groups to non-capturing groups // where possible. for (var i = 1; i < capturedGroups.length; ++i) { if (-1 === capturedGroups[i]) { capturedGroups[i] = ++capturedGroupIndex; } } for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { ++groupIndex; if (!capturedGroups[groupIndex]) { parts[i] = '(?:'; } } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue && decimalValue <= groupIndex) { parts[i] = '\\' + capturedGroups[decimalValue]; } } } // Remove any prefix anchors so that the output will match anywhere. // ^^ really does mean an anchored match though. for (var i = 0; i < n; ++i) { if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; } } // Expand letters to groups to handle mixing of case-sensitive and // case-insensitive patterns if necessary. if (regex.ignoreCase && needToFoldCase) { for (var i = 0; i < n; ++i) { var p = parts[i]; var ch0 = p.charAt(0); if (p.length >= 2 && ch0 === '[') { parts[i] = caseFoldCharset(p); } else if (ch0 !== '\\') { // TODO: handle letters in numeric escapes. parts[i] = p.replace( /[a-zA-Z]/g, function (ch) { var cc = ch.charCodeAt(0); return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']'; }); } } } return parts.join(''); } var rewritten = []; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.global || regex.multiline) { throw new Error('' + regex); } rewritten.push( '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')'); } return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g'); } /** * Split markup into a string of source code and an array mapping ranges in * that string to the text nodes in which they appear. * * <p> * The HTML DOM structure:</p> * <pre> * (Element "p" * (Element "b" * (Text "print ")) ; #1 * (Text "'Hello '") ; #2 * (Element "br") ; #3 * (Text " + 'World';")) ; #4 * </pre> * <p> * corresponds to the HTML * {@code <p><b>print </b>'Hello '<br> + 'World';</p>}.</p> * * <p> * It will produce the output:</p> * <pre> * { * sourceCode: "print 'Hello '\n + 'World';", * // 1 2 * // 012345678901234 5678901234567 * spans: [0, #1, 6, #2, 14, #3, 15, #4] * } * </pre> * <p> * where #1 is a reference to the {@code "print "} text node above, and so * on for the other text nodes. * </p> * * <p> * The {@code} spans array is an array of pairs. Even elements are the start * indices of substrings, and odd elements are the text nodes (or BR elements) * that contain the text for those substrings. * Substrings continue until the next index or the end of the source. * </p> * * @param {Node} node an HTML DOM subtree containing source-code. * @param {boolean} isPreformatted true if white-space in text nodes should * be considered significant. * @return {Object} source code and the text nodes in which they occur. */ function extractSourceSpans(node, isPreformatted) { var nocode = /(?:^|\s)nocode(?:\s|$)/; var chunks = []; var length = 0; var spans = []; var k = 0; function walk(node) { switch (node.nodeType) { case 1: // Element if (nocode.test(node.className)) { return; } for (var child = node.firstChild; child; child = child.nextSibling) { walk(child); } var nodeName = node.nodeName.toLowerCase(); if ('br' === nodeName || 'li' === nodeName) { chunks[k] = '\n'; spans[k << 1] = length++; spans[(k++ << 1) | 1] = node; } break; case 3: case 4: // Text var text = node.nodeValue; if (text.length) { if (!isPreformatted) { text = text.replace(/[ \t\r\n]+/g, ' '); } else { text = text.replace(/\r\n?/g, '\n'); // Normalize newlines. } // TODO: handle tabs here? chunks[k] = text; spans[k << 1] = length; length += text.length; spans[(k++ << 1) | 1] = node; } break; } } walk(node); return { sourceCode: chunks.join('').replace(/\n$/, ''), spans: spans }; } /** * Apply the given language handler to sourceCode and add the resulting * decorations to out. * @param {number} basePos the index of sourceCode within the chunk of source * whose decorations are already present on out. */ function appendDecorations(basePos, sourceCode, langHandler, out) { if (!sourceCode) { return; } var job = { sourceCode: sourceCode, basePos: basePos }; langHandler(job); out.push.apply(out, job.decorations); } var notWs = /\S/; /** * Given an element, if it contains only one child element and any text nodes * it contains contain only space characters, return the sole child element. * Otherwise returns undefined. * <p> * This is meant to return the CODE element in {@code <pre><code ...>} when * there is a single child element that contains all the non-space textual * content, but not to return anything where there are multiple child elements * as in {@code <pre><code>...</code><code>...</code></pre>} or when there * is textual content. */ function childContentWrapper(element) { var wrapper = undefined; for (var c = element.firstChild; c; c = c.nextSibling) { var type = c.nodeType; wrapper = (type === 1) // Element Node ? (wrapper ? element : c) : (type === 3) // Text Node ? (notWs.test(c.nodeValue) ? element : wrapper) : wrapper; } return wrapper === element ? undefined : wrapper; } /** Given triples of [style, pattern, context] returns a lexing function, * The lexing function interprets the patterns to find token boundaries and * returns a decoration list of the form * [index_0, style_0, index_1, style_1, ..., index_n, style_n] * where index_n is an index into the sourceCode, and style_n is a style * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to * all characters in sourceCode[index_n-1:index_n]. * * The stylePatterns is a list whose elements have the form * [style : string, pattern : RegExp, DEPRECATED, shortcut : string]. * * Style is a style constant like PR_PLAIN, or can be a string of the * form 'lang-FOO', where FOO is a language extension describing the * language of the portion of the token in $1 after pattern executes. * E.g., if style is 'lang-lisp', and group 1 contains the text * '(hello (world))', then that portion of the token will be passed to the * registered lisp handler for formatting. * The text before and after group 1 will be restyled using this decorator * so decorators should take care that this doesn't result in infinite * recursion. For example, the HTML lexer rule for SCRIPT elements looks * something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match * '<script>foo()<\/script>', which would cause the current decorator to * be called with '<script>' which would not match the same rule since * group 1 must not be empty, so it would be instead styled as PR_TAG by * the generic tag rule. The handler registered for the 'js' extension would * then be called with 'foo()', and finally, the current decorator would * be called with '<\/script>' which would not match the original rule and * so the generic tag rule would identify it as a tag. * * Pattern must only match prefixes, and if it matches a prefix, then that * match is considered a token with the same style. * * Context is applied to the last non-whitespace, non-comment token * recognized. * * Shortcut is an optional string of characters, any of which, if the first * character, gurantee that this pattern and only this pattern matches. * * @param {Array} shortcutStylePatterns patterns that always start with * a known character. Must have a shortcut string. * @param {Array} fallthroughStylePatterns patterns that will be tried in * order if the shortcut ones fail. May have shortcuts. * * @return {function (Object)} a * function that takes source code and returns a list of decorations. */ function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) { var shortcuts = {}; var tokenizer; (function () { var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns); var allRegexs = []; var regexKeys = {}; for (var i = 0, n = allPatterns.length; i < n; ++i) { var patternParts = allPatterns[i]; var shortcutChars = patternParts[3]; if (shortcutChars) { for (var c = shortcutChars.length; --c >= 0;) { shortcuts[shortcutChars.charAt(c)] = patternParts; } } var regex = patternParts[1]; var k = '' + regex; if (!regexKeys.hasOwnProperty(k)) { allRegexs.push(regex); regexKeys[k] = null; } } allRegexs.push(/[\0-\uffff]/); tokenizer = combinePrefixPatterns(allRegexs); })(); var nPatterns = fallthroughStylePatterns.length; /** * Lexes job.sourceCode and produces an output array job.decorations of * style classes preceded by the position at which they start in * job.sourceCode in order. * * @param {Object} job an object like <pre>{ * sourceCode: {string} sourceText plain text, * basePos: {int} position of job.sourceCode in the larger chunk of * sourceCode. * }</pre> */ var decorate = function (job) { var sourceCode = job.sourceCode, basePos = job.basePos; /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {Array.<number|string>} */ var decorations = [basePos, PR_PLAIN]; var pos = 0; // index into sourceCode var tokens = sourceCode.match(tokenizer) || []; var styleCache = {}; for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) { var token = tokens[ti]; var style = styleCache[token]; var match = void 0; var isEmbedded; if (typeof style === 'string') { isEmbedded = false; } else { var patternParts = shortcuts[token.charAt(0)]; if (patternParts) { match = token.match(patternParts[1]); style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; match = token.match(patternParts[1]); if (match) { style = patternParts[0]; break; } } if (!match) { // make sure that we make progress style = PR_PLAIN; } } isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5); if (isEmbedded && !(match && typeof match[1] === 'string')) { isEmbedded = false; style = PR_SOURCE; } if (!isEmbedded) { styleCache[token] = style; } } var tokenStart = pos; pos += token.length; if (!isEmbedded) { decorations.push(basePos + tokenStart, style); } else { // Treat group 1 as an embedded block of source code. var embeddedSource = match[1]; var embeddedSourceStart = token.indexOf(embeddedSource); var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length; if (match[2]) { // If embeddedSource can be blank, then it would match at the // beginning which would cause us to infinitely recurse on the // entire token, so we catch the right context in match[2]. embeddedSourceEnd = token.length - match[2].length; embeddedSourceStart = embeddedSourceEnd - embeddedSource.length; } var lang = style.substring(5); // Decorate the left of the embedded source appendDecorations( basePos + tokenStart, token.substring(0, embeddedSourceStart), decorate, decorations); // Decorate the embedded source appendDecorations( basePos + tokenStart + embeddedSourceStart, embeddedSource, langHandlerForExtension(lang, embeddedSource), decorations); // Decorate the right of the embedded section appendDecorations( basePos + tokenStart + embeddedSourceEnd, token.substring(embeddedSourceEnd), decorate, decorations); } } job.decorations = decorations; }; return decorate; } /** returns a function that produces a list of decorations from source text. * * This code treats ", ', and ` as string delimiters, and \ as a string * escape. It does not recognize perl's qq() style strings. * It has no special handling for double delimiter escapes as in basic, or * the tripled delimiters used in python, but should work on those regardless * although in those cases a single string literal may be broken up into * multiple adjacent string literals. * * It recognizes C, C++, and shell style comments. * * @param {Object} options a set of optional parameters. * @return {function (Object)} a function that examines the source code * in the input job and builds the decoration list. */ function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options['tripleQuotedStrings']) { // '''multi-line-string''', 'single-line-string', and double-quoted shortcutStylePatterns.push( [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options['multiLineStrings']) { // 'multi-line-string', "multi-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { // 'single-line-string', "single-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } if (options['verbatimStrings']) { // verbatim-string-literal production from the C# grammar. See issue 93. fallthroughStylePatterns.push( [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]); } var hc = options['hashComments']; if (hc) { if (options['cStyleComments']) { if (hc > 1) { // multiline hash comments shortcutStylePatterns.push( [PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']); } else { // Stop C preprocessor declarations at an unclosed open comment shortcutStylePatterns.push( [PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/, null, '#']); } // #include <stdio.h> fallthroughStylePatterns.push( [PR_STRING, /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/, null]); } else { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } } if (options['cStyleComments']) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push( [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } if (options['regexLiterals']) { /** * @const */ var REGEX_LITERAL = ( // A regular expression literal starts with a slash that is // not followed by * or / so that it is not confused with // comments. '/(?=[^/*])' // and then contains any number of raw characters, + '(?:[^/\\x5B\\x5C]' // escape sequences (\x5C), + '|\\x5C[\\s\\S]' // or non-nesting character sets (\x5B\x5D); + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+' // finally closed by a /. + '/'); fallthroughStylePatterns.push( ['lang-regex', new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')') ]); } var types = options['types']; if (types) { fallthroughStylePatterns.push([PR_TYPE, types]); } var keywords = ("" + options['keywords']).replace(/^ | $/g, ''); if (keywords.length) { fallthroughStylePatterns.push( [PR_KEYWORD, new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'), null]); } shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']); fallthroughStylePatterns.push( // TODO(mikesamuel): recognize non-latin letters and numerals in idents [PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null], [PR_TYPE, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null], [PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null], [PR_LITERAL, new RegExp( '^(?:' // A hex number + '0x[a-f0-9]+' // or an octal or decimal number, + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)' // possibly in scientific notation + '(?:e[+\\-]?\\d+)?' + ')' // with an optional modifier like UL for unsigned long + '[a-z]*', 'i'), null, '0123456789'], // Don't treat escaped quotes in bash as starting strings. See issue 144. [PR_PLAIN, /^\\[\s\S]?/, null], [PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#\\]*/, null]); return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns); } var decorateSource = sourceDecorator({ 'keywords': ALL_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'multiLineStrings': true, 'regexLiterals': true }); /** * Given a DOM subtree, wraps it in a list, and puts each line into its own * list item. * * @param {Node} node modified in place. Its content is pulled into an * HTMLOListElement, and each line is moved into a separate list item. * This requires cloning elements, so the input might not have unique * IDs after numbering. * @param {boolean} isPreformatted true iff white-space in text nodes should * be treated as significant. */ function numberLines(node, opt_startLineNum, isPreformatted) { var nocode = /(?:^|\s)nocode(?:\s|$)/; var lineBreak = /\r\n?|\n/; var document = node.ownerDocument; var li = document.createElement('li'); while (node.firstChild) { li.appendChild(node.firstChild); } // An array of lines. We split below, so this is initialized to one // un-split line. var listItems = [li]; function walk(node) { switch (node.nodeType) { case 1: // Element if (nocode.test(node.className)) { break; } if ('br' === node.nodeName) { breakAfter(node); // Discard the <BR> since it is now flush against a </LI>. if (node.parentNode) { node.parentNode.removeChild(node); } } else { for (var child = node.firstChild; child; child = child.nextSibling) { walk(child); } } break; case 3: case 4: // Text if (isPreformatted) { var text = node.nodeValue; var match = text.match(lineBreak); if (match) { var firstLine = text.substring(0, match.index); node.nodeValue = firstLine; var tail = text.substring(match.index + match[0].length); if (tail) { var parent = node.parentNode; parent.insertBefore( document.createTextNode(tail), node.nextSibling); } breakAfter(node); if (!firstLine) { // Don't leave blank text nodes in the DOM. node.parentNode.removeChild(node); } } } break; } } // Split a line after the given node. function breakAfter(lineEndNode) { // If there's nothing to the right, then we can skip ending the line // here, and move root-wards since splitting just before an end-tag // would require us to create a bunch of empty copies. while (!lineEndNode.nextSibling) { lineEndNode = lineEndNode.parentNode; if (!lineEndNode) { return; } } function breakLeftOf(limit, copy) { // Clone shallowly if this node needs to be on both sides of the break. var rightSide = copy ? limit.cloneNode(false) : limit; var parent = limit.parentNode; if (parent) { // We clone the parent chain. // This helps us resurrect important styling elements that cross lines. // E.g. in <i>Foo<br>Bar</i> // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>. var parentClone = breakLeftOf(parent, 1); // Move the clone and everything to the right of the original // onto the cloned parent. var next = limit.nextSibling; parentClone.appendChild(rightSide); for (var sibling = next; sibling; sibling = next) { next = sibling.nextSibling; parentClone.appendChild(sibling); } } return rightSide; } var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0); // Walk the parent chain until we reach an unattached LI. for (var parent; // Check nodeType since IE invents document fragments. (parent = copiedListItem.parentNode) && parent.nodeType === 1;) { copiedListItem = parent; } // Put it on the list of lines for later processing. listItems.push(copiedListItem); } // Split lines while there are lines left to split. for (var i = 0; // Number of lines that have been split so far. i < listItems.length; // length updated by breakAfter calls. ++i) { walk(listItems[i]); } // Make sure numeric indices show correctly. if (opt_startLineNum === (opt_startLineNum|0)) { listItems[0].setAttribute('value', opt_startLineNum); } var ol = document.createElement('ol'); ol.className = 'linenums'; var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0; for (var i = 0, n = listItems.length; i < n; ++i) { li = listItems[i]; // Stick a class on the LIs so that stylesheets can // color odd/even rows, or any other row pattern that // is co-prime with 10. li.className = 'L' + ((i + offset) % 10); if (!li.firstChild) { li.appendChild(document.createTextNode('\xA0')); } ol.appendChild(li); } node.appendChild(ol); } /** * Breaks {@code job.sourceCode} around style boundaries in * {@code job.decorations} and modifies {@code job.sourceNode} in place. * @param {Object} job like <pre>{ * sourceCode: {string} source as plain text, * spans: {Array.<number|Node>} alternating span start indices into source * and the text node or element (e.g. {@code <BR>}) corresponding to that * span. * decorations: {Array.<number|string} an array of style classes preceded * by the position at which they start in job.sourceCode in order * }</pre> * @private */ function recombineTagsAndDecorations(job) { var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent); isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8; var newlineRe = /\n/g; var source = job.sourceCode; var sourceLength = source.length; // Index into source after the last code-unit recombined. var sourceIndex = 0; var spans = job.spans; var nSpans = spans.length; // Index into spans after the last span which ends at or before sourceIndex. var spanIndex = 0; var decorations = job.decorations; var nDecorations = decorations.length; // Index into decorations after the last decoration which ends at or before // sourceIndex. var decorationIndex = 0; // Remove all zero-length decorations. decorations[nDecorations] = sourceLength; var decPos, i; for (i = decPos = 0; i < nDecorations;) { if (decorations[i] !== decorations[i + 2]) { decorations[decPos++] = decorations[i++]; decorations[decPos++] = decorations[i++]; } else { i += 2; } } nDecorations = decPos; // Simplify decorations. for (i = decPos = 0; i < nDecorations;) { var startPos = decorations[i]; // Conflate all adjacent decorations that use the same style. var startDec = decorations[i + 1]; var end = i + 2; while (end + 2 <= nDecorations && decorations[end + 1] === startDec) { end += 2; } decorations[decPos++] = startPos; decorations[decPos++] = startDec; i = end; } nDecorations = decorations.length = decPos; var sourceNode = job.sourceNode; var oldDisplay; if (sourceNode) { oldDisplay = sourceNode.style.display; sourceNode.style.display = 'none'; } try { var decoration = null; while (spanIndex < nSpans) { var spanStart = spans[spanIndex]; var spanEnd = spans[spanIndex + 2] || sourceLength; var decEnd = decorations[decorationIndex + 2] || sourceLength; var end = Math.min(spanEnd, decEnd); var textNode = spans[spanIndex + 1]; var styledText; if (textNode.nodeType !== 1 // Don't muck with <BR>s or <LI>s // Don't introduce spans around empty text nodes. && (styledText = source.substring(sourceIndex, end))) { // This may seem bizarre, and it is. Emitting LF on IE causes the // code to display with spaces instead of line breaks. // Emitting Windows standard issue linebreaks (CRLF) causes a blank // space to appear at the beginning of every line but the first. // Emitting an old Mac OS 9 line separator makes everything spiffy. if (isIE8OrEarlier) { styledText = styledText.replace(newlineRe, '\r'); } textNode.nodeValue = styledText; var document = textNode.ownerDocument; var span = document.createElement('span'); span.className = decorations[decorationIndex + 1]; var parentNode = textNode.parentNode; parentNode.replaceChild(span, textNode); span.appendChild(textNode); if (sourceIndex < spanEnd) { // Split off a text node. spans[spanIndex + 1] = textNode // TODO: Possibly optimize by using '' if there's no flicker. = document.createTextNode(source.substring(end, spanEnd)); parentNode.insertBefore(textNode, span.nextSibling); } } sourceIndex = end; if (sourceIndex >= spanEnd) { spanIndex += 2; } if (sourceIndex >= decEnd) { decorationIndex += 2; } } } finally { if (sourceNode) { sourceNode.style.display = oldDisplay; } } } /** Maps language-specific file extensions to handlers. */ var langHandlerRegistry = {}; /** Register a language handler for the given file extensions. * @param {function (Object)} handler a function from source code to a list * of decorations. Takes a single argument job which describes the * state of the computation. The single parameter has the form * {@code { * sourceCode: {string} as plain text. * decorations: {Array.<number|string>} an array of style classes * preceded by the position at which they start in * job.sourceCode in order. * The language handler should assigned this field. * basePos: {int} the position of source in the larger source chunk. * All positions in the output decorations array are relative * to the larger source chunk. * } } * @param {Array.<string>} fileExtensions */ function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if (win['console']) { console['warn']('cannot override language handler %s', ext); } } } function langHandlerForExtension(extension, source) { if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) { // Treat it as markup if the first non whitespace character is a < and // the last non-whitespace character is a >. extension = /^\s*</.test(source) ? 'default-markup' : 'default-code'; } return langHandlerRegistry[extension]; } registerLangHandler(decorateSource, ['default-code']); registerLangHandler( createSimpleLexer( [], [ [PR_PLAIN, /^[^<?]+/], [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/], [PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/], // Unescaped content in an unknown language ['lang-', /^<\?([\s\S]+?)(?:\?>|$)/], ['lang-', /^<%([\s\S]+?)(?:%>|$)/], [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/], ['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i], // Unescaped content in javascript. (Or possibly vbscript). ['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i], // Contains unescaped stylesheet content ['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i], ['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i] ]), ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']); registerLangHandler( createSimpleLexer( [ [PR_PLAIN, /^[\s]+/, null, ' \t\r\n'], [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\''] ], [ [PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i], [PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i], ['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/], [PR_PUNCTUATION, /^[=<>\/]+/], ['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i], ['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i], ['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i], ['lang-css', /^style\s*=\s*\"([^\"]+)\"/i], ['lang-css', /^style\s*=\s*\'([^\']+)\'/i], ['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i] ]), ['in.tag']); registerLangHandler( createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']); registerLangHandler(sourceDecorator({ 'keywords': CPP_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'types': C_TYPES }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']); registerLangHandler(sourceDecorator({ 'keywords': 'null,true,false' }), ['json']); registerLangHandler(sourceDecorator({ 'keywords': CSHARP_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'verbatimStrings': true, 'types': C_TYPES }), ['cs']); registerLangHandler(sourceDecorator({ 'keywords': JAVA_KEYWORDS, 'cStyleComments': true }), ['java']); registerLangHandler(sourceDecorator({ 'keywords': SH_KEYWORDS, 'hashComments': true, 'multiLineStrings': true }), ['bsh', 'csh', 'sh']); registerLangHandler(sourceDecorator({ 'keywords': PYTHON_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'tripleQuotedStrings': true }), ['cv', 'py']); registerLangHandler(sourceDecorator({ 'keywords': PERL_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': true }), ['perl', 'pl', 'pm']); registerLangHandler(sourceDecorator({ 'keywords': RUBY_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': true }), ['rb']); registerLangHandler(sourceDecorator({ 'keywords': JSCRIPT_KEYWORDS, 'cStyleComments': true, 'regexLiterals': true }), ['js']); registerLangHandler(sourceDecorator({ 'keywords': COFFEE_KEYWORDS, 'hashComments': 3, // ### style block comments 'cStyleComments': true, 'multilineStrings': true, 'tripleQuotedStrings': true, 'regexLiterals': true }), ['coffee']); registerLangHandler( createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']); function applyDecorator(job) { var opt_langExtension = job.langExtension; try { // Extract tags, and convert the source code to plain text. var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre); /** Plain text. @type {string} */ var source = sourceAndSpans.sourceCode; job.sourceCode = source; job.spans = sourceAndSpans.spans; job.basePos = 0; // Apply the appropriate language handler langHandlerForExtension(opt_langExtension, source)(job); // Integrate the decorations and tags back into the source code, // modifying the sourceNode in place. recombineTagsAndDecorations(job); } catch (e) { if (win['console']) { console['log'](e && e['stack'] ? e['stack'] : e); } } } /** * @param sourceCodeHtml {string} The HTML to pretty print. * @param opt_langExtension {string} The language name to use. * Typically, a filename extension like 'cpp' or 'java'. * @param opt_numberLines {number|boolean} True to number lines, * or the 1-indexed number of the first line in sourceCodeHtml. */ function prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) { // PATCHED: http://code.google.com/p/google-code-prettify/issues/detail?id=213 var container = document.createElement('div'); // This could cause images to load and onload listeners to fire. // E.g. <img onerror="alert(1337)" src="nosuchimage.png">. // We assume that the inner HTML is from a trusted source. container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>'; container = container.firstChild; if (opt_numberLines) { numberLines(container, opt_numberLines, true); } var job = { langExtension: opt_langExtension, numberLines: opt_numberLines, sourceNode: container, pre: 1 }; applyDecorator(job); return container.innerHTML; } function prettyPrint(opt_whenDone) { function byTagName(tn) { return document.getElementsByTagName(tn); } // fetch a list of nodes to rewrite var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')]; var elements = []; for (var i = 0; i < codeSegments.length; ++i) { for (var j = 0, n = codeSegments[i].length; j < n; ++j) { elements.push(codeSegments[i][j]); } } codeSegments = null; var clock = Date; if (!clock['now']) { clock = { 'now': function () { return +(new Date); } }; } // The loop is broken into a series of continuations to make sure that we // don't make the browser unresponsive when rewriting a large page. var k = 0; var prettyPrintingJob; var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/; var prettyPrintRe = /\bprettyprint\b/; var prettyPrintedRe = /\bprettyprinted\b/; var preformattedTagNameRe = /pre|xmp/i; var codeRe = /^code$/i; var preCodeXmpRe = /^(?:pre|code|xmp)$/i; function doWork() { var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ? clock['now']() + 250 /* ms */ : Infinity); for (; k < elements.length && clock['now']() < endTime; k++) { var cs = elements[k]; var className = cs.className; if (prettyPrintRe.test(className) // Don't redo this if we've already done it. // This allows recalling pretty print to just prettyprint elements // that have been added to the page since last call. && !prettyPrintedRe.test(className)) { // make sure this is not nested in an already prettified element var nested = false; for (var p = cs.parentNode; p; p = p.parentNode) { var tn = p.tagName; if (preCodeXmpRe.test(tn) && p.className && prettyPrintRe.test(p.className)) { nested = true; break; } } if (!nested) { // Mark done. If we fail to prettyprint for whatever reason, // we shouldn't try again. cs.className += ' prettyprinted'; // If the classes includes a language extensions, use it. // Language extensions can be specified like // <pre class="prettyprint lang-cpp"> // the language extension "cpp" is used to find a language handler // as passed to PR.registerLangHandler. // HTML5 recommends that a language be specified using "language-" // as the prefix instead. Google Code Prettify supports both. // http://dev.w3.org/html5/spec-author-view/the-code-element.html var langExtension = className.match(langExtensionRe); // Support <pre class="prettyprint"><code class="language-c"> var wrapper; if (!langExtension && (wrapper = childContentWrapper(cs)) && codeRe.test(wrapper.tagName)) { langExtension = wrapper.className.match(langExtensionRe); } if (langExtension) { langExtension = langExtension[1]; } var preformatted; if (preformattedTagNameRe.test(cs.tagName)) { preformatted = 1; } else { var currentStyle = cs['currentStyle']; var whitespace = ( currentStyle ? currentStyle['whiteSpace'] : (document.defaultView && document.defaultView.getComputedStyle) ? document.defaultView.getComputedStyle(cs, null) .getPropertyValue('white-space') : 0); preformatted = whitespace && 'pre' === whitespace.substring(0, 3); } // Look for a class like linenums or linenums:<n> where <n> is the // 1-indexed number of the first line. var lineNums = cs.className.match(/\blinenums\b(?::(\d+))?/); lineNums = lineNums ? lineNums[1] && lineNums[1].length ? +lineNums[1] : true : false; if (lineNums) { numberLines(cs, lineNums, preformatted); } // do the pretty printing prettyPrintingJob = { langExtension: langExtension, sourceNode: cs, numberLines: lineNums, pre: preformatted }; applyDecorator(prettyPrintingJob); } } } if (k < elements.length) { // finish up in a continuation setTimeout(doWork, 250); } else if (opt_whenDone) { opt_whenDone(); } } doWork(); } /** * Contains functions for creating and registering new language handlers. * @type {Object} */ var PR = win['PR'] = { 'createSimpleLexer': createSimpleLexer, 'registerLangHandler': registerLangHandler, 'sourceDecorator': sourceDecorator, 'PR_ATTRIB_NAME': PR_ATTRIB_NAME, 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE, 'PR_COMMENT': PR_COMMENT, 'PR_DECLARATION': PR_DECLARATION, 'PR_KEYWORD': PR_KEYWORD, 'PR_LITERAL': PR_LITERAL, 'PR_NOCODE': PR_NOCODE, 'PR_PLAIN': PR_PLAIN, 'PR_PUNCTUATION': PR_PUNCTUATION, 'PR_SOURCE': PR_SOURCE, 'PR_STRING': PR_STRING, 'PR_TAG': PR_TAG, 'PR_TYPE': PR_TYPE, 'prettyPrintOne': win['prettyPrintOne'] = prettyPrintOne, 'prettyPrint': win['prettyPrint'] = prettyPrint }; // Make PR available via the Asynchronous Module Definition (AMD) API. // Per https://github.com/amdjs/amdjs-api/wiki/AMD: // The Asynchronous Module Definition (AMD) API specifies a // mechanism for defining modules such that the module and its // dependencies can be asynchronously loaded. // ... // To allow a clear indicator that a global define function (as // needed for script src browser loading) conforms to the AMD API, // any global define function SHOULD have a property called "amd" // whose value is an object. This helps avoid conflict with any // other existing JavaScript code that could have defined a define() // function that does not conform to the AMD API. if (typeof define === "function" && define['amd']) { define("google-code-prettify", [], function () { return PR; }); } })(); })(window, window.angular); angular.element(document).find('head').append('<style type="text/css">.com{color:#93a1a1;}.lit{color:#195f91;}.pun,.opn,.clo{color:#93a1a1;}.fun{color:#dc322f;}.str,.atv{color:#D14;}.kwd,.linenums .tag{color:#1e347b;}.typ,.atn,.dec,.var{color:teal;}.pln{color:#48484c;}.prettyprint{padding:8px;background-color:#f7f7f9;border:1px solid #e1e1e8;}.prettyprint.linenums{-webkit-box-shadow:inset 40px 0 0 #fbfbfc,inset 41px 0 0 #ececf0;-moz-box-shadow:inset 40px 0 0 #fbfbfc,inset 41px 0 0 #ececf0;box-shadow:inset 40px 0 0 #fbfbfc,inset 41px 0 0 #ececf0;}ol.linenums{margin:0 0 0 33px;}ol.linenums li{padding-left:12px;color:#bebec5;line-height:18px;text-shadow:0 1px 0 #fff;}</style>');
zzangtest123-google-drive-sdk-samples
python/static/lib/angular-1.0.0/angular-bootstrap-prettify-1.0.0.js
JavaScript
asf20
67,929
/** * Configuration for jstd scenario adapter */ var jstdScenarioAdapter = { relativeUrlPrefix: '/build/docs/' };
zzangtest123-google-drive-sdk-samples
python/static/lib/angular-1.0.0/jstd-scenario-adapter-config-1.0.0.js
JavaScript
asf20
120
/** * @license AngularJS v1.0.0 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; var directive = {}; directive.dropdownToggle = ['$document', '$location', '$window', function ($document, $location, $window) { var openElement = null, close; return { restrict: 'C', link: function(scope, element, attrs) { scope.$watch(function(){return $location.path();}, function() { close && close(); }); element.parent().bind('click', function(event) { close && close(); }); element.bind('click', function(event) { event.preventDefault(); event.stopPropagation(); var iWasOpen = false; if (openElement) { iWasOpen = openElement === element; close(); } if (!iWasOpen){ element.parent().addClass('open'); openElement = element; close = function (event) { event && event.preventDefault(); event && event.stopPropagation(); $document.unbind('click', close); element.parent().removeClass('open'); close = null; openElement = null; } $document.bind('click', close); } }); } }; }]; directive.tabbable = function() { return { restrict: 'C', compile: function(element) { var navTabs = angular.element('<ul class="nav nav-tabs"></ul>'), tabContent = angular.element('<div class="tab-content"></div>'); tabContent.append(element.contents()); element.append(navTabs).append(tabContent); }, controller: ['$scope', '$element', function($scope, $element) { var navTabs = $element.contents().eq(0), ngModel = $element.controller('ngModel') || {}, tabs = [], selectedTab; ngModel.$render = function() { var $viewValue = this.$viewValue; if (selectedTab ? (selectedTab.value != $viewValue) : $viewValue) { if(selectedTab) { selectedTab.paneElement.removeClass('active'); selectedTab.tabElement.removeClass('active'); selectedTab = null; } if($viewValue) { for(var i = 0, ii = tabs.length; i < ii; i++) { if ($viewValue == tabs[i].value) { selectedTab = tabs[i]; break; } } if (selectedTab) { selectedTab.paneElement.addClass('active'); selectedTab.tabElement.addClass('active'); } } } }; this.addPane = function(element, attr) { var li = angular.element('<li><a href></a></li>'), a = li.find('a'), tab = { paneElement: element, paneAttrs: attr, tabElement: li }; tabs.push(tab); attr.$observe('value', update)(); attr.$observe('title', function(){ update(); a.text(tab.title); })(); function update() { tab.title = attr.title; tab.value = attr.value || attr.title; if (!ngModel.$setViewValue && (!ngModel.$viewValue || tab == selectedTab)) { // we are not part of angular ngModel.$viewValue = tab.value; } ngModel.$render(); } navTabs.append(li); li.bind('click', function(event) { event.preventDefault(); event.stopPropagation(); if (ngModel.$setViewValue) { $scope.$apply(function() { ngModel.$setViewValue(tab.value); ngModel.$render(); }); } else { // we are not part of angular ngModel.$viewValue = tab.value; ngModel.$render(); } }); return function() { tab.tabElement.remove(); for(var i = 0, ii = tabs.length; i < ii; i++ ) { if (tab == tabs[i]) { tabs.splice(i, 1); } } }; } }] }; }; directive.tabPane = function() { return { require: '^tabbable', restrict: 'C', link: function(scope, element, attrs, tabsCtrl) { element.bind('$remove', tabsCtrl.addPane(element, attrs)); } }; }; angular.module('bootstrap', []).directive(directive); })(window, window.angular);
zzangtest123-google-drive-sdk-samples
python/static/lib/angular-1.0.0/angular-bootstrap-1.0.0.js
JavaScript
asf20
4,516
/** * @license AngularJS v1.0.0 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc overview * @name ngResource * @description */ /** * @ngdoc object * @name ngResource.$resource * @requires $http * * @description * A factory which creates a resource object that lets you interact with * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. * * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link ng.$http $http} service. * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * * If the parameter value is prefixed with `@` then the value of that parameter is extracted from * the data object (useful for non-GET operations). * * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the * default set of resource actions. The declaration should be created in the following format: * * {action1: {method:?, params:?, isArray:?}, * action2: {method:?, params:?, isArray:?}, * ...} * * Where: * * - `action` – {string} – The name of action. This name becomes the name of the method on your * resource object. * - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, * and `JSONP` * - `params` – {object=} – Optional set of pre-bound parameters for this action. * - isArray – {boolean=} – If true then the returned object for this action is an array, see * `returns` section. * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * * { 'get': {method:'GET'}, * 'save': {method:'POST'}, * 'query': {method:'GET', isArray:true}, * 'remove': {method:'DELETE'}, * 'delete': {method:'DELETE'} }; * * Calling these methods invoke an {@link ng.$http} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class `save`, `remove` and `delete` actions are available on it as * methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read, * update, delete) on server-side data like this: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This * means that in most case one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: * * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` * - non-GET instance actions: `instance.$action([parameters], [success], [error])` * * * @example * * # Credit card resource * * <pre> // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(function() { // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} }); // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'01234', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * </pre> * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * * Calling these methods invoke `$http` on the `url` template with the given `method` and `params`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It's worth noting that the success callback for `get`, `query` and other method gets passed * in the response that came from the server as well as $http header getter function, so one * could rewrite the above example and get access to http headers as: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(u, getResponseHeaders){ u.abc = true; u.$save(function(u, putResponseHeaders) { //u => saved user object //putResponseHeaders => $http header getter }); }); </pre> * # Buzz client Let's look at what a buzz client created with the `$resource` service looks like: <doc:example> <doc:source jsfiddle="false"> <script> function BuzzController($resource) { this.userId = 'googlebuzz'; this.Activity = $resource( 'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', {alt:'json', callback:'JSON_CALLBACK'}, {get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}} ); } BuzzController.prototype = { fetch: function() { this.activities = this.Activity.get({userId:this.userId}); }, expandReplies: function(activity) { activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); } }; BuzzController.$inject = ['$resource']; </script> <div ng-controller="BuzzController"> <input ng-model="userId"/> <button ng-click="fetch()">fetch</button> <hr/> <div ng-repeat="item in activities.data.items"> <h1 style="font-size: 15px;"> <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> <a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> </h1> {{item.object.content | html}} <div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;"> <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} </div> </div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angular.module('ngResource', ['ng']). factory('$resource', ['$http', '$parse', function($http, $parse) { var DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; var noop = angular.noop, forEach = angular.forEach, extend = angular.extend, copy = angular.copy, isFunction = angular.isFunction, getter = function(obj, path) { return $parse(path)(obj); }; /** * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; forEach(template.split(/\W/), function(param){ if (param && template.match(new RegExp("[^\\\\]:" + param + "\\W"))) { urlParams[param] = true; } }); this.template = template.replace(/\\:/g, ':'); } Route.prototype = { url: function(params) { var self = this, url = this.template, encodedVal; params = params || {}; forEach(this.urlParams, function(_, urlParam){ encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || ""); url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1"); }); url = url.replace(/\/?#$/, ''); var query = []; forEach(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); } }); query.sort(); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(url, paramDefaults, actions) { var route = new Route(url); actions = extend({}, DEFAULT_ACTIONS, actions); function extractParams(data){ var ids = {}; forEach(paramDefaults || {}, function(value, key){ ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } forEach(actions, function(action, name) { var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH'; Resource[name] = function(a1, a2, a3, a4) { var params = {}; var data; var success = noop; var error = null; switch(arguments.length) { case 4: error = a4; success = a3; //fallthrough case 3: case 2: if (isFunction(a2)) { if (isFunction(a1)) { success = a1; error = a2; break; } success = a2; error = a3; //fallthrough } else { params = a1; data = a2; success = a3; break; } case 1: if (isFunction(a1)) success = a1; else if (hasBody) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-4 arguments [params, data, success, error], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); $http({ method: action.method, url: route.url(extend({}, extractParams(data), action.params || {}, params)), data: data }).then(function(response) { var data = response.data; if (data) { if (action.isArray) { value.length = 0; forEach(data, function(item) { value.push(new Resource(item)); }); } else { copy(data, value); } } (success||noop)(value, response.headers); }, error); return value; }; Resource.bind = function(additionalParamDefaults){ return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; Resource.prototype['$' + name] = function(a1, a2, a3) { var params = extractParams(this), success = noop, error; switch(arguments.length) { case 3: params = a1; success = a2; error = a3; break; case 2: case 1: if (isFunction(a1)) { success = a1; error = a2; } else { params = a1; success = a2 || noop; } case 0: break; default: throw "Expected between 1-3 arguments [params, success, error], got " + arguments.length + " arguments."; } var data = hasBody ? this : undefined; Resource[name].call(this, params, data, success, error); }; }); return Resource; } return ResourceFactory; }]); })(window, window.angular);
zzangtest123-google-drive-sdk-samples
python/static/lib/angular-1.0.0/angular-resource-1.0.0.js
JavaScript
asf20
15,889
/** * @license AngularJS v1.0.0 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document, undefined) { 'use strict'; //////////////////////////////////// /** * @ngdoc function * @name angular.lowercase * @function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; /** * @ngdoc function * @name angular.uppercase * @function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { return isString(s) ? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) {return String.fromCharCode(code);} var Error = window.Error, /** holds major version number for IE or NaN for real browsers */ msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, toString = Object.prototype.toString, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, nodeName_, uid = ['0', '0', '0']; /** * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } } return obj; } function sortedKeys(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys.sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value) }; } /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). */ function extend(dst) { forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } /** * @ngdoc function * @name angular.noop * @function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){return typeof value == 'undefined';} /** * @ngdoc function * @name angular.isDefined * @function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){return typeof value != 'undefined';} /** * @ngdoc function * @name angular.isObject * @function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){return value != null && typeof value == 'object';} /** * @ngdoc function * @name angular.isString * @function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){return typeof value == 'string';} /** * @ngdoc function * @name angular.isNumber * @function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){return typeof value == 'number';} /** * @ngdoc function * @name angular.isDate * @function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return toString.apply(value) == '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return toString.apply(value) == '[object Array]'; } /** * @ngdoc function * @name angular.isFunction * @function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){return typeof value == 'function';} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.apply(obj) === '[object File]'; } function isBoolean(value) { return typeof value == 'boolean'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } /** * @ngdoc function * @name angular.isElement * @function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { return indexOf(array, obj) != -1; } function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function arrayRemove(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array, `source` is returned. * * Note: this function is used to augment the Object type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. */ function copy(source, destination){ if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope"); if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (source === destination) throw Error("Can't copy equivalent objects or arrays"); if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * Create a shallow copy of an object */ function shallowCopy(src, dst) { dst = dst || {}; for(var key in src) { if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { dst[key] = src[key]; } } return dst; } /** * @ngdoc function * @name angular.equals * @function * * @description * Determines if two objects or two values are equivalent. Supports value types, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) * * During a property comparision, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only be identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { return isDate(o2) && o1.getTime() == o2.getTime(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false; keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } } return false; } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /** * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are are prebound to the function. This feature is also * known as [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (/^\$+/.test(key)) { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @function * * @description * Serializes input into a JSON-formatted string. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } /** * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.html(''); } catch(e) {} return jqLite('<div>').append(element).html(). match(/^(<[^>]+>)/)[1]. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = decodeURIComponent(key_value[0]); obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } /** * @ngdoc directive * @name ng.directive:ngApp * * @element ANY * @param {angular.Module} ngApp on optional application * {@link angular.module module} name to load. * * @description * * Use this directive to auto-bootstrap on application. Only * one directive can be used per HTML document. The directive * designates the root of the application and is typically placed * ot the root of the page. * * In the example below if the `ngApp` directive would not be placed * on the `html` element then the document would not be compiled * and the `{{ 1+2 }}` would not be resolved to `3`. * * `ngApp` is the easiest way to bootstrap an application. * <doc:example> <doc:source> I can add: 1 + 2 = {{ 1+2 }} </doc:source> </doc:example> * */ function angularInit(element, bootstrap) { var elements = [element], appElement, module, names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; function append(element) { element && elements.push(element); } forEach(names, function(name) { names[name] = true; append(document.getElementById(name)); name = name.replace(':', '\\:'); if (element.querySelectorAll) { forEach(element.querySelectorAll('.' + name), append); forEach(element.querySelectorAll('.' + name + '\\:'), append); forEach(element.querySelectorAll('[' + name + ']'), append); } }); forEach(elements, function(element) { if (!appElement) { var className = ' ' + element.className + ' '; var match = NG_APP_CLASS_REGEXP.exec(className); if (match) { appElement = element; module = (match[2] || '').replace(/\s+/g, ','); } else { forEach(element.attributes, function(attr) { if (!appElement && names[attr.name]) { appElement = element; module = attr.value; } }); } } }); if (appElement) { bootstrap(appElement, module ? [module] : []); } } /** * @ngdoc function * @name angular.bootstrap * @description * Use this function to manually start up angular application. * * See: {@link guide/bootstrap Bootstrap} * * @param {Element} element DOM element which is the root of angular application. * @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules} * @returns {AUTO.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules) { element = jqLite(element); modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); modules.unshift('ng'); var injector = createInjector(modules); injector.invoke( ['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector){ scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); }] ); return injector; } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator){ separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } function bindJQuery() { // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); JQLitePatchJQueryRemove('remove', true); JQLitePatchJQueryRemove('empty'); JQLitePatchJQueryRemove('html'); } else { jqLite = JQLite; } angular.element = jqLite; } /** * throw error of the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * @ngdoc interface * @name angular.Module * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } return ensure(ensure(window, 'angular', Object), 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @description * * The `angular.module` is a global place for creating and registering Angular modules. All * modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * * # Module * * A module is a collocation of services, directives, filters, and configure information. Module * is used to configure the {@link AUTO.$injector $injector}. * * <pre> * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * </pre> * * Then you can create an injector and load your modules like this: * * <pre> * var injector = angular.injector(['ng', 'MyModule']) * </pre> * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the * the module is being retrieved for further configuration. * @param {Function} configFn Option configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw Error('No module: ' + name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @propertyOf angular.Module * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @propertyOf angular.Module * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @methodOf angular.Module * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the service. * @description * See {@link AUTO.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @methodOf angular.Module * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link AUTO.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @methodOf angular.Module * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link AUTO.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @methodOf angular.Module * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link AUTO.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @methodOf angular.Module * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link AUTO.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#filter * @methodOf angular.Module * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @methodOf angular.Module * @param {string} name Controller name. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @methodOf angular.Module * @param {string} name directive name * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider.directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @methodOf angular.Module * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @methodOf angular.Module * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which needs to be performed when the injector with * with the current module is finished loading. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; } } }); }; }); } /** * @ngdoc property * @name angular.version * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.0.0', // all of these placeholder strings will be replaced by rake's major: 1, // compile task minor: 0, dot: 0, codeName: 'temporal-domination' }; function publishExternalAPI(angular){ extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0} }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCsp: ngCspDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngSubmit: ngSubmitDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngView: ngViewDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, required: requiredDirective, ngRequired: requiredDirective, ngValue: ngValueDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $route: $RouteProvider, $routeParams: $RouteParamsProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $timeout: $TimeoutProvider, $window: $WindowProvider }); } ]); } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite * implementation (commonly referred to as jqLite). * * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` * event fired. * * jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality * within a very small footprint, so only a subset of the jQuery API - methods, arguments and * invocation styles - are supported. * * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * * ## Angular's jQuery lite provides the following methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) * - [children()](http://api.jquery.com/children/) * - [clone()](http://api.jquery.com/clone/) * - [contents()](http://api.jquery.com/contents/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [eq()](http://api.jquery.com/eq/) * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name. * - [hasClass()](http://api.jquery.com/hasClass/) * - [html()](http://api.jquery.com/html/) * - [next()](http://api.jquery.com/next/) * - [parent()](http://api.jquery.com/parent/) * - [prepend()](http://api.jquery.com/prepend/) * - [prop()](http://api.jquery.com/prop/) * - [ready()](http://api.jquery.com/ready/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [toggleClass()](http://api.jquery.com/toggleClass/) * - [unbind()](http://api.jquery.com/unbind/) * - [val()](http://api.jquery.com/val/) * - [wrap()](http://api.jquery.com/wrap/) * * ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite: * * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current * element or its parent. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = JQLite.cache = {}, jqName = JQLite.expando = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } ///////////////////////////////////////////// // jQuery mutation patch // // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// function JQLitePatchJQueryRemove(name, dispatchThis) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; function removePatch() { var list = [this], fireEvent = dispatchThis, set, setIndex, setLength, element, childIndex, childLength, children, fns, events; while(list.length) { set = list.shift(); for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { element = jqLite(set[setIndex]); if (fireEvent) { events = element.data('events'); if ( (fns = events && events.$destroy) ) { forEach(fns, function(fn){ fn.handler(); }); } } else { fireEvent = !fireEvent; } for(childIndex = 0, childLength = (children = element.children()).length; childIndex < childLength; childIndex++) { list.push(jQuery(children[childIndex])); } } } return originalJqFn.apply(this, arguments); } } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } if (!(this instanceof JQLite)) { if (isString(element) && element.charAt(0) != '<') { throw Error('selectors not implemented'); } return new JQLite(element); } if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&nbsp;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteUnbind(element, type, fn) { var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!handle) return; //no listeners registered if (isUndefined(type)) { forEach(events, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete events[type]; }); } else { if (isUndefined(fn)) { removeEventListenerFn(element, type, events[type]); delete events[type]; } else { arrayRemove(events[type], fn); } } } function JQLiteRemoveData(element) { var expandoId = element[jqName], expandoStore = jqCache[expandoId]; if (expandoStore) { if (expandoStore.handle) { expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); JQLiteUnbind(element); } delete jqCache[expandoId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteExpandoStore(element, key, value) { var expandoId = element[jqName], expandoStore = jqCache[expandoId || -1]; if (isDefined(value)) { if (!expandoStore) { element[jqName] = expandoId = jqNextId(); expandoStore = jqCache[expandoId] = {}; } expandoStore[key] = value; } else { return expandoStore && expandoStore[key]; } } function JQLiteData(element, key, value) { var data = JQLiteExpandoStore(element, 'data'), isSetter = isDefined(value), keyDefined = !isSetter && isDefined(key), isSimpleGetter = keyDefined && !isObject(key); if (!data && !isSimpleGetter) { JQLiteExpandoStore(element, 'data', data = {}); } if (isSetter) { data[key] = value; } else { if (keyDefined) { if (isSimpleGetter) { // don't create data in this case. return data && data[key]; } else { extend(data, key); } } else { return data; } } } function JQLiteHasClass(element, selector) { return ((" " + element.className + " ").replace(/[\n\t]/g, " "). indexOf( " " + selector + " " ) > -1); } function JQLiteRemoveClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ") ); }); } } function JQLiteAddClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { if (!JQLiteHasClass(element, cssClass)) { element.className = trim(element.className + ' ' + trim(cssClass)); } }); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } function JQLiteController(element, name) { return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } function JQLiteInheritedData(element, name, value) { element = jqLite(element); // if element is the document object work with the html element instead // this makes $(document).scope() possible if(element[0].nodeType == 9) { element = element.find('html'); } while (element.length) { if (value = element.data(name)) return value; element = element.parent(); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. JQLite(window).bind('load', trigger); // fallback to window.onload for others }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; } forEach({ data: JQLiteData, inheritedData: JQLiteInheritedData, scope: function(element) { return JQLiteInheritedData(element, '$scope'); }, controller: JQLiteController , injector: function(element) { return JQLiteInheritedData(element, '$injector'); }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name)|| noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: extend((msie < 9) ? function(element, value) { if (element.nodeType == 1 /** Element */) { if (isUndefined(value)) return element.innerText; element.innerText = value; } else { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { if (fn === JQLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { for (key in arg1) { fn(this[i], key, arg1[key]); } } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); function createEventHandler(element, events) { var eventHandler = function (event, type) { if (!event.preventDefault) { event.preventDefault = function() { event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented; }; forEach(events[type || event.type], function(fn) { fn.call(element, event); }); // Remove monkey-patched methods (IE), // as they would cause memory leaks in IE8. if (msie <= 8) { // IE7/8 does not allow to delete property on native object event.preventDefault = null; event.stopPropagation = null; event.isDefaultPrevented = null; } else { // It shouldn't affect normal browsers (native methods are defined on prototype). delete event.preventDefault; delete event.stopPropagation; delete event.isDefaultPrevented; } }; eventHandler.elem = element; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function bindFn(element, type, fn){ var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!events) JQLiteExpandoStore(element, 'events', events = {}); if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); forEach(type.split(' '), function(type){ var eventFns = events[type]; if (!eventFns) { if (type == 'mouseenter' || type == 'mouseleave') { var counter = 0; events.mouseenter = []; events.mouseleave = []; bindFn(element, 'mouseover', function(event) { counter++; if (counter == 1) { handle(event, 'mouseenter'); } }); bindFn(element, 'mouseout', function(event) { counter --; if (counter == 0) { handle(event, 'mouseleave'); } }); } else { addEventListenerFn(element, type, handle); events[type] = []; } eventFns = events[type] } eventFns.push(fn); }); }, unbind: JQLiteUnbind, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeName != '#text') children.push(element); }); return children; }, contents: function(element) { return element.childNodes; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1) element.appendChild(child); }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode)[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { return element.nextSibling; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj, key; if (objType == 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } else { key = obj; } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * A map where multiple values can be added to the same key such that they form a queue. * @returns {HashQueueMap} */ function HashQueueMap() {} HashQueueMap.prototype = { /** * Same as array push, but using an array as the value for the hash */ push: function(key, value) { var array = this[key = hashKey(key)]; if (!array) { this[key] = [value]; } else { array.push(value); } }, /** * Same as array shift, but using an array as the value for the hash */ shift: function(key) { var array = this[key = hashKey(key)]; if (array) { if (array.length == 1) { delete this[key]; return array[0]; } else { return array.shift(); } } } }; /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @returns {function()} Injector function. See {@link AUTO.$injector $injector}. * * @example * Typical usage * <pre> * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick of your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document){ * $compile($document)($rootScope); * $rootScope.$digest(); * }); * </pre> */ /** * @ngdoc overview * @name AUTO * @description * * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(.+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function annotate(fn) { var $inject, fnText, argDecl, last; if (typeof fn == 'function') { if (!($inject = fn.$inject)) { $inject = []; fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ $inject.push(name); }); }); fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn') $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc object * @name AUTO.$injector * @function * * @description * * `$injector` is used to retrieve object instances as defined by * {@link AUTO.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * <pre> * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector){ * return $injector; * }).toBe($injector); * </pre> * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following ways are all valid way of annotating function with injection arguments and are equivalent. * * <pre> * // inferred (only works if code not minified/obfuscated) * $inject.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $inject.invoke(explicit); * * // inline * $inject.invoke(['serviceA', function(serviceA){}]); * </pre> * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation * tools since these tools change the argument names. * * ## `$inject` Annotation * By adding a `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name AUTO.$injector#get * @methodOf AUTO.$injector * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name AUTO.$injector#invoke * @methodOf AUTO.$injector * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!function} fn The function to invoke. The function arguments come form the function annotation. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name AUTO.$injector#instantiate * @methodOf AUTO.$injector * @description * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies * all of the arguments to the constructor function as specified by the constructor annotation. * * @param {function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name AUTO.$injector#annotate * @methodOf AUTO.$injector * * @description * Returns an array of service names which the function is requesting for injection. This API is used by the injector * to determine which services need to be injected into the function when the function is invoked. There are three * ways in which the function can be annotated with the needed dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting * the function into a string using `toString()` method and extracting the argument names. * <pre> * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies * are supported. * * # The `$injector` property * * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of * services to be injected into the function. * <pre> * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController.$inject = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives * minification is a better choice: * * <pre> * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tempFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * </pre> * * @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described * above. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc object * @name AUTO.$provide * * @description * * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. * The providers share the same name as the instance they create with the `Provider` suffixed to them. * * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of * a service. The Provider can have additional methods which would allow for configuration of the provider. * * <pre> * function GreetProvider() { * var salutation = 'Hello'; * * this.salutation = function(text) { * salutation = text; * }; * * this.$get = function() { * return function (name) { * return salutation + ' ' + name + '!'; * }; * }; * } * * describe('Greeter', function(){ * * beforeEach(module(function($provide) { * $provide.provider('greet', GreetProvider); * }); * * it('should greet', inject(function(greet) { * expect(greet('angular')).toEqual('Hello angular!'); * })); * * it('should allow configuration of salutation', function() { * module(function(greetProvider) { * greetProvider.salutation('Ahoj'); * }); * inject(function(greet) { * expect(greet('angular')).toEqual('Ahoj angular!'); * }); * )}; * * }); * </pre> */ /** * @ngdoc method * @name AUTO.$provide#provider * @methodOf AUTO.$provide * @description * * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#factory * @methodOf AUTO.$provide * @description * * A short hand for configuring services if only `$get` method is required. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for * `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#service * @methodOf AUTO.$provide * @description * * A short hand for registering service of given class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#value * @methodOf AUTO.$provide * @description * * A short hand for configuring services if the `$get` method is a constant. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#constant * @methodOf AUTO.$provide * @description * * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected * into configuration function (other modules) and it is not interceptable by * {@link AUTO.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance */ /** * @ngdoc method * @name AUTO.$provide#decorator * @methodOf AUTO.$provide * @description * * Decoration of service, allows the decorator to intercept the service instance creation. The * returned instance may be the original instance, or a new instance which delegates to the * original instance. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instanciated. The function is called using the {@link AUTO.$injector#invoke * injector.invoke} method and is therefore fully injectable. Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. */ function createInjector(modulesToLoad) { var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap(), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = createInternalInjector(providerCache, function() { throw Error("Unknown provider: " + path.join(' <- ')); }), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } } } function provider(name, provider_) { if (isFunction(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw Error('Provider ' + name + ' must define $get factory method.'); } return providerCache[name + providerSuffix] = provider_; } function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, value) { return factory(name, valueFn(value)); } function constant(name, value) { providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ var runBlocks = []; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); if (isString(module)) { var moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); try { for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], provider = invokeArgs[0] == '$injector' ? providerInjector : providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isFunction(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isArray(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + String(module[module.length - 1]); throw e; } } else { assertArgFn(module, 'module'); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (typeof serviceName !== 'string') { throw Error('Service name expected'); } if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw Error('Circular dependency: ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } finally { path.shift(); } } } function invoke(fn, self, locals){ var args = [], $inject = annotate(fn), length, i, key; for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key, path) ); } if (!fn.$inject) { // this means that we must be an array. fn = fn[length]; } // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke switch (self ? -1 : args.length) { case 0: return fn(); case 1: return fn(args[0]); case 2: return fn(args[0], args[1]); case 3: return fn(args[0], args[1], args[2]); case 4: return fn(args[0], args[1], args[2], args[3]); case 5: return fn(args[0], args[1], args[2], args[3], args[4]); case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); default: return fn.apply(self, args); } } function instantiate(Type, locals) { var Constructor = function() {}, instance, returnedValue; Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); returnedValue = invoke(Type, instance, locals); return isObject(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate }; } } /** * @ngdoc function * @name ng.$anchorScroll * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks current value of `$location.hash()` and scroll to related element, * according to rules specified in * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. * * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice // TODO(vojta): use filter if we change it to accept lists as well function getFirstAnchor(list) { var result = null; forEach(list, function(element) { if (!result && lowercase(element.nodeName) === 'a') result = element; }); return result; } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) $window.scrollTo(0, 0); // element with given id else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') $window.scrollTo(0, 0); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $locaiton.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function() {return $location.hash();}, function() { $rootScope.$evalAsync(scroll); }); } return scroll; }]; } /** * ! This is a private undocumented service ! * * @name ng.$browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @name ng.$browser#addPollFn * @methodOf ng.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href, baseElement = document.find('base'); /** * @name ng.$browser#url * @methodOf ng.$browser * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // setter if (url) { lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else { history.pushState(null, '', url); // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 baseElement.attr('href', baseElement.attr('href')); } } else { if (replace) location.replace(url); else location.href = url; } return self; // getter } else { // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return location.href.replace(/%27/g,"'"); } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @name ng.$browser#onUrlChange * @methodOf ng.$browser * @TODO(vojta): refactor to use node's syntax for events * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed by outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * Returns current <base href> * (always relative - without domain) * * @returns {string=} */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); /** * @name ng.$browser#cookies * @methodOf ng.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1)); } } } return lastCookies; } }; /** * @name ng.$browser#defer * @methodOf ng.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchroniously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * @name ng.$browser#defer.cancel * @methodOf ng.$browser.defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider(){ this.$get = ['$window', '$log', '$sniffer', '$document', function( $window, $log, $sniffer, $document){ return new Browser($window, $document, $log, $sniffer); }]; } /** * @ngdoc object * @name ng.$cacheFactory * * @description * Factory that constructs cache objects. * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache. * - `{{*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key) — Removes a key-value pair from the cache. * - `{void}` `removeAll() — Removes all cached values. * - `{void}` `destroy() — Removes references to this cache from $cacheFactory. * */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw Error('cacheId ' + cacheId + ' taken'); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; return caches[cacheId] = { put: function(key, value) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } }, get: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); return data[key]; }, remove: function(key) { var lruEntry = lruHash[key]; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; delete data[key]; size--; }, removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } /** * @ngdoc object * @name ng.$templateCache * * @description * Cache used for storing html templates. * * See {@link ng.$cacheFactory $cacheFactory}. * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: * * - "node" - DOM Node * - "element" - DOM Element or Node * - "$node" or "$element" - jqLite-wrapped node or element * * * Compiler related stuff: * * - "linkFn" - linking fn of a single directive * - "nodeLinkFn" - function that aggregates all linking fns for a particular node * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) */ var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: '; /** * @ngdoc function * @name ng.$compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link ng.$rootScope.Scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link ng.$compileProvider.directive directives}. For each match it * executes corresponding template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link ng.directive:ngRepeat repeater} many-times, in which * case each call results in a view that is a DOM clone of the original template. * <doc:example module="compile"> <doc:source> <script> // declare a new module, and inject the $compileProvider angular.module('compile', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }) }); function Ctrl($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; } </script> <div ng-controller="Ctrl"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </doc:source> <doc:scenario> it('should auto compile', function() { expect(element('div[compile]').text()).toBe('Hello Angular'); input('html').enter('{{name}}!'); expect(element('div[compile]').text()).toBe('Angular!'); }); </doc:scenario> </doc:example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. * @param {number} maxPriority only apply directives lower then given priority (Only effects the * root element(s), not their children) * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the linking function returns the element of the template. It is either the original element * passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var element = $compile('<p>{{total}}</p>')(scope); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var templateHTML = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * For information on how the compiler works, see the * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ /** * @ngdoc service * @name ng.$compileProvider * @function * * @description */ /** * @ngdoc function * @name ng.$compileProvider#directive * @methodOf ng.$compileProvider * @function * * @description * Register a new directive with compiler * * @param {string} name name of the directive. * @param {function} directiveFactory An injectable directive factory function. * @returns {ng.$compileProvider} Self for chaining. */ $CompileProvider.$inject = ['$provide']; function $CompileProvider($provide) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: '; /** * @ngdoc function * @name ng.$compileProvider.directive * @methodOf ng.$compileProvider * @function * * @description * Register directives with the compiler. * * @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as * <code>ng-bind</code>). * @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more * info. */ this.directive = function registerDirective(name, directiveFactory) { if (isString(name)) { assertArg(directiveFactory, 'directive'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'A'; directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', '$controller', '$rootScope', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, $controller, $rootScope) { var Attributes = function(element, attr) { this.$$element = element; this.$attr = attr || {}; }; Attributes.prototype = { $normalize: directiveNormalize, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { var booleanKey = getBooleanAttrName(this.$$element[0], key), $$observers = this.$$observers; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers $$observers && forEach($$observers[key], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * Observe an interpolated attribute. * The observer will never be called, if given attribute is not interpolated. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(*)} fn Function that will be called whenever the attribute value changes. * @returns {function(*)} the `fn` Function passed in. */ $observe: function(key, fn) { var attrs = this, $$observers = (attrs.$$observers || (attrs.$$observers = {})), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { if (!listeners.$$inter) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); return fn; } }; return compile; //================================ function compile($compileNode, transcludeFn, maxPriority) { if (!($compileNode instanceof jqLite)) { // jquery always rewraps, where as we need to preserve the original selector so that we can modify it. $compileNode = jqLite($compileNode); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach($compileNode, function(node, index){ if (node.nodeType == 3 /* text node */) { $compileNode[index] = jqLite(node).wrap('<span>').parent()[0]; } }); var compositeLinkFn = compileNodes($compileNode, transcludeFn, $compileNode, maxPriority); return function(scope, cloneConnectFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var $linkNode = cloneConnectFn ? JQLitePrototype.clone.call($compileNode) // IMPORTANT!!! : $compileNode; $linkNode.data('$scope', scope); safeAddClass($linkNode, 'ng-scope'); if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode); return $linkNode; }; } function wrongMode(localName, mode) { throw Error("Unsupported '" + mode + "' for '" + localName + "'."); } function safeAddClass($element, className) { try { $element.addClass(className); } catch(e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes to compile * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the * rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} max directive priority * @returns {?function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) { var linkFns = [], nodeLinkFn, childLinkFn, directives, attrs, linkFnFound; for(var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, maxPriority); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement) : null; childLinkFn = (nodeLinkFn && nodeLinkFn.terminal) ? null : compileNodes(nodeList[i].childNodes, nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); linkFns.push(nodeLinkFn); linkFns.push(childLinkFn); linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn); } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) { var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn; for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) { node = nodeList[n]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(isObject(nodeLinkFn.scope)); jqLite(node).data('$scope', childScope); } else { childScope = scope; } childTranscludeFn = nodeLinkFn.transclude; if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) { nodeLinkFn(childLinkFn, childScope, node, $rootElement, (function(transcludeFn) { return function(cloneFn) { var transcludeScope = scope.$new(); return transcludeFn(transcludeScope, cloneFn). bind('$destroy', bind(transcludeScope, transcludeScope.$destroy)); }; })(childTranscludeFn || transcludeFn) ); } else { nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn); } } else if (childLinkFn) { childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn); } } } } /** * Looks for directives on the given node ands them to the directive collection which is sorted. * * @param node node to search * @param directives an array to which the directives are added to. This array is sorted before * the function returns. * @param attrs the shared attrs object which is used to populate the normalized attributes. * @param {number=} max directive priority */ function collectDirectives(node, directives, attrs, maxPriority) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch(nodeType) { case 1: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority); // iterate over the attributes for (var attr, name, nName, value, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { attr = nAttrs[j]; if (attr.specified) { name = attr.name; nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; attrs[nName] = value = trim((msie && name == 'href') ? decodeURIComponent(node.getAttribute(name, 2)) : attr.value); if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } addAttrInterpolateDirective(node, directives, value, nName); addDirective(directives, nName, 'A', maxPriority); } } // use class as directive className = node.className; if (isString(className)) { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case 3: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case 8: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Once the directives have been collected their compile functions is executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached.. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement} $rootElement If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace widgets on it. * @returns linkFn */ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) { var terminalPriority = -Number.MAX_VALUE, preLinkFns = [], postLinkFns = [], newScopeDirective = null, newIsolatedScopeDirective = null, templateDirective = null, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, transcludeDirective, childTranscludeFn = transcludeFn, controllerDirectives, linkFn, directiveValue; // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, $compileNode); if (isObject(directiveValue)) { safeAddClass($compileNode, 'ng-isolate-scope'); newIsolatedScopeDirective = directive; } safeAddClass($compileNode, 'ng-scope'); newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (directiveValue = directive.controller) { controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); transcludeDirective = directive; terminalPriority = directive.priority; if (directiveValue == 'element') { $template = jqLite(compileNode); $compileNode = templateAttrs.$$element = jqLite('<!-- ' + directiveName + ': ' + templateAttrs[directiveName] + ' -->'); compileNode = $compileNode[0]; replaceWith($rootElement, jqLite($template[0]), compileNode); childTranscludeFn = compile($template, transcludeFn, terminalPriority); } else { $template = jqLite(JQLiteClone(compileNode)).contents(); $compileNode.html(''); // clear contents childTranscludeFn = compile($template, transcludeFn); } } if (directiveValue = directive.template) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; $template = jqLite('<div>' + trim(directiveValue) + '</div>').contents(); compileNode = $template[0]; if (directive.replace) { if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue); } replaceWith($rootElement, $compileNode, compileNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that were already applied and those that weren't // - collect directives from the template, add them to the second group and sort them // - append the second group with new directives to the first group directives = directives.concat( collectDirectives( compileNode, directives.splice(i + 1, directives.length - (i + 1)), newTemplateAttrs ) ); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { $compileNode.html(directiveValue); } } if (directive.templateUrl) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace, childTranscludeFn); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { addLinkFns(null, linkFn); } else if (linkFn) { addLinkFns(linkFn.pre, linkFn.post); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); } } if (directive.terminal) { nodeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope; nodeLinkFn.transclude = transcludeDirective && childTranscludeFn; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// function addLinkFns(pre, post) { if (pre) { pre.require = directive.require; preLinkFns.push(pre); } if (post) { post.require = directive.require; postLinkFns.push(post); } } function getControllers(require, $element) { var value, retrievalMethod = 'data', optional = false; if (isString(require)) { while((value = require.charAt(0)) == '^' || value == '?') { require = require.substr(1); if (value == '^') { retrievalMethod = 'inheritedData'; } optional = optional || value == '?'; } value = $element[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw Error("No controller: " + require); } return value; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(require, $element)); }); } return value; } function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { var attrs, $element, i, ii, linkFn, controller; if (compileNode === linkNode) { attrs = templateAttrs; } else { attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); } $element = attrs.$$element; if (newScopeDirective && isObject(newScopeDirective.scope)) { var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/; var parentScope = scope.$parent || scope; forEach(newScopeDirective.scope, function(definiton, scopeName) { var match = definiton.match(LOCAL_REGEXP) || [], attrName = match[2]|| scopeName, mode = match[1], // @, =, or & lastValue, parentGet, parentSet; switch (mode) { case '@': { attrs.$observe(attrName, function(value) { scope[scopeName] = value; }); attrs.$$observers[attrName].$$scope = parentScope; break; } case '=': { parentGet = $parse(attrs[attrName]); parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest lastValue = scope[scopeName] = parentGet(parentScope); throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] + ' (directive: ' + newScopeDirective.name + ')'); }; lastValue = scope[scopeName] = parentGet(parentScope); scope.$watch(function() { var parentValue = parentGet(parentScope); if (parentValue !== scope[scopeName]) { // we are out of sync and need to copy if (parentValue !== lastValue) { // parent changed and it has precedence lastValue = scope[scopeName] = parentValue; } else { // if the parent can be assigned then do so parentSet(parentScope, lastValue = scope[scopeName]); } } return parentValue; }); break; } case '&': { parentGet = $parse(attrs[attrName]); scope[scopeName] = function(locals) { return parentGet(parentScope, locals); } break; } default: { throw Error('Invalid isolate scope definition for directive ' + newScopeDirective.name + ': ' + definiton); } } }); } if (controllerDirectives) { forEach(controllerDirectives, function(directive) { var locals = { $scope: scope, $element: $element, $attrs: attrs, $transclude: boundTranscludeFn }; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } $element.data( '$' + directive.name + 'Controller', $controller(controller, locals)); }); } // PRELINKING for(i = 0, ii = preLinkFns.length; i < ii; i++) { try { linkFn = preLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } // RECURSION childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for(i = 0, ii = postLinkFns.length; i < ii; i++) { try { linkFn = postLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority) { var match = false; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i<ii; i++) { try { directive = directives[i]; if ( (maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { tDirectives.push(directive); match = true; } } catch(e) { $exceptionHandler(e); } } } return match; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key]) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, $rootElement, replace, childTranscludeFn) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { controller: null, templateUrl: null, transclude: null }); $compileNode.html(''); $http.get(origAsyncDirective.templateUrl, {cache: $templateCache}). success(function(content) { var compileNode, tempTemplateAttrs, $template; if (replace) { $template = jqLite('<div>' + trim(content) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); collectDirectives(compileNode, directives, tempTemplateAttrs); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; $compileNode.html(content); } directives.unshift(derivedSyncDirective); afterTemplateNodeLinkFn = applyDirectivesToNode(directives, $compileNode, tAttrs, childTranscludeFn); afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn); while(linkQueue.length) { var controller = linkQueue.pop(), linkRootElement = linkQueue.pop(), beforeTemplateLinkNode = linkQueue.pop(), scope = linkQueue.pop(), linkNode = compileNode; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { // it was cloned therefore we have to clone as well. linkNode = JQLiteClone(compileNode); replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); } afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller); }, scope, linkNode, $rootElement, controller); } linkQueue = null; }). error(function(response, code, headers, config) { throw Error('Failed to load template: ' + config.url); }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) { if (linkQueue) { linkQueue.push(scope); linkQueue.push(node); linkQueue.push(rootElement); linkQueue.push(controller); } else { afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller); }, scope, node, rootElement, controller); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { return b.priority - a.priority; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw Error('Multiple directives [' + previousDirective.name + ', ' + directive.name + '] asking for ' + what + ' on: ' + startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: valueFn(function(scope, node) { var parent = node.parent(), bindings = parent.data('$binding') || []; bindings.push(interpolateFn); safeAddClass(parent.data('$binding', bindings), 'ng-binding'); scope.$watch(interpolateFn, function(value) { node[0].nodeValue = value; }); }) }); } } function addAttrInterpolateDirective(node, directives, value, name) { var interpolateFn = $interpolate(value, true); // no interpolation found -> ignore if (!interpolateFn) return; directives.push({ priority: 100, compile: valueFn(function(scope, element, attr) { var $$observers = (attr.$$observers || (attr.$$observers = {})); if (name === 'class') { // we need to interpolate classes again, in the case the element was replaced // and therefore the two class attrs got merged - we want to interpolate the result interpolateFn = $interpolate(attr[name], true); } attr[name] = undefined; ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function(value) { attr.$set(name, value); }); }) }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell, * but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith($rootElement, $element, newNode) { var oldNode = $element[0], parent = oldNode.parentNode, i, ii; if ($rootElement) { for(i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] == oldNode) { $rootElement[i] = newNode; break; } } } if (parent) { parent.replaceChild(newNode, oldNode); } newNode[jqLite.expando] = oldNode[jqLite.expando]; $element[0] = newNode; } }]; } var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': * my:DiRective * my-directive * x-my-directive * data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * @ngdoc object * @name ng.$compile.directive.Attributes * @description * * A shared object between directive compile / linking functions which contains normalized DOM element * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed * since all of these are treated as equivalent in Angular: * * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> */ /** * @ngdoc property * @name ng.$compile.directive.Attributes#$attr * @propertyOf ng.$compile.directive.Attributes * @returns {object} A map of DOM element attribute names to the normalized name. This is * needed to do reverse lookup from normalized name back to actual name. */ /** * @ngdoc function * @name ng.$compile.directive.Attributes#$set * @methodOf ng.$compile.directive.Attributes * @function * * @description * Set DOM element attribute value. * * * @param {string} name Normalized element attribute name of the property to modify. The name is * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. * @param {string} value Value to set the attribute to. */ /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} /** * @ngdoc object * @name ng.$controllerProvider * @description * The {@link ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}; /** * @ngdoc function * @name ng.$controllerProvider#register * @methodOf ng.$controllerProvider * @param {string} name Controller name * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { if (isObject(name)) { extend(controllers, name) } else { controllers[name] = constructor; } }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc function * @name ng.$controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * check `window[constructor]` on the global `window` object * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just simple call to {@link AUTO.$injector $injector}, but extracted into * a service, so that one can override this service with {@link https://gist.github.com/1649788 * BC version}. */ return function(constructor, locals) { if(isString(constructor)) { var name = constructor; constructor = controllers.hasOwnProperty(name) ? controllers[name] : getter(locals.$scope, name, true) || getter($window, name, true); assertArgFn(constructor, name, true); } return $injector.instantiate(constructor, locals); }; }]; } /** * @ngdoc object * @name ng.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ function $DocumentProvider(){ this.$get = ['$window', function(window){ return jqLite(window.document); }]; } /** * @ngdoc function * @name ng.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log){ return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } /** * @ngdoc function * @name ng.$interpolateProvider * @function * * @description * * Used for configuring the interpolation markup. Deafults to `{{` and `}}`. */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name ng.$interpolateProvider#startSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @prop {string=} value new value to set the starting symbol to. */ this.startSymbol = function(value){ if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name ng.$interpolateProvider#endSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @prop {string=} value new value to set the ending symbol to. */ this.endSymbol = function(value){ if (value) { endSymbol = value; return this; } else { return startSymbol; } }; this.$get = ['$parse', function($parse) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length; /** * @ngdoc function * @name ng.$interpolate * @function * * @requires $parse * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link ng.$compile $compile} service for data binding. See * {@link ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * <pre> var $interpolate = ...; // injected var exp = $interpolate('Hello {{name}}!'); expect(exp({name:'Angular'}).toEqual('Hello Angular!'); </pre> * * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @returns {function(context)} an interpolation function which is used to compute the interpolated * string. The function has these parameters: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against. * */ return function(text, mustHaveExpression) { var startIndex, endIndex, index = 0, parts = [], length = text.length, hasInterpolation = false, fn, exp, concat = []; while(index < length) { if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { (index != startIndex) && parts.push(text.substring(index, startIndex)); parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); fn.exp = exp; index = endIndex + endSymbolLength; hasInterpolation = true; } else { // we did not find anything, so we have to add the remainder to the parts array (index != length) && parts.push(text.substring(index)); index = length; } } if (!(length = parts.length)) { // we added, nothing, must have been an empty string. parts.push(''); length = 1; } if (!mustHaveExpression || hasInterpolation) { concat.length = length; fn = function(context) { for(var i = 0, ii = length, part; i<ii; i++) { if (typeof (part = parts[i]) == 'function') { part = part(context); if (part == null || part == undefined) { part = ''; } else if (typeof part != 'string') { part = toJson(part); } } concat[i] = part; } return concat.join(''); }; fn.exp = text; fn.parts = parts; return fn; } }; }]; } var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = PATH_MATCH, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function stripHash(url) { return url.split('#')[0]; } function matchUrl(url, obj) { var match = URL_MATCH.exec(url); match = { protocol: match[1], host: match[3], port: int(match[5]) || DEFAULT_PORTS[match[1]] || null, path: match[6] || '/', search: match[8], hash: match[10] }; if (obj) { obj.$$protocol = match.protocol; obj.$$host = match.host; obj.$$port = match.port; } return match; } function composeProtocolHostPort(protocol, host, port) { return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); } function pathPrefixFromBase(basePath) { return basePath.substr(0, basePath.lastIndexOf('/')); } function convertToHtml5Url(url, basePath, hashPrefix) { var match = matchUrl(url); // already html5 url if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) || match.hash.indexOf(hashPrefix) !== 0) { return url; // convert hashbang url -> html5 url } else { return composeProtocolHostPort(match.protocol, match.host, match.port) + pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length); } } function convertToHashbangUrl(url, basePath, hashPrefix) { var match = matchUrl(url); // already hashbang url if (decodeURIComponent(match.path) == basePath) { return url; // convert html5 url -> hashbang url } else { var search = match.search && '?' + match.search || '', hash = match.hash && '#' + match.hash || '', pathPrefix = pathPrefixFromBase(basePath), path = match.path.substr(pathPrefix.length); if (match.path.indexOf(pathPrefix) !== 0) { throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'); } return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath + '#' + hashPrefix + path + search + hash; } } /** * LocationUrl represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} url HTML5 url * @param {string} pathPrefix */ function LocationUrl(url, pathPrefix, appBaseUrl) { pathPrefix = pathPrefix || ''; /** * Parse given html5 (regular) url string into properties * @param {string} newAbsoluteUrl HTML5 url * @private */ this.$$parse = function(newAbsoluteUrl) { var match = matchUrl(newAbsoluteUrl, this); if (match.path.indexOf(pathPrefix) !== 0) { throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !'); } this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length)); this.$$search = parseKeyValue(match.search); this.$$hash = match.hash && decodeURIComponent(match.hash) || ''; this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + pathPrefix + this.$$url; }; this.$$rewriteAppUrl = function(absoluteLinkUrl) { if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { return absoluteLinkUrl; } } this.$$parse(url); } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is disabled or not supported * * @constructor * @param {string} url Legacy url * @param {string} hashPrefix Prefix for hash part (containing path and search) */ function LocationHashbangUrl(url, hashPrefix, appBaseUrl) { var basePath; /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.hash && match.hash.indexOf(hashPrefix) !== 0) { throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !'); } basePath = match.path + (match.search ? '?' + match.search : ''); match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length)); if (match[1]) { this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]); } else { this.$$path = ''; } this.$$search = parseKeyValue(match[3]); this.$$hash = match[5] && decodeURIComponent(match[5]) || ''; this.$$compose(); }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + basePath + (this.$$url ? '#' + hashPrefix + this.$$url : ''); }; this.$$rewriteAppUrl = function(absoluteLinkUrl) { if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { return absoluteLinkUrl; } } this.$$parse(url); } LocationUrl.prototype = { /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name ng.$location#absUrl * @methodOf ng.$location * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. * * @return {string} full url */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name ng.$location#url * @methodOf ng.$location * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} url */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1]) this.path(decodeURIComponent(match[1])); if (match[2] || match[1]) this.search(match[3] || ''); this.hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name ng.$location#protocol * @methodOf ng.$location * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} protocol of current url */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name ng.$location#host * @methodOf ng.$location * * @description * This method is getter only. * * Return host of current url. * * @return {string} host of current url. */ host: locationGetter('$$host'), /** * @ngdoc method * @name ng.$location#port * @methodOf ng.$location * * @description * This method is getter only. * * Return port of current url. * * @return {Number} port */ port: locationGetter('$$port'), /** * @ngdoc method * @name ng.$location#path * @methodOf ng.$location * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} path */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name ng.$location#search * @methodOf ng.$location * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * @param {string|object<string,string>=} search New search params - string or hash object * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a * single search parameter. If the value is `null`, the parameter will be deleted. * * @return {string} search */ search: function(search, paramValue) { if (isUndefined(search)) return this.$$search; if (isDefined(paramValue)) { if (paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } else { this.$$search = isString(search) ? parseKeyValue(search) : search; } this.$$compose(); return this; }, /** * @ngdoc method * @name ng.$location#hash * @methodOf ng.$location * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} hash */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name ng.$location#replace * @methodOf ng.$location * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; LocationHashbangUrl.prototype = inherit(LocationUrl.prototype); function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) { LocationHashbangUrl.apply(this, arguments); this.$$rewriteAppUrl = function(absoluteLinkUrl) { if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) { return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length); } } } LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype); function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc object * @name ng.$location * * @requires $browser * @requires $sniffer * @requires $rootElement * * @description * The $location service parses the URL in the browser address bar (based on the * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL * available to your application. Changes to the URL in the address bar are reflected into * $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular * Services: Using $location} */ /** * @ngdoc object * @name ng.$locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider(){ var hashPrefix = '', html5Mode = false; /** * @ngdoc property * @name ng.$locationProvider#hashPrefix * @methodOf ng.$locationProvider * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc property * @name ng.$locationProvider#html5Mode * @methodOf ng.$locationProvider * @description * @param {string=} mode Use HTML5 strategy if available. * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isDefined(mode)) { html5Mode = mode; return this; } else { return html5Mode; } }; this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', function( $rootScope, $browser, $sniffer, $rootElement) { var $location, basePath, pathPrefix, initUrl = $browser.url(), initUrlParts = matchUrl(initUrl), appBaseUrl; if (html5Mode) { basePath = $browser.baseHref() || '/'; pathPrefix = pathPrefixFromBase(basePath); appBaseUrl = composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + pathPrefix + '/'; if ($sniffer.history) { $location = new LocationUrl( convertToHtml5Url(initUrl, basePath, hashPrefix), pathPrefix, appBaseUrl); } else { $location = new LocationHashbangInHtml5Url( convertToHashbangUrl(initUrl, basePath, hashPrefix), hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1)); } } else { appBaseUrl = composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + (initUrlParts.path || '') + (initUrlParts.search ? ('?' + initUrlParts.search) : '') + '#' + hashPrefix + '/'; $location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl); } $rootElement.bind('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (lowercase(elm[0].nodeName) !== 'a') { if (elm[0] === $rootElement[0]) return; elm = elm.parent(); } var absHref = elm.prop('href'), rewrittenUrl = $location.$$rewriteAppUrl(absHref); if (absHref && !elm.attr('target') && rewrittenUrl) { // update location manually $location.$$parse(rewrittenUrl); $rootScope.$apply(); event.preventDefault(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; } }); // rewrite hashbang url <> html5 url if ($location.absUrl() != initUrl) { $browser.url($location.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if ($location.absUrl() != newUrl) { $rootScope.$evalAsync(function() { var oldUrl = $location.absUrl(); $location.$$parse(newUrl); afterLocationChange(oldUrl); }); if (!$rootScope.$$phase) $rootScope.$digest(); } }); // update browser var changeCounter = 0; $rootScope.$watch(function $locationWatch() { var oldUrl = $browser.url(); if (!changeCounter || oldUrl != $location.absUrl()) { changeCounter++; $rootScope.$evalAsync(function() { if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). defaultPrevented) { $location.$$parse(oldUrl); } else { $browser.url($location.absUrl(), $location.$$replace); $location.$$replace = false; afterLocationChange(oldUrl); } }); } return changeCounter; }); return $location; function afterLocationChange(oldUrl) { $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); } }]; } /** * @ngdoc object * @name ng.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <doc:example> <doc:source> <script> function LogCtrl($log) { this.$log = $log; this.message = 'Hello World!'; } </script> <div ng-controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ function $LogProvider(){ this.$get = ['$window', function($window){ return { /** * @ngdoc method * @name ng.$log#log * @methodOf ng.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name ng.$log#warn * @methodOf ng.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name ng.$log#info * @methodOf ng.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name ng.$log#error * @methodOf ng.$log * * @description * Write an error message */ error: consoleLog('error') }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop; if (logFn.apply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2); } } }]; } var OPERATORS = { 'null':function(){return null;}, 'true':function(){return true;}, 'false':function(){return false;}, undefined:noop, '+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, '=':noop, '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, // '|':function(self, locals, a,b){return a|b;}, '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, '!':function(self, locals, a){return !a(self, locals);} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, csp){ var tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function() {return number;}}); } function readIdent() { var ident = "", start = index, lastDot, peekIndex, methodName; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { if (ch == '.') lastDot = index; ident += ch; } else { break; } index++; } //check if this is not a method invocation and if it is back out to last dot if (lastDot) { peekIndex = index; while(peekIndex < text.length) { var ch = text.charAt(peekIndex); if (ch == '(') { methodName = ident.substr(lastDot - start + 1); ident = ident.substr(0, lastDot - start); index = peekIndex; break; } if(isWhitespace(ch)) { peekIndex++; } else { break; } } } var token = { index:start, text:ident }; if (OPERATORS.hasOwnProperty(ident)) { token.fn = token.json = OPERATORS[ident]; } else { var getter = getterFn(ident, csp); token.fn = extend(function(self, locals) { return (getter(self, locals)); }, { assign: function(self, value) { return setter(self, ident, value); } }); } tokens.push(token); if (methodName) { tokens.push({ index:lastDot, text: '.', json: false }); tokens.push({ index: lastDot + 1, text: methodName, json: false }); } } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({ index:start, text:rawString, string:string, json:true, fn:function() { return string; } }); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json, $filter, csp){ var ZERO = valueFn(0), value, tokens = lex(text, csp), assignment = _assignment, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = filterChain = function() { throwError("is not valid json", {text:text, index:0}); }; value = primary(); } else { value = statements(); } if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } return value; /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return function(self, locals) { return fn(self, locals, right); }; } function binaryFn(left, fn, right) { return function(self, locals) { return fn(self, locals, left, right); }; } function statements() { var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function(self, locals){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self, locals); } return value; }; } } } function _filterChain() { var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter() { var token = expect(); var fn = $filter(token.text); var argsFn = []; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, locals, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } return fn.apply(self, args); }; return function() { return fnInvoke; }; } } } function expression() { return assignment(); } function _assignment() { var left = logicalOR(); var right; var token; if ((token = expect('='))) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = logicalOR(); return function(self, locals){ return left.assign(self, right(self, locals), locals); }; } else { return left; } } function logicalOR() { var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND() { var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality() { var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational() { var left = additive(); var token; if ((token = expect('<', '>', '<=', '>='))) { left = binaryFn(left, token.fn, relational()); } return left; } function additive() { var left = multiplicative(); var token; while ((token = expect('+','-'))) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative() { var left = unary(); var token; while ((token = expect('*','/','%'))) { left = binaryFn(left, token.fn, unary()); } return left; } function unary() { var token; if (expect('+')) { return primary(); } else if ((token = expect('-'))) { return binaryFn(ZERO, token.fn, unary()); } else if ((token = expect('!'))) { return unaryFn(token.fn, unary()); } else { return primary(); } } function primary() { var primary; if (expect('(')) { primary = filterChain(); consume(')'); } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } } var next, context; while ((next = expect('(', '[', '.'))) { if (next.text === '(') { primary = functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = objectIndex(primary); } else if (next.text === '.') { context = primary; primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field, csp); return extend( function(self, locals) { return getter(object(self, locals), locals); }, { assign:function(self, value, locals) { return setter(object(self, locals), field, value); } } ); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function(self, locals){ var o = obj(self, locals), i = indexFn(self, locals), v, p; if (!o) return undefined; v = o[i]; if (v && v.then) { p = v; if (!('$$v' in v)) { p.$$v = undefined; p.then(function(val) { p.$$v = val; }); } v = v.$$v; } return v; }, { assign:function(self, value, locals){ return obj(self, locals)[indexFn(self, locals)] = value; } }); } function _functionCall(fn, contextGetter) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function(self, locals){ var args = [], context = contextGetter ? contextGetter(self, locals) : self; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } var fnPtr = fn(self, locals) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(context, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function(self, locals){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self, locals)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function(self, locals){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self, locals); object[keyValue.key] = value; } return object; }; } } ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue) { var element = path.split('.'); for (var i = 0; element.length > 1; i++) { var key = element.shift(); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } obj[element.shift()] = setValue; return setValue; } /** * Return the value accesible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {string} path path to traverse * @param {boolean=true} bindFnToScope * @returns value as accesbile by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } var getterFnCache = {}; /** * Implementation of the "Black Hole" variant from: * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ function cspSafeGetterFn(key0, key1, key2, key3, key4) { return function(scope, locals) { var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, promise; if (pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key0]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key1 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key1]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key2 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key2]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key3 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key3]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key4 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key4]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } return pathVal; }; }; function getterFn(path, csp) { if (getterFnCache.hasOwnProperty(path)) { return getterFnCache[path]; } var pathKeys = path.split('.'), pathKeysLength = pathKeys.length, fn; if (csp) { fn = (pathKeysLength < 6) ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4]) : function(scope, locals) { var i = 0, val do { val = cspSafeGetterFn( pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++] )(scope, locals); locals = undefined; // clear after first iteration scope = val; } while (i < pathKeysLength); return val; } } else { var code = 'var l, fn, p;\n'; forEach(pathKeys, function(key, index) { code += 'if(s === null || s === undefined) return s;\n' + 'l=s;\n' + 's='+ (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + 'if (s && s.then) {\n' + ' if (!("$$v" in s)) {\n' + ' p=s;\n' + ' p.$$v = undefined;\n' + ' p.then(function(v) {p.$$v=v;});\n' + '}\n' + ' s=s.$$v\n' + '}\n'; }); code += 'return s;'; fn = Function('s', 'k', code); // s=scope, k=locals fn.toString = function() { return code; }; } return getterFnCache[path] = fn; } /////////////////////////////////// /** * @ngdoc function * @name ng.$parse * @function * * @description * * Converts Angular {@link guide/expression expression} into a function. * * <pre> * var getter = $parse('user.name'); * var setter = getter.assign; * var context = {user:{name:'angular'}}; * var locals = {user:{name:'local'}}; * * expect(getter(context)).toEqual('angular'); * setter(context, 'newValue'); * expect(context.user.name).toEqual('newValue'); * expect(getter(context, locals)).toEqual('local'); * </pre> * * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against (Topically a scope object). * * `locals`: local variables context object, useful for overriding values in `context`. * * The return function also has an `assign` property, if the expression is assignable, which * allows one to set values to expressions. * */ function $ParseProvider() { var cache = {}; this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { return function(exp) { switch(typeof exp) { case 'string': return cache.hasOwnProperty(exp) ? cache[exp] : cache[exp] = parser(exp, false, $filter, $sniffer.csp); case 'function': return exp; default: return noop; } }; }]; } /** * @ngdoc service * @name ng.$q * @requires $rootScope * * @description * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise apis are to * asynchronous programing what `try`, `catch` and `throw` keywords are to synchronous programing. * * <pre> * // for the purpose of this example let's assume that variables `$q` and `scope` are * // available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * // since this fn executes async in a future turn of the event loop, we need to wrap * // our code into an $apply call so that the model changes are properly observed. * scope.$apply(function() { * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }); * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * ); * </pre> * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of * [guarantees that promise and deferred apis make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as apis * that can be used for signaling the successful or unsuccessful completion of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved * or rejected calls one of the success or error callbacks asynchronously as soon as the result * is available. The callbacks are called with a single argument the result or rejection reason. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback` or `errorCallback`. * * * # Chaining promises * * Because calling `then` api of a promise returns a new derived promise, it is easily possible * to create a chain of promises: * * <pre> * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and it's value will be * // the result of promiseA incremented by 1 * </pre> * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful apis like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are three main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - $q promises are recognized by the templating engine in angular, which means that in templates * you can treat promises attached to a scope as if they were the resulting values. * - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { /** * @ngdoc * @name ng.$q#defer * @methodOf ng.$q * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { var pending = [], value, deferred; deferred = { resolve: function(val) { if (pending) { var callbacks = pending; pending = undefined; value = ref(val); if (callbacks.length) { nextTick(function() { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; value.then(callback[0], callback[1]); } }); } } }, reject: function(reason) { deferred.resolve(reject(reason)); }, promise: { then: function(callback, errback) { var result = defer(); var wrappedCallback = function(value) { try { result.resolve((callback || defaultCallback)(value)); } catch(e) { exceptionHandler(e); result.reject(e); } }; var wrappedErrback = function(reason) { try { result.resolve((errback || defaultErrback)(reason)); } catch(e) { exceptionHandler(e); result.reject(e); } }; if (pending) { pending.push([wrappedCallback, wrappedErrback]); } else { value.then(wrappedCallback, wrappedErrback); } return result.promise; } } }; return deferred; }; var ref = function(value) { if (value && value.then) return value; return { then: function(callback) { var result = defer(); nextTick(function() { result.resolve(callback(value)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#reject * @methodOf ng.$q * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * <pre> * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * </pre> * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { return { then: function(callback, errback) { var result = defer(); nextTick(function() { result.resolve((errback || defaultErrback)(reason)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#when * @methodOf ng.$q * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with on object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value coresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ var when = function(value, callback, errback) { var result = defer(), done; var wrappedCallback = function(value) { try { return (callback || defaultCallback)(value); } catch (e) { exceptionHandler(e); return reject(e); } }; var wrappedErrback = function(reason) { try { return (errback || defaultErrback)(reason); } catch (e) { exceptionHandler(e); return reject(e); } }; nextTick(function() { ref(value).then(function(value) { if (done) return; done = true; result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); }, function(reason) { if (done) return; done = true; result.resolve(wrappedErrback(reason)); }); }); return result.promise; }; function defaultCallback(value) { return value; } function defaultErrback(reason) { return reject(reason); } /** * @ngdoc * @name ng.$q#all * @methodOf ng.$q * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>} promises An array of promises. * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value coresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ function all(promises) { var deferred = defer(), counter = promises.length, results = []; if (counter) { forEach(promises, function(promise, index) { ref(promise).then(function(value) { if (index in results) return; results[index] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (index in results) return; deferred.reject(reason); }); }); } else { deferred.resolve(results); } return deferred.promise; } return { defer: defer, reject: reject, when: when, all: all }; } /** * @ngdoc object * @name ng.$routeProvider * @function * * @description * * Used for configuring routes. See {@link ng.$route $route} for an example. */ function $RouteProvider(){ var routes = {}; /** * @ngdoc method * @name ng.$routeProvider#when * @methodOf ng.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exacly match the * route definition. * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{function()=}` – Controller fn that should be associated with newly * created scope. * - `template` – `{string=}` – html template as a string that should be used by * {@link ng.directive:ngView ngView} or * {@link ng.directive:ngInclude ngInclude} directives. * this property takes precedence over `templateUrl`. * - `templateUrl` – `{string=}` – path to an html template that should be used by * {@link ng.directive:ngView ngView}. * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, they will be * resolved and converted to a value before the controller is instantiated and the * `$aftreRouteChange` event is fired. The map object is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is resolved * before its value is injected into the controller. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() * changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = extend({reloadOnSearch: true}, route); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = {redirectTo: path}; } return this; }; /** * @ngdoc method * @name ng.$routeProvider#otherwise * @methodOf ng.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) { /** * @ngdoc object * @name ng.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * Is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * You can define routes through {@link ng.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView} * directive and the {@link ng.$routeParams $routeParams} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); sleep(2); // promises are not part of scenario waiting content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.$route#$routeChangeStart * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occurs. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ng.$route#$routeChangeSuccess * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ng.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. */ /** * @ngdoc event * @name ng.$route#$routeChangeError * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ng.$route#$routeUpdate * @eventOf ng.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var matcher = switchRouteMatcher, forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ng.$route#reload * @methodOf ng.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ng.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// function switchRouteMatcher(on, when) { // TODO(i): this code is convoluted and inefficient, we should construct the route matching // regex only once and then reuse it var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$', params = [], dst = {}; forEach(when.split(/\W/), function(param) { if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { forEach(params, function(name, index) { dst[name] = match[index + 1]; }); } return match ? dst : null; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$route === last.$route && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var keys = [], values = [], template; forEach(next.resolve || {}, function(value, key) { keys.push(key); values.push(isFunction(value) ? $injector.invoke(value) : $injector.get(value)); }); if (isDefined(template = next.template)) { } else if (isDefined(template = next.templateUrl)) { template = $http.get(template, {cache: $templateCache}). then(function(response) { return response.data; }); } if (isDefined(template)) { keys.push('$template'); values.push(template); } return $q.all(values).then(function(values) { var locals = {}; forEach(values, function(value, index) { locals[keys[index]] = value; }); return locals; }); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; forEach(routes, function(route, path) { if (!match && (params = matcher($location.path(), path))) { match = inherit(route, { params: extend({}, $location.search(), params), pathParams: params}); match.$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parametrs */ function interpolate(string, params) { var result = []; forEach((string||'').split(':'), function(segment, i) { if (i == 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } /** * @ngdoc object * @name ng.$routeParams * @requires $route * * @description * Current set of route parameters. The route parameters are a combination of the * {@link ng.$location $location} `search()`, and `path()`. The `path` parameters * are extracted when the {@link ng.$route $route} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = valueFn({}); } /** * DESIGN NOTES * * The design decisions behind the scope ware heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive from speed as well as memory: * - no closures, instead ups prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the begging (shift) instead of at the end (push) * * Child scopes are created and removed often * - Using array would be slow since inserts in meddle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc object * @name ng.$rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc function * @name ng.$rootScopeProvider#digestTtl * @methodOf ng.$rootScopeProvider * @description * * Sets the number of digest iteration the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc object * @name ng.$rootScope * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide * event processing life-cycle. See {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider(){ var TTL = 10; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', function( $injector, $exceptionHandler, $parse) { /** * @ngdoc function * @name ng.$rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link AUTO.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> angular.injector(['ng']).invoke(function($rootScope) { var scope = $rootScope.$new(); scope.salutation = 'Hello'; scope.name = 'World'; expect(scope.greeting).toEqual(undefined); scope.$watch('name', function() { this.greeting = this.salutation + ' ' + this.name + '!'; }); // initialize the watch expect(scope.greeting).toEqual(undefined); scope.name = 'Misko'; // still old value, since watches have not been called yet expect(scope.greeting).toEqual(undefined); scope.$digest(); // fire all the watches expect(scope.greeting).toEqual('Hello Misko!'); }); * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Defaults to {@link ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy when unit-testing and having * the need to override a default service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this['this'] = this.$root = this; this.$$asyncQueue = []; this.$$listeners = {}; } /** * @ngdoc property * @name ng.$rootScope.Scope#$id * @propertyOf ng.$rootScope.Scope * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ Scope.prototype = { /** * @ngdoc function * @name ng.$rootScope.Scope#$new * @methodOf ng.$rootScope.Scope * @function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * * @param {boolean} isolate if true then the scoped does not prototypically inherit from the * parent scope. The scope is isolated, as it can not se parent scope properties. * When creating widgets it is useful for the widget to not accidently read parent * state. * * @returns {Object} The newly created child scope. * */ $new: function(isolate) { var Child, child; if (isFunction(isolate)) { // TODO: remove at some point throw Error('API-CHANGE: Use $controller to instantiate controllers.'); } if (isolate) { child = new Scope(); child.$root = this.$root; } else { Child = function() {}; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. These will then show up as class // name in the debugger. Child.prototype = this; child = new Child(); child.$id = nextUid(); } child['this'] = child; child.$$listeners = {}; child.$parent = this; child.$$asyncQueue = []; child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } return child; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$watch * @methodOf ng.$rootScope.Scope * @function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()} * reruns when it detects changes the `watchExpression` can execute multiple times per * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression' are not equal (with the exception of the initial run * see below). The inequality is determined according to * {@link angular.equals} function. To save the value of the object for later comparison * {@link angular.copy} function is used. It also means that watching complex options will * have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This * is achieved by rerunning the watchers until no changes are detected. The rerun iteration * limit is 100 to prevent infinity loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`, * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is * detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * # Example * <pre> // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a * call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. * * @param {boolean=} objectEquality Compare object for equality rather then for refference. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var scope = this, get = compileToFn(watchExp, 'watch'), array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; // in the case user pass string, we need to compile it, do we really need this ? if (!isFunction(listener)) { var listenFn = compileToFn(listener || noop, 'listener'); watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function() { arrayRemove(array, watcher); }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$digest * @methodOf ng.$rootScope.Scope * @function * * @description * Process all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children. * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are * firing. This means that it is possible to get into an infinite loop. This function will throw * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10. * * Usually you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider.directive directives}. * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a * {@link ng.$compileProvider.directive directives}) will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()} * with no `listener`. * * You may have a need to call `$digest()` from within unit-tests, to simulate the scope * life-cycle. * * # Example * <pre> var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * */ $digest: function() { var watch, value, last, watchers, asyncQueue, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, logMsg; beginPhase('$digest'); do { dirty = false; current = target; do { asyncQueue = current.$$asyncQueue; while(asyncQueue.length) { try { current.$eval(asyncQueue.shift()); } catch (e) { $exceptionHandler(e); } } if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value == 'number' && typeof last == 'number' && isNaN(value) && isNaN(last)))) { dirty = true; watch.last = watch.eq ? copy(value) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; logMsg = (isFunction(watch.exp)) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp; logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); watchLog[logIdx].push(logMsg); } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); if(dirty && !(ttl--)) { clearPhase(); throw Error(TTL + ' $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: ' + toJson(watchLog)); } } while (dirty || asyncQueue.length); clearPhase(); }, /** * @ngdoc event * @name ng.$rootScope.Scope#$destroy * @eventOf ng.$rootScope.Scope * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. */ /** * @ngdoc function * @name ng.$rootScope.Scope#$destroy * @methodOf ng.$rootScope.Scope * @function * * @description * Remove the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it chance to * perform any necessary cleanup. */ $destroy: function() { if ($rootScope == this) return; // we can't remove the root node; var parent = this.$parent; this.$broadcast('$destroy'); if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$eval * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating engular expressions. * * # Example * <pre> var scope = ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * </pre> * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$evalAsync * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: * * - it will execute in the current script execution context (before any DOM rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { this.$$asyncQueue.push(expr); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$apply * @methodOf ng.$rootScope.Scope * @function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular framework. * (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life-cycle * of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` * <pre> function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * </pre> * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/expression expression} is executed using the * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } } }, /** * @ngdoc function * @name ng.$rootScope.Scope#$on * @methodOf ng.$rootScope.Scope * @function * * @description * Listen on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of * event life cycle. * * @param {string} name Event name to listen on. * @param {function(event)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. * * The event listener function format is: `function(event)`. The `event` object passed into the * listener has the following attributes * * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed. * - `currentScope` - {Scope}: the current scope which is handling the event. * - `name` - {string}: Name of the event. * - `stopPropagation` - {function=}: calling `stopPropagation` function will cancel further event propagation * (available only for events that were `$emit`-ed). * - `preventDefault` - {function}: calling `preventDefault` sets `defaultPrevented` flag to true. * - `defaultPrevented` - {boolean}: true if `preventDefault` was called. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); return function() { arrayRemove(namedListeners, listener); }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$emit * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event traverses upwards toward the root scope and calls all registered * listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { try { namedListeners[i].apply(null, listenerArgs); if (stopPropagation) return event; } catch (e) { $exceptionHandler(e); } } //traverse upwards scope = scope.$parent; } while (scope); return event; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$broadcast * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event propagates to all direct and indirect scopes of the current scope and * calls all registered listeners along the way. The event cannot be canceled. * * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1); //down while you can, then up and next sibling or up and next sibling until back at root do { current = next; event.currentScope = current; forEach(current.$$listeners[name], function(listener) { try { listener.apply(null, listenerArgs); } catch(e) { $exceptionHandler(e); } }); // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); return event; } }; var $rootScope = new Scope(); return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw Error($rootScope.$$phase + ' already in progress'); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function compileToFn(exp, name) { var fn = $parse(exp); assertArgFn(fn, name); return fn; } /** * function used as an initial value for watchers. * because it's uniqueue we can easily tell it apart from other values */ function initWatchVal() {} }]; } /** * !!! This is an undocumented "private" service !!! * * @name ng.$sniffer * @requires $window * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', function($window) { var eventSupport = {}, android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]); return { // Android has history.pushState, but it does not update location correctly // so let's not use the history API at all. // http://code.google.com/p/android/issues/detail?id=17471 // https://github.com/angular/angular.js/issues/904 history: !!($window.history && $window.history.pushState && !(android < 4)), hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!$window.document.documentMode || $window.document.documentMode > 7), hasEvent: function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. if (event == 'input' && msie == 9) return false; if (isUndefined(eventSupport[event])) { var divElm = $window.document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }, // TODO(i): currently there is no way to feature detect CSP without triggering alerts csp: false }; }]; } /** * @ngdoc object * @name ng.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" /> <button ng-click="$window.alert(greeting)">ALERT</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ function $WindowProvider(){ this.$get = valueFn(window); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { if (parsed[key]) { parsed[key] += ', ' + val; } else { parsed[key] = val; } } }); return parsed; } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers Http headers getter fn. * @param {(function|Array.<function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, fns) { if (isFunction(fns)) return fns(data, headers); forEach(fns, function(fn) { data = fn(data, headers); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } function $HttpProvider() { var JSON_START = /^\s*(\[|\{[^\{])/, JSON_END = /[\}\]]\s*$/, PROTECTION_PREFIX = /^\)\]\}',?\n/; var $config = this.defaults = { // transform incoming response data transformResponse: [function(data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data, true); } return data; }], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*', 'X-Requested-With': 'XMLHttpRequest' }, post: {'Content-Type': 'application/json;charset=utf-8'}, put: {'Content-Type': 'application/json;charset=utf-8'} } }; var providerResponseInterceptors = this.responseInterceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'), responseInterceptors = []; forEach(providerResponseInterceptors, function(interceptor) { responseInterceptors.push( isString(interceptor) ? $injector.get(interceptor) : $injector.invoke(interceptor) ); }); /** * @ngdoc function * @name ng.$http * @requires $httpBacked * @requires $browser * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patters this doesn't matter much, for advanced usage, * it is important to familiarize yourself with these apis and guarantees they provide. * * * # General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an http request and returns a {@link ng.$q promise} * with two $http specific methods: `success` and `error`. * * <pre> * $http({method: 'GET', url: '/someUrl'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with status * // code outside of the <200, 400) range * }); * </pre> * * Since the returned value of calling the $http function is a Promise object, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the api signature and type info below for more * details. * * * # Shortcut methods * * Since all invocation of the $http service require definition of the http method and url and * POST and PUT requests require response body/data to be provided as well, shortcut methods * were created to simplify using the api: * * <pre> * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * </pre> * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * * * # Setting HTTP Headers * * The $http service will automatically add certain http headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `X-Requested-With: XMLHttpRequest` * - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from this configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with name equal to the lower-cased http method name, e.g. * `$httpProvider.defaults.headers.get['My-Header']='value'`. * * Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar * fassion as described above. * * * # Transforming Requests and Responses * * Both requests and responses can be transformed using transform functions. By default, Angular * applies these transformations: * * Request transformations: * * - if the `data` property of the request config object contains an object, serialize it into * JSON format. * * Response transformations: * * - if XSRF prefix is detected, strip it (see Security Considerations section below) * - if json response is detected, deserialize it using a JSON parser * * To override these transformation locally, specify transform functions as `transformRequest` * and/or `transformResponse` properties of the config object. To globally override the default * transforms, override the `$httpProvider.defaults.transformRequest` and * `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`. * * * # Caching * * To enable caching set the configuration property `cache` to `true`. When the cache is * enabled, `$http` stores the response from the server in local cache. Next time the * response is served from the cache without sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same url that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response for the first request. * * * # Response interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication or any kind of synchronous or * asynchronous preprocessing of received responses, it is desirable to be able to intercept * responses for http requests before they are handed over to the application code that * initiated these requests. The response interceptors leverage the {@link ng.$q * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. * * The interceptors are service factories that are registered with the $httpProvider by * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor — a function that * takes a {@link ng.$q promise} and returns the original or a new promise. * * <pre> * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return function(promise) { * return promise.then(function(response) { * // do something on success * }, function(response) { * // do something on error * if (canRecover(response)) { * return responseOrNewPromise * } * return $q.reject(response); * }); * } * }); * * $httpProvider.responseInterceptors.push('myHttpInterceptor'); * * * // register the interceptor via an anonymous factory * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { * return function(promise) { * // same as above * } * }); * </pre> * * * # Security Considerations * * When designing web applications, consider security threats from: * * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * Angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which * an unauthorized site can gain your user's private data. Angular provides following mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that * runs on your domain could read the cookie, your server can be assured that the XHR came from * JavaScript running on your domain. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have read the token. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript making * up its own tokens). We recommend that the token is a digest of your site's authentication * cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number}` – timeout in milliseconds. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 * requests with credentials} for more information. * * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example> <file name="index.html"> <div ng-controller="FetchCtrl"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button ng-click="fetch()">fetch</button><br> <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> function FetchCtrl($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; } </file> <file name="http-hello.html"> Hello, $http! </file> <file name="scenario.js"> it('should make an xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Hello, \$http!/); }); it('should make a JSONP request to angularjs.org', function() { element(':button:contains("Sample JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('0'); expect(binding('data')).toBe('Request failed'); }); </file> </example> */ function $http(config) { config.method = uppercase(config.method); var reqTransformFn = config.transformRequest || $config.transformRequest, respTransformFn = config.transformResponse || $config.transformResponse, defHeaders = $config.headers, reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, defHeaders.common, defHeaders[lowercase(config.method)], config.headers), reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn), promise; // strip content-type if data is undefined if (isUndefined(config.data)) { delete reqHeaders['Content-Type']; } // send request promise = sendReq(config, reqData, reqHeaders); // transform future response promise = promise.then(transformResponse, transformResponse); // apply interceptors forEach(responseInterceptors, function(interceptor) { promise = interceptor(promise); }); promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response, { data: transformData(response.data, response.headers, respTransformFn) }); return (isSuccess(response.status)) ? resp : $q.reject(resp); } } $http.pendingRequests = []; /** * @ngdoc method * @name ng.$http#get * @methodOf ng.$http * * @description * Shortcut method to perform `GET` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#delete * @methodOf ng.$http * * @description * Shortcut method to perform `DELETE` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#head * @methodOf ng.$http * * @description * Shortcut method to perform `HEAD` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#jsonp * @methodOf ng.$http * * @description * Shortcut method to perform `JSONP` request * * @param {string} url Relative or absolute URL specifying the destination of the request. * Should contain `JSON_CALLBACK` string. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name ng.$http#post * @methodOf ng.$http * * @description * Shortcut method to perform `POST` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#put * @methodOf ng.$http * * @description * Shortcut method to perform `PUT` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put'); /** * @ngdoc property * @name ng.$http#defaults * @propertyOf ng.$http * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = $config; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request * * !!! ACCESSES CLOSURE VARS: * $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData, reqHeaders) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if (config.cache && config.method == 'GET') { cache = isObject(config.cache) ? config.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (cachedResp) { if (cachedResp.then) { // cached request has already been sent, but there is no response yet cachedResp.then(removePendingReq, removePendingReq); return cachedResp; } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); } else { resolvePromise(cachedResp, 200, {}); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, send the request to the backend if (!cachedResp) { $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString)]); } else { // remove promise from the cache cache.remove(url); } } resolvePromise(response, status, headersString); $rootScope.$apply(); } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config }); } function removePendingReq() { var idx = indexOf($http.pendingRequests, config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value == null || value == undefined) return; if (isObject(value)) { value = toJson(value); } parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); }); return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } }]; } var XHR = window.XMLHttpRequest || function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc object * @name ng.$httpBackend * @requires $browser * @requires $window * @requires $document * * @description * HTTP backend used by the {@link ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link ng.$http $http} or {@link ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, $document[0], $window.location.protocol.replace(':', '')); }]; } function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials) { $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; }; jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), function() { if (callbacks[callbackId].data) { completeRequest(callback, 200, callbacks[callbackId].data); } else { completeRequest(callback, -2); } delete callbacks[callbackId]; }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); var status; // In IE6 and 7, this might be called synchronously when xhr.send below is called and the // response is in the cache. the promise api will ensure that to the app code the api is // always async xhr.onreadystatechange = function() { if (xhr.readyState == 4) { completeRequest( callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders()); } }; if (withCredentials) { xhr.withCredentials = true; } xhr.send(post || ''); if (timeout > 0) { $browserDefer(function() { status = -1; xhr.abort(); }, timeout); } } function completeRequest(callback, status, response, headersString) { // URL_MATCH is defined in src/service/location.js var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1]; // fix status code for file protocol (it's always 0) status = (protocol == 'file') ? (response ? 200 : 404) : status; // normalize IE bug (http://bugs.jquery.com/ticket/1450) status = status == 1223 ? 204 : status; callback(status, response, headersString); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), doneWrapper = function() { rawDocument.body.removeChild(script); if (done) done(); }; script.type = 'text/javascript'; script.src = url; if (msie) { script.onreadystatechange = function() { if (/loaded|complete/.test(script.readyState)) doneWrapper(); }; } else { script.onload = script.onerror = doneWrapper; } rawDocument.body.appendChild(script); } } /** * @ngdoc object * @name ng.$locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider(){ this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } function $TimeoutProvider() { this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', function($rootScope, $browser, $q, $exceptionHandler) { var deferreds = {}; /** * @ngdoc function * @name ng.$timeout * @requires $browser * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch * block and delegates any exceptions to * {@link ng.$exceptionHandler $exceptionHandler} service. * * The return value of registering a timeout function is a promise which will be resolved when * the timeout is reached and the timeout function is executed. * * To cancel a the timeout request, call `$timeout.cancel(promise)`. * * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to * synchronously flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be delayed. * @param {number=} [delay=0] Delay in milliseconds. * @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {*} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. */ function timeout(fn, delay, invokeApply) { var deferred = $q.defer(), promise = deferred.promise, skipApply = (isDefined(invokeApply) && !invokeApply), timeoutId, cleanup; timeoutId = $browser.defer(function() { try { deferred.resolve(fn()); } catch(e) { deferred.reject(e); $exceptionHandler(e); } if (!skipApply) $rootScope.$apply(); }, delay); cleanup = function() { delete deferreds[promise.$$timeoutId]; }; promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; promise.then(cleanup, cleanup); return promise; } /** * @ngdoc function * @name ng.$timeout#cancel * @methodOf ng.$timeout * * @description * Cancels a task associated with the `promise`. As a result of this the promise will be * resolved with a rejection. * * @param {Promise=} promise Promise returned by the `$timeout` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ timeout.cancel = function(promise) { if (promise && promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); return $browser.defer.cancel(promise.$$timeoutId); } return false; }; return timeout; }]; } /** * @ngdoc object * @name ng.$filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To * achieve this a filter definition consists of a factory function which is annotated with dependencies and is * responsible for creating a the filter function. * * <pre> * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }); * } * </pre> * * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`. * <pre> * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * </pre> * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @ngdoc method * @name ng.$filterProvider#register * @methodOf ng.$filterProvider * @description * Register filter factory function. * * @param {String} name Name of the filter. * @param {function} fn The filter factory function which is injectable. */ /** * @ngdoc function * @name ng.$filter * @function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression | [ filter_name ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; function register(name, factory) { return $provide.factory(name + suffix, factory); } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); } }]; //////////////////////////////////////// register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name ng.filter:filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @example <doc:example> <doc:source> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"å><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:search"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Julie']); }); </doc:scenario> </doc:example> */ function filterFilter() { return function(array, expression) { if (!(array instanceof Array)) return array; var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function() { var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function() { var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; } } /** * @ngdoc filter * @name ng.filter:currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.amount = 1234.56; } </script> <div ng-controller="Ctrl"> <input type="number" ng-model="amount"> <br> default currency symbol ($): {{amount | currency}}<br> custom currency identifier (USD$): {{amount | currency:"USD$"}} </div> </doc:source> <doc:scenario> it('should init with 1234.56', function() { expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function() { input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); }); </doc:scenario> </doc:example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol){ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name ng.filter:number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.val = 1234.56789; } </script> <div ng-controller="Ctrl"> Enter number: <input ng-model='val'><br> Default formatting: {{val | number}}<br> No fractions: {{val | number:0}}<br> Negative number: {{-val | number:4}} </div> </doc:source> <doc:scenario> it('should format numbers', function() { expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function() { input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; if (numStr.indexOf('e') !== -1) { formatedText = numStr; } else { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, NUMBER_STRING = /^\d+$/; /** * @ngdoc filter * @name ng.filter:date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200) * * `format` string can also be one of the following predefined * {@link guide/i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h o''clock"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br> </doc:source> <doc:scenario> it('should format date', function() { expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </doc:scenario> </doc:example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; function jsonStringToDate(string){ var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); return date; } return string; } return function(date, format) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = int(date); } else { date = jsonStringToDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name ng.filter:json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * * @example: <doc:example> <doc:source> <pre>{{ {'name':'value'} | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); }); </doc:scenario> </doc:example> * */ function jsonFilter() { return function(object) { return toJson(object, true); }; } /** * @ngdoc filter * @name ng.filter:lowercase * @function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name ng.filter:uppercase * @function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array containing only a specified number of elements in an array. The elements * are taken from either the beginning or the end of the source array, as specified by the * value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array} array Source array to be limited. * @param {string|Number} limit The length of the returned array. If the `limit` number is * positive, `limit` number of items from the beginning of the source array are copied. * If the number is negative, `limit` number of items from the end of the source array are * copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit` * elements. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.limit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="limit"> <p>Output: {{ numbers | limitTo:limit }}</p> </div> </doc:source> <doc:scenario> it('should limit the numer array to first three items', function() { expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3'); expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]'); }); it('should update the output when -3 is entered', function() { input('limit').enter(-3); expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]'); }); it('should not exceed the maximum size of input array', function() { input('limit').enter(100); expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]'); }); </doc:scenario> </doc:example> */ function limitToFilter(){ return function(array, limit) { if (!(array instanceof Array)) return array; limit = int(limit); var out = [], i, n; // check that array is iterable if (!array || !(array instanceof Array)) return out; // if abs(limit) exceeds maximum length, trim it if (limit > array.length) limit = array.length; else if (limit < -array.length) limit = -array.length; if (limit > 0) { i = 0; n = limit; } else { i = array.length + limit; n = array.length; } for (; i<n; i++) { out.push(array[i]); } return out; } } /** * @ngdoc function * @name ng.filter:orderBy * @function * * @description * Orders a specified `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more informaton about Angular arrays. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}] $scope.predicate = '-age'; } </script> <div ng-controller="Ctrl"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> <tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> </div> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('-age'); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse){ return function(array, sortPredicate, reverseOrder) { if (!(array instanceof Array)) return array; if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = $parse(predicate); } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } } } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive } } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /* * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with `ngClick` directive * without changing the location or causing page reloads, e.g.: * <a href="" ng-click="model.$save()">Save</a> */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { // turn <a href ng-click="..">link</a> into a link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!attr.href) { attr.$set('href', ''); } return function(scope, element) { element.bind('click', function(event){ // if we have no href url, then don't navigate anywhere. if (!element.attr('href')) { event.preventDefault(); } }); } } }); /** * @ngdoc directive * @name ng.directive:ngHref * @restrict A * * @description * Using Angular markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ngHref` directive solves this problem. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </doc:source> <doc:scenario> it('should execute ng-click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng-click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element('#link-3').attr('href')).toBe("/123"); element('#link-3').click(); expect(browser().window().path()).toEqual('/123'); }); it('should execute ng-click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(''); }); it('should only change url when only ng-href', function() { input('value').enter('6'); expect(element('#link-6').attr('href')).toBe('6'); element('#link-6').click(); expect(browser().location().url()).toEqual('/6'); }); </doc:scenario> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngSrc * @restrict A * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ng.directive:ngDisabled * @restrict A * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngDisabled` directive. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngDisabled Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngChecked * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngChecked` directive. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngChecked Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngMultiple * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngMultiple` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="checked"><br/> <select id="select" ng-multiple="checked"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element SELECT * @param {expression} ngMultiple Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngReadonly * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngReadonly` directive. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngSelected * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduced the `ngSelected` directive. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); input('selected').check(); expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element OPTION * @param {string} expression Angular expression that will be evaluated. */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 100, compile: function() { return function(scope, element, attr) { scope.$watch(attr[normalized], function(value) { attr.$set(attrName, !!value); }); }; } }; }; }); // ng-src, ng-href are interpolated forEach(['src', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { attr.$observe(normalized, function(value) { attr.$set(attrName, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect if (msie) element.prop(attrName, value); }); } }; }; }); var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, $setDirty: noop }; /** * @ngdoc object * @name ng.directive:form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containg forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * * @property {Object} $error Is an object hash, containing references to all invalid controls or * forms, where: * * - keys are validation tokens (error names) — such as `REQUIRED`, `URL` or `EMAIL`), * - values are arrays of controls or forms that are invalid with given error. * * @description * `FormController` keeps track of all its controls and nested forms as well as state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope']; function FormController(element, attrs) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid errors = form.$error = {}; // init state form.$name = attrs.name; form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; parentForm.$addControl(form); // Setup initial state of the control element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } form.$addControl = function(control) { if (control.$name && !form.hasOwnProperty(control.$name)) { form[control.$name] = control; } }; form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); }; form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; if (isValid) { if (queue) { arrayRemove(queue, control); if (!queue.length) { invalidCount--; if (!invalidCount) { toggleValidCss(isValid); form.$valid = true; form.$invalid = false; } errors[validationToken] = false; toggleValidCss(true, validationToken); parentForm.$setValidity(validationToken, true, form); } } } else { if (!invalidCount) { toggleValidCss(isValid); } if (queue) { if (includes(queue, control)) return; } else { errors[validationToken] = queue = []; invalidCount++; toggleValidCss(false, validationToken); parentForm.$setValidity(validationToken, false, form); } queue.push(control); form.$valid = false; form.$invalid = true; } }; form.$setDirty = function() { element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); form.$dirty = true; form.$pristine = false; }; } /** * @ngdoc directive * @name ng.directive:ngForm * @restrict EAC * * @description * Nestable alias of {@link ng.directive:form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name ng.directive:form * @restrict E * * @description * Directive that instantiates * {@link ng.directive:form.FormController FormController}. * * If `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link ng.directive:ngForm `ngForm`} * * In angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this * reason angular provides {@link ng.directive:ngForm `ngForm`} alias * which behaves identical to `<form>` but allows form nesting. * * * # CSS classes * - `ng-valid` Is set if the form is valid. * - `ng-invalid` Is set if the form is invalid. * - `ng-pristine` Is set if the form is pristine. * - `ng-dirty` Is set if the form is dirty. * * * # Submitting a form and preventing default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in application specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element * - {@link ng.directive:ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This * is because of the following form submission rules coming from the html spec: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.userType = 'guest'; } </script> <form name="myForm" ng-controller="Ctrl"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.REQUIRED">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('userType')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('userType').enter(''); expect(binding('userType')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var formDirectiveDir = { name: 'form', restrict: 'E', controller: FormController, compile: function() { return { pre: function(scope, formElement, attr, controller) { if (!attr.action) { formElement.bind('submit', function(event) { event.preventDefault(); }); } var parentFormCtrl = formElement.parent().controller('form'), alias = attr.name || attr.ngForm; if (alias) { scope[alias] = controller; } if (parentFormCtrl) { formElement.bind('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { scope[alias] = undefined; } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } } }; } }; var formDirective = valueFn(formDirectiveDir); var ngFormDirective = valueFn(extend(copy(formDirectiveDir), {restrict: 'EAC'})); var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var inputType = { /** * @ngdoc inputType * @name ng.directive:input.text * * @description * Standard HTML text input with angular data binding. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'guest'; $scope.word = /^\w*$/; } </script> <form name="myForm" ng-controller="Ctrl"> Single word: <input type="text" name="input" ng-model="text" ng-pattern="word" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if multi word', function() { input('text').enter('hello world'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'text': textInputType, /** * @ngdoc inputType * @name ng.directive:input.number * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less then `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value = 12; } </script> <form name="myForm" ng-controller="Ctrl"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <span class="error" ng-show="myForm.list.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('value').enter(''); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if over max', function() { input('value').enter('123'); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'number': numberInputType, /** * @ngdoc inputType * @name ng.directive:input.url * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'http://google.com'; } </script> <form name="myForm" ng-controller="Ctrl"> URL: <input type="url" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('http://google.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not url', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'url': urlInputType, /** * @ngdoc inputType * @name ng.directive:input.email * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'me@example.com'; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('me@example.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not email', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'email': emailInputType, /** * @ngdoc inputType * @name ng.directive:input.radio * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.color = 'blue'; } </script> <form name="myForm" ng-controller="Ctrl"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" value="green"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> <tt>color = {{color}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('color')).toEqual('blue'); input('color').select('red'); expect(binding('color')).toEqual('red'); }); </doc:scenario> </doc:example> */ 'radio': radioInputType, /** * @ngdoc inputType * @name ng.directive:input.checkbox * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngTrueValue The value to which the expression should be set when selected. * @param {string=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value1 = true; $scope.value2 = 'YES' } </script> <form name="myForm" ng-controller="Ctrl"> Value1: <input type="checkbox" ng-model="value1"> <br/> Value2: <input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO"> <br/> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('value1')).toEqual('true'); expect(binding('value2')).toEqual('YES'); input('value1').check(); input('value2').check(); expect(binding('value1')).toEqual('false'); expect(binding('value2')).toEqual('NO'); }); </doc:scenario> </doc:example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop }; function isEmpty(value) { return isUndefined(value) || value === '' || value === null || value !== value; } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var listener = function() { var value = trim(element.val()); if (ctrl.$viewValue !== value) { scope.$apply(function() { ctrl.$setViewValue(value); }); } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { element.bind('input', listener); } else { var timeout; element.bind('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; if (!timeout) { timeout = $browser.defer(function() { listener(); timeout = null; }); } }); // if user paste into input using mouse, we need "change" event to catch it element.bind('change', listener); } ctrl.$render = function() { element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; // pattern validator var pattern = attr.ngPattern, patternValidator; var validate = function(regexp, value) { if (isEmpty(value) || regexp.test(value)) { ctrl.$setValidity('pattern', true); return value; } else { ctrl.$setValidity('pattern', false); return undefined; } }; if (pattern) { if (pattern.match(/^\/(.*)\/$/)) { pattern = new RegExp(pattern.substr(1, pattern.length - 2)); patternValidator = function(value) { return validate(pattern, value) }; } else { patternValidator = function(value) { var patternObj = scope.$eval(pattern); if (!patternObj || !patternObj.test) { throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); } return validate(patternObj, value); }; } ctrl.$formatters.push(patternValidator); ctrl.$parsers.push(patternValidator); } // min length validator if (attr.ngMinlength) { var minlength = int(attr.ngMinlength); var minLengthValidator = function(value) { if (!isEmpty(value) && value.length < minlength) { ctrl.$setValidity('minlength', false); return undefined; } else { ctrl.$setValidity('minlength', true); return value; } }; ctrl.$parsers.push(minLengthValidator); ctrl.$formatters.push(minLengthValidator); } // max length validator if (attr.ngMaxlength) { var maxlength = int(attr.ngMaxlength); var maxLengthValidator = function(value) { if (!isEmpty(value) && value.length > maxlength) { ctrl.$setValidity('maxlength', false); return undefined; } else { ctrl.$setValidity('maxlength', true); return value; } }; ctrl.$parsers.push(maxLengthValidator); ctrl.$formatters.push(maxLengthValidator); } } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { var empty = isEmpty(value); if (empty || NUMBER_REGEXP.test(value)) { ctrl.$setValidity('number', true); return value === '' ? null : (empty ? value : parseFloat(value)); } else { ctrl.$setValidity('number', false); return undefined; } }); ctrl.$formatters.push(function(value) { return isEmpty(value) ? '' : '' + value; }); if (attr.min) { var min = parseFloat(attr.min); var minValidator = function(value) { if (!isEmpty(value) && value < min) { ctrl.$setValidity('min', false); return undefined; } else { ctrl.$setValidity('min', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } if (attr.max) { var max = parseFloat(attr.max); var maxValidator = function(value) { if (!isEmpty(value) && value > max) { ctrl.$setValidity('max', false); return undefined; } else { ctrl.$setValidity('max', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } ctrl.$formatters.push(function(value) { if (isEmpty(value) || isNumber(value)) { ctrl.$setValidity('number', true); return value; } else { ctrl.$setValidity('number', false); return undefined; } }); } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var urlValidator = function(value) { if (isEmpty(value) || URL_REGEXP.test(value)) { ctrl.$setValidity('url', true); return value; } else { ctrl.$setValidity('url', false); return undefined; } }; ctrl.$formatters.push(urlValidator); ctrl.$parsers.push(urlValidator); } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var emailValidator = function(value) { if (isEmpty(value) || EMAIL_REGEXP.test(value)) { ctrl.$setValidity('email', true); return value; } else { ctrl.$setValidity('email', false); return undefined; } }; ctrl.$formatters.push(emailValidator); ctrl.$parsers.push(emailValidator); } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } element.bind('click', function() { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value); }); } }); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function checkboxInputType(scope, element, attr, ctrl) { var trueValue = attr.ngTrueValue, falseValue = attr.ngFalseValue; if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; element.bind('click', function() { scope.$apply(function() { ctrl.$setViewValue(element[0].checked); }); }); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; ctrl.$formatters.push(function(value) { return value === trueValue; }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name ng.directive:textarea * @restrict E * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link ng.directive:input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. */ /** * @ngdoc directive * @name ng.directive:input * @restrict E * * @description * HTML input element control with angular data-binding. Input control follows HTML5 input types * and polyfills the HTML5 validation behavior for older browsers. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.user = {name: 'guest', last: 'visitor'}; } </script> <div ng-controller="Ctrl"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if empty when required', function() { input('user.name').enter(''); expect(binding('user')).toEqual('{"last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('false'); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be valid if empty when min length is set', function() { input('user.last').enter(''); expect(binding('user')).toEqual('{"name":"guest","last":""}'); expect(binding('myForm.lastName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if less than required min length', function() { input('user.last').enter('xx'); expect(binding('user')).toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/minlength/); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be invalid if longer than max length', function() { input('user.last').enter('some ridiculously long name'); expect(binding('user')) .toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); expect(binding('myForm.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { return { restrict: 'E', require: '?ngModel', link: function(scope, element, attr, ctrl) { if (ctrl) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, $browser); } } }; }]; var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty'; /** * @ngdoc object * @name ng.directive:ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes * all of these functions to sanitize / convert the value as well as validate. * * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of * these functions to convert the value as well as validate. * * @property {Object} $error An bject hash with all errors as keys. * * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * * @description * * `NgModelController` provides API for the `ng-model` directive. The controller contains * services for data-binding, validation, CSS update, value formatting and parsing. It * specifically does not contain any logic which deals with DOM rendering or listening to * DOM events. The `NgModelController` is meant to be extended by other directives where, the * directive provides DOM manipulation and the `NgModelController` provides the data-binding. * * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) * collaborate together to achieve the desired result. * * <example module="customControl"> <file name="style.css"> [contenteditable] { border: 1px solid black; background-color: white; min-height: 20px; } .ng-invalid { border: 1px solid red; } </file> <file name="script.js"> angular.module('customControl', []). directive('contenteditable', function() { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if(!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html(ngModel.$viewValue || ''); }; // Listen for change events to enable binding element.bind('blur keyup change', function() { scope.$apply(read); }); read(); // initialize // Write data to the model function read() { ngModel.$setViewValue(element.html()); } } }; }); </file> <file name="index.html"> <form name="myForm"> <div contenteditable name="myWidget" ng-model="userContent" required>Change me!</div> <span ng-show="myForm.myWidget.$error.required">Required!</span> <hr> <textarea ng-model="userContent"></textarea> </form> </file> <file name="scenario.js"> it('should data-bind and become invalid', function() { var contentEditable = element('[contenteditable]'); expect(contentEditable.text()).toEqual('Change me!'); input('userContent').enter(''); expect(contentEditable.text()).toEqual(''); expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/); }); </file> * </example> * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', function($scope, $exceptionHandler, $attr, $element, $parse) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$name = $attr.name; var ngModelGet = $parse($attr.ngModel), ngModelSet = ngModelGet.assign; if (!ngModelSet) { throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel + ' (' + startingTag($element) + ')'); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$render * @methodOf ng.directive:ngModel.NgModelController * * @description * Called when the view needs to be updated. It is expected that the user of the ng-model * directive will implement this method. */ this.$render = noop; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid $error = this.$error = {}; // keep invalid keys here // Setup initial state of the control $element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; $element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setValidity * @methodOf ng.directive:ngModel.NgModelController * * @description * Change the validity state, and notifies the form when the control changes validity. (i.e. it * does not notify form if given validator is already marked as invalid). * * This method should be called by validators - i.e. the parser or formatter functions. * * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). */ this.$setValidity = function(validationErrorKey, isValid) { if ($error[validationErrorKey] === !isValid) return; if (isValid) { if ($error[validationErrorKey]) invalidCount--; if (!invalidCount) { toggleValidCss(true); this.$valid = true; this.$invalid = false; } } else { toggleValidCss(false); this.$invalid = true; this.$valid = false; invalidCount++; } $error[validationErrorKey] = !isValid; toggleValidCss(isValid, validationErrorKey); parentForm.$setValidity(validationErrorKey, isValid, this); }; /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setViewValue * @methodOf ng.directive:ngModel.NgModelController * * @description * Read a value from view. * * This method should be called from within a DOM event handler. * For example {@link ng.directive:input input} or * {@link ng.directive:select select} directives call it. * * It internally calls all `formatters` and if resulted value is valid, updates the model and * calls all registered change listeners. * * @param {string} value Value from the view. */ this.$setViewValue = function(value) { this.$viewValue = value; // change to dirty if (this.$pristine) { this.$dirty = true; this.$pristine = false; $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); parentForm.$setDirty(); } forEach(this.$parsers, function(fn) { value = fn(value); }); if (this.$modelValue !== value) { this.$modelValue = value; ngModelSet($scope, value); forEach(this.$viewChangeListeners, function(listener) { try { listener(); } catch(e) { $exceptionHandler(e); } }) } }; // model -> value var ctrl = this; $scope.$watch(ngModelGet, function(value) { // ignore change from view if (ctrl.$modelValue === value) return; var formatters = ctrl.$formatters, idx = formatters.length; ctrl.$modelValue = value; while(idx--) { value = formatters[idx](value); } if (ctrl.$viewValue !== value) { ctrl.$viewValue = value; ctrl.$render(); } }); }]; /** * @ngdoc directive * @name ng.directive:ngModel * * @element input * * @description * Is directive that tells Angular to do two-way data binding. It works together with `input`, * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well. * * `ngModel` is responsible for: * * - binding the view into the model, which other directives such as `input`, `textarea` or `select` * require, * - providing validation behavior (i.e. required, number, email, url), * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), * - register the control with parent {@link ng.directive:form form}. * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} * - {@link ng.directive:input.text text} * - {@link ng.directive:input.checkbox checkbox} * - {@link ng.directive:input.radio radio} * - {@link ng.directive:input.number number} * - {@link ng.directive:input.email email} * - {@link ng.directive:input.url url} * - {@link ng.directive:select select} * - {@link ng.directive:textarea textarea} * */ var ngModelDirective = function() { return { require: ['ngModel', '^?form'], controller: NgModelController, link: function(scope, element, attr, ctrls) { // notify others, especially parent forms var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; formCtrl.$addControl(modelCtrl); element.bind('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngChange * @restrict E * * @description * Evaluate given expression when user changes the input. * The expression is not evaluated when the value change is coming from the model. * * Note, this directive requires `ngModel` to be present. * * @element input * * @example * <doc:example> * <doc:source> * <script> * function Controller($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * } * </script> * <div ng-controller="Controller"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * debug = {{confirmed}}<br /> * counter = {{counter}} * </div> * </doc:source> * <doc:scenario> * it('should evaluate the expression if changing from view', function() { * expect(binding('counter')).toEqual('0'); * element('#ng-change-example1').click(); * expect(binding('counter')).toEqual('1'); * expect(binding('confirmed')).toEqual('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element('#ng-change-example2').click(); * expect(binding('counter')).toEqual('0'); * expect(binding('confirmed')).toEqual('true'); * }); * </doc:scenario> * </doc:example> */ var ngChangeDirective = valueFn({ require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); var requiredDirective = function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.required = true; // force truthy in case we are on non input element var validator = function(value) { if (attr.required && (isEmpty(value) || value === false)) { ctrl.$setValidity('required', false); return; } else { ctrl.$setValidity('required', true); return value; } }; ctrl.$formatters.push(validator); ctrl.$parsers.unshift(validator); attr.$observe('required', function() { validator(ctrl.$viewValue); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngList * * @description * Text input that converts between comma-seperated string into an array of strings. * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. If * specified in form `/something/` then the value will be converted into a regular expression. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.names = ['igor', 'misko', 'vojta']; } </script> <form name="myForm" ng-controller="Ctrl"> List: <input name="namesInput" ng-model="names" ng-list required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <tt>names = {{names}}</tt><br/> <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('names')).toEqual('["igor","misko","vojta"]'); expect(binding('myForm.namesInput.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('names').enter(''); expect(binding('names')).toEqual('[]'); expect(binding('myForm.namesInput.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var ngListDirective = function() { return { require: 'ngModel', link: function(scope, element, attr, ctrl) { var match = /\/(.*)\//.exec(attr.ngList), separator = match && new RegExp(match[1]) || attr.ngList || ','; var parse = function(viewValue) { var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trim(value)); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value) && !equals(parse(ctrl.$viewValue), value)) { return value.join(', '); } return undefined; }); } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; var ngValueDirective = function() { return { priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function(scope, elm, attr) { scope.$watch(attr.ngValue, function(value) { attr.$set('value', value, false); }); }; } } }; }; /** * @ngdoc directive * @name ng.directive:ngBind * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when * it's desirable to put bindings into template that is momentarily displayed by the browser in its * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the * bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/expression Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.name = 'Whirled'; } </script> <div ng-controller="Ctrl"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ var ngBindDirective = ngDirective(function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBind); scope.$watch(attr.ngBind, function(value) { element.text(value == undefined ? '' : value); }); }); /** * @ngdoc directive * @name ng.directive:ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text should be replaced with the template in ngBindTemplate. * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; } </script> <div ng-controller="Ctrl"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('salutation')). toBe('Hello'); expect(using('.doc-example-live').binding('name')). toBe('World'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('salutation')). toBe('Greetings'); expect(using('.doc-example-live').binding('name')). toBe('user'); }); </doc:scenario> </doc:example> */ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { return function(scope, element, attr) { // TODO: move this to scenario runner var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); element.addClass('ng-binding').data('$binding', interpolateFn); attr.$observe('ngBindTemplate', function(value) { element.text(value); }); } }]; /** * @ngdoc directive * @name ng.directive:ngBindHtmlUnsafe * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too * restrictive and when you absolutely trust the source of the content you are binding to. * * See {@link ngSanitize.$sanitize $sanitize} docs for examples. * * @element ANY * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate. */ var ngBindHtmlUnsafeDirective = [function() { return function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); scope.$watch(attr.ngBindHtmlUnsafe, function(value) { element.html(value || ''); }); }; }]; function classDirective(name, selector) { name = 'ngClass' + name; return ngDirective(function(scope, element, attr) { scope.$watch(attr[name], function(newVal, oldVal) { if (selector === true || scope.$index % 2 === selector) { if (oldVal && (newVal !== oldVal)) { if (isObject(oldVal) && !isArray(oldVal)) oldVal = map(oldVal, function(v, k) { if (v) return k }); element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal); } if (isObject(newVal) && !isArray(newVal)) newVal = map(newVal, function(v, k) { if (v) return k }); if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); } }, true); }); } /** * @ngdoc directive * @name ng.directive:ngClass * * @description * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an * expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the classes * new classes are added. * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myVar='my-class'"> <input type="button" value="clear" ng-click="myVar=''"> <br> <span ng-class="myVar">Sample Text</span> </file> <file name="style.css"> .my-class { color: red; } </file> <file name="scenario.js"> it('should check ng-class', function() { expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').prop('className')). toMatch(/my-class/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); }); </file> </example> */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name ng.directive:ngClassOdd * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name ng.directive:ngClassEven * * @description * The `ngClassOdd` and `ngClassEven` works exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name ng.directive:ngCloak * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but typically a fine-grained application is * prefered in order to benefit from progressive rendering of the browser view. * * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * * <pre> * [ng\:cloak], [ng-cloak], .ng-cloak { * display: none; * } * </pre> * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive * during the compilation of the template it deletes the `ngCloak` element attribute, which * makes the compiled element visible. * * For the best result, `angular.js` script must be loaded in the head section of the html file; * alternatively, the css rule (above) must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. * * @element ANY * * @example <doc:example> <doc:source> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </doc:source> <doc:scenario> it('should remove the template directive and css class', function() { expect(element('.doc-example-live #template1').attr('ng-cloak')). not().toBeDefined(); expect(element('.doc-example-live #template2').attr('ng-cloak')). not().toBeDefined(); }); </doc:scenario> </doc:example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name ng.directive:ngController * * @description * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the `{@link ng.$route}` * service. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/expression expression} that on the current scope evaluates to a * constructor function. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. <doc:example> <doc:source> <script> function SettingsController($scope) { $scope.name = "John Smith"; $scope.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'john.smith@example.org'} ]; $scope.greet = function() { alert(this.name); }; $scope.addContact = function() { this.contacts.push({type:'email', value:'yourname@example.org'}); }; $scope.removeContact = function(contactToRemove) { var index = this.contacts.indexOf(contactToRemove); this.contacts.splice(index, 1); }; $scope.clearContact = function(contact) { contact.type = 'phone'; contact.value = ''; }; } </script> <div ng-controller="SettingsController"> Name: <input type="text" ng-model="name"/> [ <a href="" ng-click="greet()">greet</a> ]<br/> Contact: <ul> <li ng-repeat="contact in contacts"> <select ng-model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng-model="contact.value"/> [ <a href="" ng-click="clearContact(contact)">clear</a> | <a href="" ng-click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng-click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('yourname@example.org'); }); </doc:scenario> </doc:example> */ var ngControllerDirective = [function() { return { scope: true, controller: '@' }; }]; /** * @ngdoc directive * @name ng.directive:ngCsp * @priority 1000 * * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. * This directive should be used on the root element of the application (typically the `<html>` * element or other element with the {@link ng.directive:ngApp ngApp} * directive). * * If enabled the performance of template expression evaluator will suffer slightly, so don't enable * this mode unless you need it. * * @element html */ var ngCspDirective = ['$sniffer', function($sniffer) { return { priority: 1000, compile: function() { $sniffer.csp = true; } }; }]; /** * @ngdoc directive * @name ng.directive:ngClick * * @description * The ngClick allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon * click. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng-click', function() { expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. */ var ngEventDirectives = {}; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return function(scope, element, attr) { var fn = $parse(attr[directiveName]); element.bind(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }); }; }]; } ); /** * @ngdoc directive * @name ng.directive:ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. * * @element ANY * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon * dblclick. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon * mousedown. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon * mouseup. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon * mouseover. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon * mouseenter. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon * mouseleave. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon * mousemove. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} ngSubmit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if (this.text) { this.list.push(this.text); this.text = ''; } }; } </script> <form ng-submit="submit()" ng-controller="Ctrl"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </doc:source> <doc:scenario> it('should check ng-submit', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); expect(input('text').val()).toBe(''); }); it('should ignore empty strings', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); }); </doc:scenario> </doc:example> */ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { element.bind('submit', function() { scope.$apply(attrs.ngSubmit); }); }); /** * @ngdoc directive * @name ng.directive:ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ngInclude won't work for cross-domain requests on all browsers and for * file:// access on some browsers). * * @scope * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <example> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> <hr/> <div ng-include src="template.url"></div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'} , { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; } </file> <file name="template1.html"> Content of template1.html </file> <file name="template2.html"> Content of template2.html </file> <file name="scenario.js"> it('should load template1.html', function() { expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template1.html/); }); it('should load template2.html', function() { select('template').option('1'); expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template2.html/); }); it('should change to blank', function() { select('template').option(''); expect(element('.doc-example-live [ng-include]').text()).toEqual(''); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngInclude#$includeContentLoaded * @eventOf ng.directive:ngInclude * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. */ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', function($http, $templateCache, $anchorScroll, $compile) { return { restrict: 'ECA', terminal: true, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, element) { var changeCounter = 0, childScope; var clearContent = function() { if (childScope) { childScope.$destroy(); childScope = null; } element.html(''); }; scope.$watch(srcExp, function(src) { var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; if (childScope) childScope.$destroy(); childScope = scope.$new(); element.html(response); $compile(element.contents())(childScope); if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } childScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { if (thisChangeId === changeCounter) clearContent(); }); } else clearContent(); }); }; } }; }]; /** * @ngdoc directive * @name ng.directive:ngInit * * @description * The `ngInit` directive specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <div ng-init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function() { expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ var ngInitDirective = ngDirective({ compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } } } }); /** * @ngdoc directive * @name ng.directive:ngNonBindable * @priority 1000 * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ngNonBindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng-non-bindable', function() { expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name ng.directive:ngPluralize * @restrict EA * * @description * # Overview * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js and the rules can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * * While a pural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. You will see the use of plural categories * and explicit number rules throughout later parts of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/expression * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object so that Angular * can interpret it correctly. * * The following example shows how to configure ngPluralize: * * <pre> * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *</pre> * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * <pre> * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * </pre> * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. * @param {string} when The mapping between plural category to its correspoding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; } </script> <div ng-controller="Ctrl"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </doc:source> <doc:scenario> it('should show correct pluralized string', function() { expect(element('.doc-example-live ng-pluralize:first').text()). toBe('1 person is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor is viewing.'); using('.doc-example-live').input('personCount').enter('0'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('Nobody is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Nobody is viewing.'); using('.doc-example-live').input('personCount').enter('2'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('2 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor and Misko are viewing.'); using('.doc-example-live').input('personCount').enter('3'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('3 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and one other person are viewing.'); using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('4 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); }); it('should show data-binded names', function() { using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); using('.doc-example-live').input('person1').enter('Di'); using('.doc-example-live').input('person2').enter('Vojta'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Di, Vojta and 2 other people are viewing.'); }); </doc:scenario> </doc:example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp), whensExpFns = {}; forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, '{{' + numberExp + '-' + offset + '}}')); }); scope.$watch(function() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!whens[value]) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope, element, true); } else { return ''; } }, function(newVal) { element.text(newVal); }); } }; }]; /** * @ngdoc directive * @name ng.directive:ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$first` – `{boolean}` – true if the repeated element is first in the iterator. * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator. * * `$last` – `{boolean}` – true if the repeated element is last in the iterator. * * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <doc:example> <doc:source> <div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng-repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </doc:source> <doc:scenario> it('should check ng-repeat', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); </doc:scenario> </doc:example> */ var ngRepeatDirective = ngDirective({ transclude: 'element', priority: 1000, terminal: true, compile: function(element, attr, linker) { return function(scope, iterStartElement, attr){ var expression = attr.ngRepeat; var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + lhs + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is an array of objects with following properties. // - scope: bound scope // - element: previous element. // - index: position // We need an array of these objects since the same object can be returned from the iterator. // We expect this to be a rare case. var lastOrder = new HashQueueMap(); scope.$watch(function(scope){ var index, length, collection = scope.$eval(rhs), collectionLength = size(collection, true), childScope, // Same as lastOrder but it has the current state. It will become the // lastOrder on the next iteration. nextOrder = new HashQueueMap(), key, value, // key/value of iteration array, last, // last object information {scope, element, index} cursor = iterStartElement; // current position of the node if (!isArray(collection)) { // if object, extract keys, sort them and use to determine order of iteration over obj props array = []; for(key in collection) { if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { array.push(key); } } array.sort(); } else { array = collection || []; } // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0, length = array.length; index < length; index++) { key = (collection === array) ? index : array[index]; value = collection[key]; last = lastOrder.shift(value); if (last) { // if we have already seen this object, then we need to reuse the // associated scope/element childScope = last.scope; nextOrder.push(value, last); if (index === last.index) { // do nothing cursor = last.element; } else { // existing item which got moved last.index = index; // This may be a noop, if the element is next, but I don't know of a good way to // figure this out, since it would require extra DOM access, so let's just hope that // the browsers realizes that it is noop, and treats it as such. cursor.after(last.element); cursor = last.element; } } else { // new item which we don't know about childScope = scope.$new(); } childScope[valueIdent] = value; if (keyIdent) childScope[keyIdent] = key; childScope.$index = index; childScope.$first = (index === 0); childScope.$last = (index === (collectionLength - 1)); childScope.$middle = !(childScope.$first || childScope.$last); if (!last) { linker(childScope, function(clone){ cursor.after(clone); last = { scope: childScope, element: (cursor = clone), index: index }; nextOrder.push(value, last); }); } } //shrink children for (key in lastOrder) { if (lastOrder.hasOwnProperty(key)) { array = lastOrder[key]; while(array.length) { value = array.pop(); value.element.remove(); value.scope.$destroy(); } } } lastOrder = nextOrder; }); }; } }); /** * @ngdoc directive * @name ng.directive:ngShow * * @description * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/> Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngShowDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngShow, function(value){ element.css('display', toBoolean(value) ? '' : 'none'); }); }); /** * @ngdoc directive * @name ng.directive:ngHide * * @description * The `ngHide` and `ngShow` directives hide or show a portion * of the HTML conditionally. * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} truthy then * the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngHideDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngHide, function(value){ element.css('display', toBoolean(value) ? 'none' : ''); }); }); /** * @ngdoc directive * @name ng.directive:ngStyle * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle {@link guide/expression Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myStyle={color:'red'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </file> <file name="style.css"> span { color: black; } </file> <file name="scenario.js"> it('should check ng-style', function() { expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </file> </example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watch(attr.ngStyle, function(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }, true); }); /** * @ngdoc directive * @name ng.directive:ngSwitch * @restrict EA * * @description * Conditionally change the DOM structure. * * @usageContent * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * ... * <ANY ng-switch-default>...</ANY> * * @scope * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * @paramDescription * On child elments add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. * * `ngSwitchDefault`: the default case when no other casses match. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </script> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div ng-switch on="selection" > <div ng-switch-when="settings">Settings Div</div> <span ng-switch-when="home">Home Span</span> <span ng-switch-default>default</span> </div> </div> </doc:source> <doc:scenario> it('should start in settings', function() { expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); }); it('should change to home', function() { select('selection').option('home'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); }); it('should select deafault', function() { select('selection').option('other'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); }); </doc:scenario> </doc:example> */ var NG_SWITCH = 'ng-switch'; var ngSwitchDirective = valueFn({ restrict: 'EA', compile: function(element, attr) { var watchExpr = attr.ngSwitch || attr.on, cases = {}; element.data(NG_SWITCH, cases); return function(scope, element){ var selectedTransclude, selectedElement, selectedScope; scope.$watch(watchExpr, function(value) { if (selectedElement) { selectedScope.$destroy(); selectedElement.remove(); selectedElement = selectedScope = null; } if ((selectedTransclude = cases['!' + value] || cases['?'])) { scope.$eval(attr.change); selectedScope = scope.$new(); selectedTransclude(selectedScope, function(caseElement) { selectedElement = caseElement; element.append(caseElement); }); } }); }; } }); var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['!' + attrs.ngSwitchWhen] = transclude; } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['?'] = transclude; } }); /** * @ngdoc directive * @name ng.directive:ngTransclude * * @description * Insert the transcluded DOM here. * * @element ANY * * @example <doc:example module="transclude"> <doc:source> <script> function Ctrl($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; } angular.module('transclude', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: 'isolate', locals: { title:'bind' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<div ng-transclude></div>' + '</div>' }; }); </script> <div ng-controller="Ctrl"> <input ng-model="title"><br> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </doc:source> <doc:scenario> it('should have transcluded', function() { input('title').enter('TITLE'); input('text').enter('TEXT'); expect(binding('title')).toEqual('TITLE'); expect(binding('text')).toEqual('TEXT'); }); </doc:scenario> </doc:example> * */ var ngTranscludeDirective = ngDirective({ controller: ['$transclude', '$element', function($transclude, $element) { $transclude(function(clone) { $element.append(clone); }); }] }); /** * @ngdoc directive * @name ng.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ng.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * @scope * @example <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.template = {{$route.current.template}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngView#$viewContentLoaded * @eventOf ng.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile', '$controller', function($http, $templateCache, $route, $anchorScroll, $compile, $controller) { return { restrict: 'ECA', terminal: true, link: function(scope, element, attr) { var lastScope, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function destroyLastScope() { if (lastScope) { lastScope.$destroy(); lastScope = null; } } function clearContent() { element.html(''); destroyLastScope(); } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (template) { element.html(template); destroyLastScope(); var link = $compile(element.contents()), current = $route.current, controller; lastScope = current.scope = scope.$new(); if (current.controller) { locals.$scope = lastScope; controller = $controller(current.controller, locals); element.contents().data('$ngControllerController', controller); } link(lastScope); lastScope.$emit('$viewContentLoaded'); lastScope.$eval(onloadExp); // $anchorScroll might listen on event... $anchorScroll(); } else { clearContent(); } } } }; }]; /** * @ngdoc directive * @name ng.directive:script * * @description * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the * template can be used by `ngInclude`, `ngView` or directive templates. * * @restrict E * @param {'text/ng-template'} type must be set to `'text/ng-template'` * * @example <doc:example> <doc:source> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </doc:source> <doc:scenario> it('should load template defined inside script tag', function() { element('#tpl-link').click(); expect(element('#tpl-content').text()).toMatch(/Content of the template/); }); </doc:scenario> </doc:example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; /** * @ngdoc directive * @name ng.directive:select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for a `<select>` element using an array or an object obtained by evaluating the * `ngOptions` expression. *˝˝ * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead * of {@link ng.directive:ngRepeat ngRepeat} when you want the * `select` model to be bound to a non-string value. This is because an option element can currently * be bound to string values only. * * @param {string} name assignable expression to data-bind to. * @param {string=} required The control is considered valid only if value is entered. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * @example <doc:example> <doc:source> <script> function MyCntrl($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.color = $scope.colors[2]; // red } </script> <div ng-controller="MyCntrl"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.splice($index, 1)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="color" ng-options="c.name for c in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="color" ng-options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="color" ng-options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng-options', function() { expect(binding('{selected_color:color}')).toMatch('red'); select('color').option('0'); expect(binding('{selected_color:color}')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('{selected_color:color}')).toMatch('null'); }); </doc:scenario> </doc:example> */ var ngOptionsDirective = valueFn({ terminal: true }); var selectDirective = ['$compile', '$parse', function($compile, $parse) { //00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/, nullModelCtrl = {$setViewValue: noop}; return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.databound = $attrs.ngModel; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; } self.addOption = function(value) { optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue == value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE } self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); } $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value == '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple && (attr.required || attr.ngRequired)) { var requiredValidator = function(value) { ngModelCtrl.$setValidity('required', !attr.required || (value && value.length)); return value; }; ngModelCtrl.$parsers.push(requiredValidator); ngModelCtrl.$formatters.unshift(requiredValidator); attr.$observe('required', function() { requiredValidator(ngModelCtrl.$viewValue); }); } if (optionsExp) Options(scope, element, ngModelCtrl); else if (multiple) Multiple(scope, element, ngModelCtrl); else Single(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function Single(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.bind('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function Multiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.children(), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function() { if (!equals(lastView, ctrl.$viewValue)) { lastView = copy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.bind('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.children(), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function Options(scope, selectElement, ctrl) { var match; if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '" + optionsExp + "'."); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.html('') because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.html(''); selectElement.bind('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], locals = {}, key, value, optionElement, index, groupIndex, length, groupLength; if (multiple) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; locals[valueName] = collection[key]; value.push(valueFn(scope, locals)); } } } } else { key = selectElement.val(); if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { locals[valueName] = collection[key]; if (keyName) locals[keyName] = key; value = valueFn(scope, locals); } } ctrl.$setViewValue(value); }); }); ctrl.$render = render; // TODO(vojta): can't we optimize this ? scope.$watch(render); function render() { var optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, modelValue = ctrl.$modelValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, groupLength, length, groupIndex, index, locals = {}, selected, selectedSet = false, // nothing is selected yet lastElement, element; if (multiple) { selectedSet = new HashMap(modelValue); } else if (modelValue === null || nullOption) { // if we are not multiselect, and we are null then we have to add the nullOption optionGroups[''].push({selected:modelValue === null, id:'', label:''}); selectedSet = true; } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index]; optionGroupName = groupByFn(scope, locals) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { selected = selectedSet.remove(valueFn(scope, locals)) != undefined; } else { selected = modelValue === valueFn(scope, locals); selectedSet = selectedSet || selected; // see if at least one item is selected } optionGroup.push({ id: keyName ? keys[index] : index, // either the index into array or key from object label: displayFn(scope, locals) || '', // what will be seen by the user selected: selected // determine if we should be selected }); } if (!multiple && !selectedSet) { // nothing was selected, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } if (existingOption.element.selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } } } } }]; var optionDirective = ['$interpolate', function($interpolate) { var nullSelectCtrl = { addOption: noop, removeOption: noop }; return { restrict: 'E', priority: 100, require: '^select', compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } return function (scope, element, attr, selectCtrl) { if (selectCtrl.databound) { // For some reason Opera defaults to true and if not overridden this messes up the repeater. // We don't want the view to drive the initialization of the model anyway. element.prop('selected', false); } else { selectCtrl = nullSelectCtrl; } if (interpolateFn) { scope.$watch(interpolateFn, function(newVal, oldVal) { attr.$set('value', newVal); if (newVal !== oldVal) selectCtrl.removeOption(oldVal); selectCtrl.addOption(newVal); }); } else { selectCtrl.addOption(attr.value); } element.bind('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } } }]; var styleDirective = valueFn({ restrict: 'E', terminal: true }); //try to bind to jquery now so that one can write angular.element().read() //but we will rebind on bootstrap again. bindJQuery(); publishExternalAPI(angular); jqLite(document).ready(function() { angularInit(document, bootstrap); }); })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak{display:none;}ng\\:form{display:block;}</style>');
zzangtest123-google-drive-sdk-samples
python/static/lib/angular-1.0.0/angular-1.0.0.js
JavaScript
asf20
473,115