diff --git a/.gitignore b/.gitignore index 943af75..3cda0d4 100644 --- a/.gitignore +++ b/.gitignore @@ -115,4 +115,94 @@ dist .yarn/unplugged .yarn/build-state.yml .yarn/install-state.gz -.pnp.* \ No newline at end of file +.pnp.* + + +# Created by https://www.gitignore.io + +### OSX ### +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear on external disk +.Spotlight-V100 +.Trashes + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.cache +nosetests.xml +coverage.xml + +# Translations +*.mo +*.pot + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + + +### Django ### +*.log +*.pot +*.pyc +__pycache__/ +local_settings.py +eng_env/* +.env \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..b7368ca --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.formatting.provider": "black" +} diff --git a/books/django (1).pdf b/books/django (1).pdf new file mode 100644 index 0000000..2a5fb56 Binary files /dev/null and b/books/django (1).pdf differ diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/jquery-1.7.2.min.js b/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/jquery-1.7.2.min.js deleted file mode 100644 index 5627896..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/jquery-1.7.2.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v1.7.2 jquery.com | jquery.org/license */ -(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"":"")+""),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;e=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="
"+""+"
",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="
t
",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="
",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( -a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&j.push({elem:this,matches:d.slice(e)});for(k=0;k0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
","
"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f -.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(;d1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]===""&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/tipTipv13/jquery.tipTip.js b/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/tipTipv13/jquery.tipTip.js deleted file mode 100644 index 7eacf35..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/tipTipv13/jquery.tipTip.js +++ /dev/null @@ -1,191 +0,0 @@ - /* - * TipTip - * Copyright 2010 Drew Wilson - * www.drewwilson.com - * code.drewwilson.com/entry/tiptip-jquery-plugin - * - * Version 1.3 - Updated: Mar. 23, 2010 - * - * This Plug-In will create a custom tooltip to replace the default - * browser tooltip. It is extremely lightweight and very smart in - * that it detects the edges of the browser window and will make sure - * the tooltip stays within the current window size. As a result the - * tooltip will adjust itself to be displayed above, below, to the left - * or to the right depending on what is necessary to stay within the - * browser window. It is completely customizable as well via CSS. - * - * This TipTip jQuery plug-in is dual licensed under the MIT and GPL licenses: - * http://www.opensource.org/licenses/mit-license.php - * http://www.gnu.org/licenses/gpl.html - */ - -(function($){ - $.fn.tipTip = function(options) { - var defaults = { - activation: "hover", - keepAlive: false, - maxWidth: "200px", - edgeOffset: 3, - defaultPosition: "bottom", - delay: 400, - fadeIn: 200, - fadeOut: 200, - attribute: "title", - content: false, // HTML or String to fill TipTIp with - enter: function(){}, - exit: function(){} - }; - var opts = $.extend(defaults, options); - - // Setup tip tip elements and render them to the DOM - if($("#tiptip_holder").length <= 0){ - var tiptip_holder = $('
'); - var tiptip_content = $('
'); - var tiptip_arrow = $('
'); - $("body").append(tiptip_holder.html(tiptip_content).prepend(tiptip_arrow.html('
'))); - } else { - var tiptip_holder = $("#tiptip_holder"); - var tiptip_content = $("#tiptip_content"); - var tiptip_arrow = $("#tiptip_arrow"); - } - - return this.each(function(){ - var org_elem = $(this); - if(opts.content){ - var org_title = opts.content; - } else { - var org_title = org_elem.attr(opts.attribute); - } - if(org_title != ""){ - if(!opts.content){ - org_elem.removeAttr(opts.attribute); //remove original Attribute - } - var timeout = false; - - if(opts.activation == "hover"){ - org_elem.hover(function(){ - active_tiptip(); - }, function(){ - if(!opts.keepAlive){ - deactive_tiptip(); - } - }); - if(opts.keepAlive){ - tiptip_holder.hover(function(){}, function(){ - deactive_tiptip(); - }); - } - } else if(opts.activation == "focus"){ - org_elem.focus(function(){ - active_tiptip(); - }).blur(function(){ - deactive_tiptip(); - }); - } else if(opts.activation == "click"){ - org_elem.click(function(){ - active_tiptip(); - return false; - }).hover(function(){},function(){ - if(!opts.keepAlive){ - deactive_tiptip(); - } - }); - if(opts.keepAlive){ - tiptip_holder.hover(function(){}, function(){ - deactive_tiptip(); - }); - } - } - - function active_tiptip(){ - opts.enter.call(this); - tiptip_content.html(org_title); - tiptip_holder.hide().removeAttr("class").css("margin","0"); - tiptip_arrow.removeAttr("style"); - - var top = parseInt(org_elem.offset()['top']); - var left = parseInt(org_elem.offset()['left']); - var org_width = parseInt(org_elem.outerWidth()); - var org_height = parseInt(org_elem.outerHeight()); - var tip_w = tiptip_holder.outerWidth(); - var tip_h = tiptip_holder.outerHeight(); - var w_compare = Math.round((org_width - tip_w) / 2); - var h_compare = Math.round((org_height - tip_h) / 2); - var marg_left = Math.round(left + w_compare); - var marg_top = Math.round(top + org_height + opts.edgeOffset); - var t_class = ""; - var arrow_top = ""; - var arrow_left = Math.round(tip_w - 12) / 2; - - if(opts.defaultPosition == "bottom"){ - t_class = "_bottom"; - } else if(opts.defaultPosition == "top"){ - t_class = "_top"; - } else if(opts.defaultPosition == "left"){ - t_class = "_left"; - } else if(opts.defaultPosition == "right"){ - t_class = "_right"; - } - - var right_compare = (w_compare + left) < parseInt($(window).scrollLeft()); - var left_compare = (tip_w + left) > parseInt($(window).width()); - - if((right_compare && w_compare < 0) || (t_class == "_right" && !left_compare) || (t_class == "_left" && left < (tip_w + opts.edgeOffset + 5))){ - t_class = "_right"; - arrow_top = Math.round(tip_h - 13) / 2; - arrow_left = -12; - marg_left = Math.round(left + org_width + opts.edgeOffset); - marg_top = Math.round(top + h_compare); - } else if((left_compare && w_compare < 0) || (t_class == "_left" && !right_compare)){ - t_class = "_left"; - arrow_top = Math.round(tip_h - 13) / 2; - arrow_left = Math.round(tip_w); - marg_left = Math.round(left - (tip_w + opts.edgeOffset + 5)); - marg_top = Math.round(top + h_compare); - } - - var top_compare = (top + org_height + opts.edgeOffset + tip_h + 8) > parseInt($(window).height() + $(window).scrollTop()); - var bottom_compare = ((top + org_height) - (opts.edgeOffset + tip_h + 8)) < 0; - - if(top_compare || (t_class == "_bottom" && top_compare) || (t_class == "_top" && !bottom_compare)){ - if(t_class == "_top" || t_class == "_bottom"){ - t_class = "_top"; - } else { - t_class = t_class+"_top"; - } - arrow_top = tip_h; - marg_top = Math.round(top - (tip_h + 5 + opts.edgeOffset)); - } else if(bottom_compare | (t_class == "_top" && bottom_compare) || (t_class == "_bottom" && !top_compare)){ - if(t_class == "_top" || t_class == "_bottom"){ - t_class = "_bottom"; - } else { - t_class = t_class+"_bottom"; - } - arrow_top = -12; - marg_top = Math.round(top + org_height + opts.edgeOffset); - } - - if(t_class == "_right_top" || t_class == "_left_top"){ - marg_top = marg_top + 5; - } else if(t_class == "_right_bottom" || t_class == "_left_bottom"){ - marg_top = marg_top - 5; - } - if(t_class == "_left_top" || t_class == "_left_bottom"){ - marg_left = marg_left + 5; - } - tiptip_arrow.css({"margin-left": arrow_left+"px", "margin-top": arrow_top+"px"}); - tiptip_holder.css({"margin-left": marg_left+"px", "margin-top": marg_top+"px"}).attr("class","tip"+t_class); - - if (timeout){ clearTimeout(timeout); } - timeout = setTimeout(function(){ tiptip_holder.stop(true,true).fadeIn(opts.fadeIn); }, opts.delay); - } - - function deactive_tiptip(){ - opts.exit.call(this); - if (timeout){ clearTimeout(timeout); } - tiptip_holder.fadeOut(opts.fadeOut); - } - } - }); - } -})(jQuery); \ No newline at end of file diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/tipTipv13/jquery.tipTip.minified.js b/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/tipTipv13/jquery.tipTip.minified.js deleted file mode 100644 index cdf3a89..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/tipTipv13/jquery.tipTip.minified.js +++ /dev/null @@ -1,21 +0,0 @@ - /* - * TipTip - * Copyright 2010 Drew Wilson - * www.drewwilson.com - * code.drewwilson.com/entry/tiptip-jquery-plugin - * - * Version 1.3 - Updated: Mar. 23, 2010 - * - * This Plug-In will create a custom tooltip to replace the default - * browser tooltip. It is extremely lightweight and very smart in - * that it detects the edges of the browser window and will make sure - * the tooltip stays within the current window size. As a result the - * tooltip will adjust itself to be displayed above, below, to the left - * or to the right depending on what is necessary to stay within the - * browser window. It is completely customizable as well via CSS. - * - * This TipTip jQuery plug-in is dual licensed under the MIT and GPL licenses: - * http://www.opensource.org/licenses/mit-license.php - * http://www.gnu.org/licenses/gpl.html - */ -(function($){$.fn.tipTip=function(options){var defaults={activation:"hover",keepAlive:false,maxWidth:"200px",edgeOffset:3,defaultPosition:"bottom",delay:400,fadeIn:200,fadeOut:200,attribute:"title",content:false,enter:function(){},exit:function(){}};var opts=$.extend(defaults,options);if($("#tiptip_holder").length<=0){var tiptip_holder=$('
');var tiptip_content=$('
');var tiptip_arrow=$('
');$("body").append(tiptip_holder.html(tiptip_content).prepend(tiptip_arrow.html('
')))}else{var tiptip_holder=$("#tiptip_holder");var tiptip_content=$("#tiptip_content");var tiptip_arrow=$("#tiptip_arrow")}return this.each(function(){var org_elem=$(this);if(opts.content){var org_title=opts.content}else{var org_title=org_elem.attr(opts.attribute)}if(org_title!=""){if(!opts.content){org_elem.removeAttr(opts.attribute)}var timeout=false;if(opts.activation=="hover"){org_elem.hover(function(){active_tiptip()},function(){if(!opts.keepAlive){deactive_tiptip()}});if(opts.keepAlive){tiptip_holder.hover(function(){},function(){deactive_tiptip()})}}else if(opts.activation=="focus"){org_elem.focus(function(){active_tiptip()}).blur(function(){deactive_tiptip()})}else if(opts.activation=="click"){org_elem.click(function(){active_tiptip();return false}).hover(function(){},function(){if(!opts.keepAlive){deactive_tiptip()}});if(opts.keepAlive){tiptip_holder.hover(function(){},function(){deactive_tiptip()})}}function active_tiptip(){opts.enter.call(this);tiptip_content.html(org_title);tiptip_holder.hide().removeAttr("class").css("margin","0");tiptip_arrow.removeAttr("style");var top=parseInt(org_elem.offset()['top']);var left=parseInt(org_elem.offset()['left']);var org_width=parseInt(org_elem.outerWidth());var org_height=parseInt(org_elem.outerHeight());var tip_w=tiptip_holder.outerWidth();var tip_h=tiptip_holder.outerHeight();var w_compare=Math.round((org_width-tip_w)/2);var h_compare=Math.round((org_height-tip_h)/2);var marg_left=Math.round(left+w_compare);var marg_top=Math.round(top+org_height+opts.edgeOffset);var t_class="";var arrow_top="";var arrow_left=Math.round(tip_w-12)/2;if(opts.defaultPosition=="bottom"){t_class="_bottom"}else if(opts.defaultPosition=="top"){t_class="_top"}else if(opts.defaultPosition=="left"){t_class="_left"}else if(opts.defaultPosition=="right"){t_class="_right"}var right_compare=(w_compare+left)parseInt($(window).width());if((right_compare&&w_compare<0)||(t_class=="_right"&&!left_compare)||(t_class=="_left"&&left<(tip_w+opts.edgeOffset+5))){t_class="_right";arrow_top=Math.round(tip_h-13)/2;arrow_left=-12;marg_left=Math.round(left+org_width+opts.edgeOffset);marg_top=Math.round(top+h_compare)}else if((left_compare&&w_compare<0)||(t_class=="_left"&&!right_compare)){t_class="_left";arrow_top=Math.round(tip_h-13)/2;arrow_left=Math.round(tip_w);marg_left=Math.round(left-(tip_w+opts.edgeOffset+5));marg_top=Math.round(top+h_compare)}var top_compare=(top+org_height+opts.edgeOffset+tip_h+8)>parseInt($(window).height()+$(window).scrollTop());var bottom_compare=((top+org_height)-(opts.edgeOffset+tip_h+8))<0;if(top_compare||(t_class=="_bottom"&&top_compare)||(t_class=="_top"&&!bottom_compare)){if(t_class=="_top"||t_class=="_bottom"){t_class="_top"}else{t_class=t_class+"_top"}arrow_top=tip_h;marg_top=Math.round(top-(tip_h+5+opts.edgeOffset))}else if(bottom_compare|(t_class=="_top"&&bottom_compare)||(t_class=="_bottom"&&!top_compare)){if(t_class=="_top"||t_class=="_bottom"){t_class="_bottom"}else{t_class=t_class+"_bottom"}arrow_top=-12;marg_top=Math.round(top+org_height+opts.edgeOffset)}if(t_class=="_right_top"||t_class=="_left_top"){marg_top=marg_top+5}else if(t_class=="_right_bottom"||t_class=="_left_bottom"){marg_top=marg_top-5}if(t_class=="_left_top"||t_class=="_left_bottom"){marg_left=marg_left+5}tiptip_arrow.css({"margin-left":arrow_left+"px","margin-top":arrow_top+"px"});tiptip_holder.css({"margin-left":marg_left+"px","margin-top":marg_top+"px"}).attr("class","tip"+t_class);if(timeout){clearTimeout(timeout)}timeout=setTimeout(function(){tiptip_holder.stop(true,true).fadeIn(opts.fadeIn)},opts.delay)}function deactive_tiptip(){opts.exit.call(this);if(timeout){clearTimeout(timeout)}tiptip_holder.fadeOut(opts.fadeOut)}}})}})(jQuery); \ No newline at end of file diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/tipTipv13/tipTip.css b/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/tipTipv13/tipTip.css deleted file mode 100644 index 4fb95d3..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/lib/tipTipv13/tipTip.css +++ /dev/null @@ -1,113 +0,0 @@ -/* TipTip CSS - Version 1.2 */ - -#tiptip_holder { - display: none; - position: absolute; - top: 0; - left: 0; - z-index: 99999; -} - -#tiptip_holder.tip_top { - padding-bottom: 5px; -} - -#tiptip_holder.tip_bottom { - padding-top: 5px; -} - -#tiptip_holder.tip_right { - padding-left: 5px; -} - -#tiptip_holder.tip_left { - padding-right: 5px; -} - -#tiptip_content { - font-size: 11px; - color: #fff; - text-shadow: 0 0 2px #000; - padding: 4px 8px; - border: 1px solid rgba(255,255,255,0.25); - background-color: rgb(25,25,25); - background-color: rgba(25,25,25,0.92); - background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(transparent), to(#000)); - border-radius: 3px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - box-shadow: 0 0 3px #555; - -webkit-box-shadow: 0 0 3px #555; - -moz-box-shadow: 0 0 3px #555; -} - -#tiptip_arrow, #tiptip_arrow_inner { - position: absolute; - border-color: transparent; - border-style: solid; - border-width: 6px; - height: 0; - width: 0; -} - -#tiptip_holder.tip_top #tiptip_arrow { - border-top-color: #fff; - border-top-color: rgba(255,255,255,0.35); -} - -#tiptip_holder.tip_bottom #tiptip_arrow { - border-bottom-color: #fff; - border-bottom-color: rgba(255,255,255,0.35); -} - -#tiptip_holder.tip_right #tiptip_arrow { - border-right-color: #fff; - border-right-color: rgba(255,255,255,0.35); -} - -#tiptip_holder.tip_left #tiptip_arrow { - border-left-color: #fff; - border-left-color: rgba(255,255,255,0.35); -} - -#tiptip_holder.tip_top #tiptip_arrow_inner { - margin-top: -7px; - margin-left: -6px; - border-top-color: rgb(25,25,25); - border-top-color: rgba(25,25,25,0.92); -} - -#tiptip_holder.tip_bottom #tiptip_arrow_inner { - margin-top: -5px; - margin-left: -6px; - border-bottom-color: rgb(25,25,25); - border-bottom-color: rgba(25,25,25,0.92); -} - -#tiptip_holder.tip_right #tiptip_arrow_inner { - margin-top: -6px; - margin-left: -5px; - border-right-color: rgb(25,25,25); - border-right-color: rgba(25,25,25,0.92); -} - -#tiptip_holder.tip_left #tiptip_arrow_inner { - margin-top: -6px; - margin-left: -7px; - border-left-color: rgb(25,25,25); - border-left-color: rgba(25,25,25,0.92); -} - -/* Webkit Hacks */ -@media screen and (-webkit-min-device-pixel-ratio:0) { - #tiptip_content { - padding: 4px 8px 5px 8px; - background-color: rgba(45,45,45,0.88); - } - #tiptip_holder.tip_bottom #tiptip_arrow_inner { - border-bottom-color: rgba(45,45,45,0.88); - } - #tiptip_holder.tip_top #tiptip_arrow_inner { - border-top-color: rgba(20,20,20,0.92); - } -} \ No newline at end of file diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/tests/lib/prototype.js b/extension/sandbox/chrome-extensions-samples/apps/samples/clock/tests/lib/prototype.js deleted file mode 100644 index 8219200..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/tests/lib/prototype.js +++ /dev/null @@ -1,7036 +0,0 @@ -/* Prototype JavaScript framework, version 1.7.1 - * (c) 2005-2010 Sam Stephenson - * - * Prototype is freely distributable under the terms of an MIT-style license. - * For details, see the Prototype web site: http://www.prototypejs.org/ - * - *--------------------------------------------------------------------------*/ - -var Prototype = { - - Version: '1.7.1', - - Browser: (function(){ - var ua = navigator.userAgent; - var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'; - return { - IE: !!window.attachEvent && !isOpera, - Opera: isOpera, - WebKit: ua.indexOf('AppleWebKit/') > -1, - Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1, - MobileSafari: /Apple.*Mobile/.test(ua) - } - })(), - - BrowserFeatures: { - XPath: !!document.evaluate, - - SelectorsAPI: !!document.querySelector, - - ElementExtensions: (function() { - var constructor = window.Element || window.HTMLElement; - return !!(constructor && constructor.prototype); - })(), - SpecificElementExtensions: (function() { - if (typeof window.HTMLDivElement !== 'undefined') - return true; - - var div = document.createElement('div'), - form = document.createElement('form'), - isSupported = false; - - if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) { - isSupported = true; - } - - div = form = null; - - return isSupported; - })() - }, - - ScriptFragment: ']*>([\\S\\s]*?)<\/script\\s*>', - JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, - - emptyFunction: function() { }, - - K: function(x) { return x } -}; - -if (Prototype.Browser.MobileSafari) - Prototype.BrowserFeatures.SpecificElementExtensions = false; -/* Based on Alex Arnell's inheritance implementation. */ - -var Class = (function() { - - var IS_DONTENUM_BUGGY = (function(){ - for (var p in { toString: 1 }) { - if (p === 'toString') return false; - } - return true; - })(); - - function subclass() {}; - function create() { - var parent = null, properties = $A(arguments); - if (Object.isFunction(properties[0])) - parent = properties.shift(); - - function klass() { - this.initialize.apply(this, arguments); - } - - Object.extend(klass, Class.Methods); - klass.superclass = parent; - klass.subclasses = []; - - if (parent) { - subclass.prototype = parent.prototype; - klass.prototype = new subclass; - parent.subclasses.push(klass); - } - - for (var i = 0, length = properties.length; i < length; i++) - klass.addMethods(properties[i]); - - if (!klass.prototype.initialize) - klass.prototype.initialize = Prototype.emptyFunction; - - klass.prototype.constructor = klass; - return klass; - } - - function addMethods(source) { - var ancestor = this.superclass && this.superclass.prototype, - properties = Object.keys(source); - - if (IS_DONTENUM_BUGGY) { - if (source.toString != Object.prototype.toString) - properties.push("toString"); - if (source.valueOf != Object.prototype.valueOf) - properties.push("valueOf"); - } - - for (var i = 0, length = properties.length; i < length; i++) { - var property = properties[i], value = source[property]; - if (ancestor && Object.isFunction(value) && - value.argumentNames()[0] == "$super") { - var method = value; - value = (function(m) { - return function() { return ancestor[m].apply(this, arguments); }; - })(property).wrap(method); - - value.valueOf = (function(method) { - return function() { return method.valueOf.call(method); }; - })(method); - - value.toString = (function(method) { - return function() { return method.toString.call(method); }; - })(method); - } - this.prototype[property] = value; - } - - return this; - } - - return { - create: create, - Methods: { - addMethods: addMethods - } - }; -})(); -(function() { - - var _toString = Object.prototype.toString, - _hasOwnProperty = Object.prototype.hasOwnProperty, - NULL_TYPE = 'Null', - UNDEFINED_TYPE = 'Undefined', - BOOLEAN_TYPE = 'Boolean', - NUMBER_TYPE = 'Number', - STRING_TYPE = 'String', - OBJECT_TYPE = 'Object', - FUNCTION_CLASS = '[object Function]', - BOOLEAN_CLASS = '[object Boolean]', - NUMBER_CLASS = '[object Number]', - STRING_CLASS = '[object String]', - ARRAY_CLASS = '[object Array]', - DATE_CLASS = '[object Date]', - NATIVE_JSON_STRINGIFY_SUPPORT = window.JSON && - typeof JSON.stringify === 'function' && - JSON.stringify(0) === '0' && - typeof JSON.stringify(Prototype.K) === 'undefined'; - - - - var DONT_ENUMS = ['toString', 'toLocaleString', 'valueOf', - 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor']; - - var IS_DONTENUM_BUGGY = (function(){ - for (var p in { toString: 1 }) { - if (p === 'toString') return false; - } - return true; - })(); - - function Type(o) { - switch(o) { - case null: return NULL_TYPE; - case (void 0): return UNDEFINED_TYPE; - } - var type = typeof o; - switch(type) { - case 'boolean': return BOOLEAN_TYPE; - case 'number': return NUMBER_TYPE; - case 'string': return STRING_TYPE; - } - return OBJECT_TYPE; - } - - function extend(destination, source) { - for (var property in source) - destination[property] = source[property]; - return destination; - } - - function inspect(object) { - try { - if (isUndefined(object)) return 'undefined'; - if (object === null) return 'null'; - return object.inspect ? object.inspect() : String(object); - } catch (e) { - if (e instanceof RangeError) return '...'; - throw e; - } - } - - function toJSON(value) { - return Str('', { '': value }, []); - } - - function Str(key, holder, stack) { - var value = holder[key]; - if (Type(value) === OBJECT_TYPE && typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - - var _class = _toString.call(value); - - switch (_class) { - case NUMBER_CLASS: - case BOOLEAN_CLASS: - case STRING_CLASS: - value = value.valueOf(); - } - - switch (value) { - case null: return 'null'; - case true: return 'true'; - case false: return 'false'; - } - - var type = typeof value; - switch (type) { - case 'string': - return value.inspect(true); - case 'number': - return isFinite(value) ? String(value) : 'null'; - case 'object': - - for (var i = 0, length = stack.length; i < length; i++) { - if (stack[i] === value) { - throw new TypeError("Cyclic reference to '" + value + "' in object"); - } - } - stack.push(value); - - var partial = []; - if (_class === ARRAY_CLASS) { - for (var i = 0, length = value.length; i < length; i++) { - var str = Str(i, value, stack); - partial.push(typeof str === 'undefined' ? 'null' : str); - } - partial = '[' + partial.join(',') + ']'; - } else { - var keys = Object.keys(value); - for (var i = 0, length = keys.length; i < length; i++) { - var key = keys[i], str = Str(key, value, stack); - if (typeof str !== "undefined") { - partial.push(key.inspect(true)+ ':' + str); - } - } - partial = '{' + partial.join(',') + '}'; - } - stack.pop(); - return partial; - } - } - - function stringify(object) { - return JSON.stringify(object); - } - - function toQueryString(object) { - return $H(object).toQueryString(); - } - - function toHTML(object) { - return object && object.toHTML ? object.toHTML() : String.interpret(object); - } - - function keys(object) { - if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); } - var results = []; - for (var property in object) { - if (_hasOwnProperty.call(object, property)) - results.push(property); - } - - if (IS_DONTENUM_BUGGY) { - for (var i = 0; property = DONT_ENUMS[i]; i++) { - if (_hasOwnProperty.call(object, property)) - results.push(property); - } - } - - return results; - } - - function values(object) { - var results = []; - for (var property in object) - results.push(object[property]); - return results; - } - - function clone(object) { - return extend({ }, object); - } - - function isElement(object) { - return !!(object && object.nodeType == 1); - } - - function isArray(object) { - return _toString.call(object) === ARRAY_CLASS; - } - - var hasNativeIsArray = (typeof Array.isArray == 'function') - && Array.isArray([]) && !Array.isArray({}); - - if (hasNativeIsArray) { - isArray = Array.isArray; - } - - function isHash(object) { - return object instanceof Hash; - } - - function isFunction(object) { - return _toString.call(object) === FUNCTION_CLASS; - } - - function isString(object) { - return _toString.call(object) === STRING_CLASS; - } - - function isNumber(object) { - return _toString.call(object) === NUMBER_CLASS; - } - - function isDate(object) { - return _toString.call(object) === DATE_CLASS; - } - - function isUndefined(object) { - return typeof object === "undefined"; - } - - extend(Object, { - extend: extend, - inspect: inspect, - toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON, - toQueryString: toQueryString, - toHTML: toHTML, - keys: Object.keys || keys, - values: values, - clone: clone, - isElement: isElement, - isArray: isArray, - isHash: isHash, - isFunction: isFunction, - isString: isString, - isNumber: isNumber, - isDate: isDate, - isUndefined: isUndefined - }); -})(); -Object.extend(Function.prototype, (function() { - var slice = Array.prototype.slice; - - function update(array, args) { - var arrayLength = array.length, length = args.length; - while (length--) array[arrayLength + length] = args[length]; - return array; - } - - function merge(array, args) { - array = slice.call(array, 0); - return update(array, args); - } - - function argumentNames() { - var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1] - .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '') - .replace(/\s+/g, '').split(','); - return names.length == 1 && !names[0] ? [] : names; - } - - - function bind(context) { - if (arguments.length < 2 && Object.isUndefined(arguments[0])) - return this; - - if (!Object.isFunction(this)) - throw new TypeError("The object is not callable."); - - var nop = function() {}; - var __method = this, args = slice.call(arguments, 1); - - var bound = function() { - var a = merge(args, arguments), c = context; - var c = this instanceof bound ? this : context; - return __method.apply(c, a); - }; - - nop.prototype = this.prototype; - bound.prototype = new nop(); - - return bound; - } - - function bindAsEventListener(context) { - var __method = this, args = slice.call(arguments, 1); - return function(event) { - var a = update([event || window.event], args); - return __method.apply(context, a); - } - } - - function curry() { - if (!arguments.length) return this; - var __method = this, args = slice.call(arguments, 0); - return function() { - var a = merge(args, arguments); - return __method.apply(this, a); - } - } - - function delay(timeout) { - var __method = this, args = slice.call(arguments, 1); - timeout = timeout * 1000; - return window.setTimeout(function() { - return __method.apply(__method, args); - }, timeout); - } - - function defer() { - var args = update([0.01], arguments); - return this.delay.apply(this, args); - } - - function wrap(wrapper) { - var __method = this; - return function() { - var a = update([__method.bind(this)], arguments); - return wrapper.apply(this, a); - } - } - - function methodize() { - if (this._methodized) return this._methodized; - var __method = this; - return this._methodized = function() { - var a = update([this], arguments); - return __method.apply(null, a); - }; - } - - var extensions = { - argumentNames: argumentNames, - bindAsEventListener: bindAsEventListener, - curry: curry, - delay: delay, - defer: defer, - wrap: wrap, - methodize: methodize - }; - - if (!Function.prototype.bind) - extensions.bind = bind; - - return extensions; -})()); - - - -(function(proto) { - - - function toISOString() { - return this.getUTCFullYear() + '-' + - (this.getUTCMonth() + 1).toPaddedString(2) + '-' + - this.getUTCDate().toPaddedString(2) + 'T' + - this.getUTCHours().toPaddedString(2) + ':' + - this.getUTCMinutes().toPaddedString(2) + ':' + - this.getUTCSeconds().toPaddedString(2) + 'Z'; - } - - - function toJSON() { - return this.toISOString(); - } - - if (!proto.toISOString) proto.toISOString = toISOString; - if (!proto.toJSON) proto.toJSON = toJSON; - -})(Date.prototype); - - -RegExp.prototype.match = RegExp.prototype.test; - -RegExp.escape = function(str) { - return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); -}; -var PeriodicalExecuter = Class.create({ - initialize: function(callback, frequency) { - this.callback = callback; - this.frequency = frequency; - this.currentlyExecuting = false; - - this.registerCallback(); - }, - - registerCallback: function() { - this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); - }, - - execute: function() { - this.callback(this); - }, - - stop: function() { - if (!this.timer) return; - clearInterval(this.timer); - this.timer = null; - }, - - onTimerEvent: function() { - if (!this.currentlyExecuting) { - try { - this.currentlyExecuting = true; - this.execute(); - this.currentlyExecuting = false; - } catch(e) { - this.currentlyExecuting = false; - throw e; - } - } - } -}); -Object.extend(String, { - interpret: function(value) { - return value == null ? '' : String(value); - }, - specialChar: { - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '\\': '\\\\' - } -}); - -Object.extend(String.prototype, (function() { - var NATIVE_JSON_PARSE_SUPPORT = window.JSON && - typeof JSON.parse === 'function' && - JSON.parse('{"test": true}').test; - - function prepareReplacement(replacement) { - if (Object.isFunction(replacement)) return replacement; - var template = new Template(replacement); - return function(match) { return template.evaluate(match) }; - } - - function gsub(pattern, replacement) { - var result = '', source = this, match; - replacement = prepareReplacement(replacement); - - if (Object.isString(pattern)) - pattern = RegExp.escape(pattern); - - if (!(pattern.length || pattern.source)) { - replacement = replacement(''); - return replacement + source.split('').join(replacement) + replacement; - } - - while (source.length > 0) { - if (match = source.match(pattern)) { - result += source.slice(0, match.index); - result += String.interpret(replacement(match)); - source = source.slice(match.index + match[0].length); - } else { - result += source, source = ''; - } - } - return result; - } - - function sub(pattern, replacement, count) { - replacement = prepareReplacement(replacement); - count = Object.isUndefined(count) ? 1 : count; - - return this.gsub(pattern, function(match) { - if (--count < 0) return match[0]; - return replacement(match); - }); - } - - function scan(pattern, iterator) { - this.gsub(pattern, iterator); - return String(this); - } - - function truncate(length, truncation) { - length = length || 30; - truncation = Object.isUndefined(truncation) ? '...' : truncation; - return this.length > length ? - this.slice(0, length - truncation.length) + truncation : String(this); - } - - function strip() { - return this.replace(/^\s+/, '').replace(/\s+$/, ''); - } - - function stripTags() { - return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, ''); - } - - function stripScripts() { - return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); - } - - function extractScripts() { - var matchAll = new RegExp(Prototype.ScriptFragment, 'img'), - matchOne = new RegExp(Prototype.ScriptFragment, 'im'); - return (this.match(matchAll) || []).map(function(scriptTag) { - return (scriptTag.match(matchOne) || ['', ''])[1]; - }); - } - - function evalScripts() { - return this.extractScripts().map(function(script) { return eval(script); }); - } - - function escapeHTML() { - return this.replace(/&/g,'&').replace(//g,'>'); - } - - function unescapeHTML() { - return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&'); - } - - - function toQueryParams(separator) { - var match = this.strip().match(/([^?#]*)(#.*)?$/); - if (!match) return { }; - - return match[1].split(separator || '&').inject({ }, function(hash, pair) { - if ((pair = pair.split('='))[0]) { - var key = decodeURIComponent(pair.shift()), - value = pair.length > 1 ? pair.join('=') : pair[0]; - - if (value != undefined) value = decodeURIComponent(value); - - if (key in hash) { - if (!Object.isArray(hash[key])) hash[key] = [hash[key]]; - hash[key].push(value); - } - else hash[key] = value; - } - return hash; - }); - } - - function toArray() { - return this.split(''); - } - - function succ() { - return this.slice(0, this.length - 1) + - String.fromCharCode(this.charCodeAt(this.length - 1) + 1); - } - - function times(count) { - return count < 1 ? '' : new Array(count + 1).join(this); - } - - function camelize() { - return this.replace(/-+(.)?/g, function(match, chr) { - return chr ? chr.toUpperCase() : ''; - }); - } - - function capitalize() { - return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); - } - - function underscore() { - return this.replace(/::/g, '/') - .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') - .replace(/([a-z\d])([A-Z])/g, '$1_$2') - .replace(/-/g, '_') - .toLowerCase(); - } - - function dasherize() { - return this.replace(/_/g, '-'); - } - - function inspect(useDoubleQuotes) { - var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) { - if (character in String.specialChar) { - return String.specialChar[character]; - } - return '\\u00' + character.charCodeAt().toPaddedString(2, 16); - }); - if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; - return "'" + escapedString.replace(/'/g, '\\\'') + "'"; - } - - function unfilterJSON(filter) { - return this.replace(filter || Prototype.JSONFilter, '$1'); - } - - function isJSON() { - var str = this; - if (str.blank()) return false; - str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'); - str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); - str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, ''); - return (/^[\],:{}\s]*$/).test(str); - } - - function evalJSON(sanitize) { - var json = this.unfilterJSON(), - cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - if (cx.test(json)) { - json = json.replace(cx, function (a) { - return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - try { - if (!sanitize || json.isJSON()) return eval('(' + json + ')'); - } catch (e) { } - throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); - } - - function parseJSON() { - var json = this.unfilterJSON(); - return JSON.parse(json); - } - - function include(pattern) { - return this.indexOf(pattern) > -1; - } - - function startsWith(pattern) { - return this.lastIndexOf(pattern, 0) === 0; - } - - function endsWith(pattern) { - var d = this.length - pattern.length; - return d >= 0 && this.indexOf(pattern, d) === d; - } - - function empty() { - return this == ''; - } - - function blank() { - return /^\s*$/.test(this); - } - - function interpolate(object, pattern) { - return new Template(this, pattern).evaluate(object); - } - - return { - gsub: gsub, - sub: sub, - scan: scan, - truncate: truncate, - strip: String.prototype.trim || strip, - stripTags: stripTags, - stripScripts: stripScripts, - extractScripts: extractScripts, - evalScripts: evalScripts, - escapeHTML: escapeHTML, - unescapeHTML: unescapeHTML, - toQueryParams: toQueryParams, - parseQuery: toQueryParams, - toArray: toArray, - succ: succ, - times: times, - camelize: camelize, - capitalize: capitalize, - underscore: underscore, - dasherize: dasherize, - inspect: inspect, - unfilterJSON: unfilterJSON, - isJSON: isJSON, - evalJSON: NATIVE_JSON_PARSE_SUPPORT ? parseJSON : evalJSON, - include: include, - startsWith: startsWith, - endsWith: endsWith, - empty: empty, - blank: blank, - interpolate: interpolate - }; -})()); - -var Template = Class.create({ - initialize: function(template, pattern) { - this.template = template.toString(); - this.pattern = pattern || Template.Pattern; - }, - - evaluate: function(object) { - if (object && Object.isFunction(object.toTemplateReplacements)) - object = object.toTemplateReplacements(); - - return this.template.gsub(this.pattern, function(match) { - if (object == null) return (match[1] + ''); - - var before = match[1] || ''; - if (before == '\\') return match[2]; - - var ctx = object, expr = match[3], - pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/; - - match = pattern.exec(expr); - if (match == null) return before; - - while (match != null) { - var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : match[1]; - ctx = ctx[comp]; - if (null == ctx || '' == match[3]) break; - expr = expr.substring('[' == match[3] ? match[1].length : match[0].length); - match = pattern.exec(expr); - } - - return before + String.interpret(ctx); - }); - } -}); -Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; - -var $break = { }; - -var Enumerable = (function() { - function each(iterator, context) { - try { - this._each(iterator, context); - } catch (e) { - if (e != $break) throw e; - } - return this; - } - - function eachSlice(number, iterator, context) { - var index = -number, slices = [], array = this.toArray(); - if (number < 1) return array; - while ((index += number) < array.length) - slices.push(array.slice(index, index+number)); - return slices.collect(iterator, context); - } - - function all(iterator, context) { - iterator = iterator || Prototype.K; - var result = true; - this.each(function(value, index) { - result = result && !!iterator.call(context, value, index, this); - if (!result) throw $break; - }, this); - return result; - } - - function any(iterator, context) { - iterator = iterator || Prototype.K; - var result = false; - this.each(function(value, index) { - if (result = !!iterator.call(context, value, index, this)) - throw $break; - }, this); - return result; - } - - function collect(iterator, context) { - iterator = iterator || Prototype.K; - var results = []; - this.each(function(value, index) { - results.push(iterator.call(context, value, index, this)); - }, this); - return results; - } - - function detect(iterator, context) { - var result; - this.each(function(value, index) { - if (iterator.call(context, value, index, this)) { - result = value; - throw $break; - } - }, this); - return result; - } - - function findAll(iterator, context) { - var results = []; - this.each(function(value, index) { - if (iterator.call(context, value, index, this)) - results.push(value); - }, this); - return results; - } - - function grep(filter, iterator, context) { - iterator = iterator || Prototype.K; - var results = []; - - if (Object.isString(filter)) - filter = new RegExp(RegExp.escape(filter)); - - this.each(function(value, index) { - if (filter.match(value)) - results.push(iterator.call(context, value, index, this)); - }, this); - return results; - } - - function include(object) { - if (Object.isFunction(this.indexOf)) - if (this.indexOf(object) != -1) return true; - - var found = false; - this.each(function(value) { - if (value == object) { - found = true; - throw $break; - } - }); - return found; - } - - function inGroupsOf(number, fillWith) { - fillWith = Object.isUndefined(fillWith) ? null : fillWith; - return this.eachSlice(number, function(slice) { - while(slice.length < number) slice.push(fillWith); - return slice; - }); - } - - function inject(memo, iterator, context) { - this.each(function(value, index) { - memo = iterator.call(context, memo, value, index, this); - }, this); - return memo; - } - - function invoke(method) { - var args = $A(arguments).slice(1); - return this.map(function(value) { - return value[method].apply(value, args); - }); - } - - function max(iterator, context) { - iterator = iterator || Prototype.K; - var result; - this.each(function(value, index) { - value = iterator.call(context, value, index, this); - if (result == null || value >= result) - result = value; - }, this); - return result; - } - - function min(iterator, context) { - iterator = iterator || Prototype.K; - var result; - this.each(function(value, index) { - value = iterator.call(context, value, index, this); - if (result == null || value < result) - result = value; - }, this); - return result; - } - - function partition(iterator, context) { - iterator = iterator || Prototype.K; - var trues = [], falses = []; - this.each(function(value, index) { - (iterator.call(context, value, index, this) ? - trues : falses).push(value); - }, this); - return [trues, falses]; - } - - function pluck(property) { - var results = []; - this.each(function(value) { - results.push(value[property]); - }); - return results; - } - - function reject(iterator, context) { - var results = []; - this.each(function(value, index) { - if (!iterator.call(context, value, index, this)) - results.push(value); - }, this); - return results; - } - - function sortBy(iterator, context) { - return this.map(function(value, index) { - return { - value: value, - criteria: iterator.call(context, value, index, this) - }; - }, this).sort(function(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }).pluck('value'); - } - - function toArray() { - return this.map(); - } - - function zip() { - var iterator = Prototype.K, args = $A(arguments); - if (Object.isFunction(args.last())) - iterator = args.pop(); - - var collections = [this].concat(args).map($A); - return this.map(function(value, index) { - return iterator(collections.pluck(index)); - }); - } - - function size() { - return this.toArray().length; - } - - function inspect() { - return '#'; - } - - - - - - - - - - return { - each: each, - eachSlice: eachSlice, - all: all, - every: all, - any: any, - some: any, - collect: collect, - map: collect, - detect: detect, - findAll: findAll, - select: findAll, - filter: findAll, - grep: grep, - include: include, - member: include, - inGroupsOf: inGroupsOf, - inject: inject, - invoke: invoke, - max: max, - min: min, - partition: partition, - pluck: pluck, - reject: reject, - sortBy: sortBy, - toArray: toArray, - entries: toArray, - zip: zip, - size: size, - inspect: inspect, - find: detect - }; -})(); - -function $A(iterable) { - if (!iterable) return []; - if ('toArray' in Object(iterable)) return iterable.toArray(); - var length = iterable.length || 0, results = new Array(length); - while (length--) results[length] = iterable[length]; - return results; -} - - -function $w(string) { - if (!Object.isString(string)) return []; - string = string.strip(); - return string ? string.split(/\s+/) : []; -} - -Array.from = $A; - - -(function() { - var arrayProto = Array.prototype, - slice = arrayProto.slice, - _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available - - function each(iterator, context) { - for (var i = 0, length = this.length >>> 0; i < length; i++) { - if (i in this) iterator.call(context, this[i], i, this); - } - } - if (!_each) _each = each; - - function clear() { - this.length = 0; - return this; - } - - function first() { - return this[0]; - } - - function last() { - return this[this.length - 1]; - } - - function compact() { - return this.select(function(value) { - return value != null; - }); - } - - function flatten() { - return this.inject([], function(array, value) { - if (Object.isArray(value)) - return array.concat(value.flatten()); - array.push(value); - return array; - }); - } - - function without() { - var values = slice.call(arguments, 0); - return this.select(function(value) { - return !values.include(value); - }); - } - - function reverse(inline) { - return (inline === false ? this.toArray() : this)._reverse(); - } - - function uniq(sorted) { - return this.inject([], function(array, value, index) { - if (0 == index || (sorted ? array.last() != value : !array.include(value))) - array.push(value); - return array; - }); - } - - function intersect(array) { - return this.uniq().findAll(function(item) { - return array.indexOf(item) !== -1; - }); - } - - - function clone() { - return slice.call(this, 0); - } - - function size() { - return this.length; - } - - function inspect() { - return '[' + this.map(Object.inspect).join(', ') + ']'; - } - - function indexOf(item, i) { - if (this == null) throw new TypeError(); - - var array = Object(this), length = array.length >>> 0; - if (length === 0) return -1; - - i = Number(i); - if (isNaN(i)) { - i = 0; - } else if (i !== 0 && isFinite(i)) { - i = (i > 0 ? 1 : -1) * Math.floor(Math.abs(i)); - } - - if (i > length) return -1; - - var k = i >= 0 ? i : Math.max(length - Math.abs(i), 0); - for (; k < length; k++) - if (k in array && array[k] === item) return k; - return -1; - } - - - function lastIndexOf(item, i) { - if (this == null) throw new TypeError(); - - var array = Object(this), length = array.length >>> 0; - if (length === 0) return -1; - - if (!Object.isUndefined(i)) { - i = Number(i); - if (isNaN(i)) { - i = 0; - } else if (i !== 0 && isFinite(i)) { - i = (i > 0 ? 1 : -1) * Math.floor(Math.abs(i)); - } - } else { - i = length; - } - - var k = i >= 0 ? Math.min(i, length - 1) : - length - Math.abs(i); - - for (; k >= 0; k--) - if (k in array && array[k] === item) return k; - return -1; - } - - function concat(_) { - var array = [], items = slice.call(arguments, 0), item, n = 0; - items.unshift(this); - for (var i = 0, length = items.length; i < length; i++) { - item = items[i]; - if (Object.isArray(item) && !('callee' in item)) { - for (var j = 0, arrayLength = item.length; j < arrayLength; j++) { - if (j in item) array[n] = item[j]; - n++; - } - } else { - array[n++] = item; - } - } - array.length = n; - return array; - } - - - function wrapNative(method) { - return function() { - if (arguments.length === 0) { - return method.call(this, Prototype.K); - } else if (arguments[0] === undefined) { - var args = slice.call(arguments, 1); - args.unshift(Prototype.K); - return method.apply(this, args); - } else { - return method.apply(this, arguments); - } - }; - } - - - function map(iterator) { - if (this == null) throw new TypeError(); - iterator = iterator || Prototype.K; - - var object = Object(this); - var results = [], context = arguments[1], n = 0; - - for (var i = 0, length = object.length >>> 0; i < length; i++) { - if (i in object) { - results[n] = iterator.call(context, object[i], i, object); - } - n++; - } - results.length = n; - return results; - } - - if (arrayProto.map) { - map = wrapNative(Array.prototype.map); - } - - function filter(iterator) { - if (this == null || !Object.isFunction(iterator)) - throw new TypeError(); - - var object = Object(this); - var results = [], context = arguments[1], value; - - for (var i = 0, length = object.length >>> 0; i < length; i++) { - if (i in object) { - value = object[i]; - if (iterator.call(context, value, i, object)) { - results.push(value); - } - } - } - return results; - } - - if (arrayProto.filter) { - filter = Array.prototype.filter; - } - - function some(iterator) { - if (this == null) throw new TypeError(); - iterator = iterator || Prototype.K; - var context = arguments[1]; - - var object = Object(this); - for (var i = 0, length = object.length >>> 0; i < length; i++) { - if (i in object && iterator.call(context, object[i], i, object)) { - return true; - } - } - - return false; - } - - if (arrayProto.some) { - var some = wrapNative(Array.prototype.some); - } - - - function every(iterator) { - if (this == null) throw new TypeError(); - iterator = iterator || Prototype.K; - var context = arguments[1]; - - var object = Object(this); - for (var i = 0, length = object.length >>> 0; i < length; i++) { - if (i in object && !iterator.call(context, object[i], i, object)) { - return false; - } - } - - return true; - } - - if (arrayProto.every) { - var every = wrapNative(Array.prototype.every); - } - - var _reduce = arrayProto.reduce; - function inject(memo, iterator) { - iterator = iterator || Prototype.K; - var context = arguments[2]; - return _reduce.call(this, iterator.bind(context), memo); - } - - if (!arrayProto.reduce) { - var inject = Enumerable.inject; - } - - Object.extend(arrayProto, Enumerable); - - if (!arrayProto._reverse) - arrayProto._reverse = arrayProto.reverse; - - Object.extend(arrayProto, { - _each: _each, - - map: map, - collect: map, - select: filter, - filter: filter, - findAll: filter, - some: some, - any: some, - every: every, - all: every, - inject: inject, - - clear: clear, - first: first, - last: last, - compact: compact, - flatten: flatten, - without: without, - reverse: reverse, - uniq: uniq, - intersect: intersect, - clone: clone, - toArray: clone, - size: size, - inspect: inspect - }); - - var CONCAT_ARGUMENTS_BUGGY = (function() { - return [].concat(arguments)[0][0] !== 1; - })(1,2); - - if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat; - - if (!arrayProto.indexOf) arrayProto.indexOf = indexOf; - if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf; -})(); -function $H(object) { - return new Hash(object); -}; - -var Hash = Class.create(Enumerable, (function() { - function initialize(object) { - this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); - } - - - function _each(iterator, context) { - for (var key in this._object) { - var value = this._object[key], pair = [key, value]; - pair.key = key; - pair.value = value; - iterator.call(context, pair); - } - } - - function set(key, value) { - return this._object[key] = value; - } - - function get(key) { - if (this._object[key] !== Object.prototype[key]) - return this._object[key]; - } - - function unset(key) { - var value = this._object[key]; - delete this._object[key]; - return value; - } - - function toObject() { - return Object.clone(this._object); - } - - - - function keys() { - return this.pluck('key'); - } - - function values() { - return this.pluck('value'); - } - - function index(value) { - var match = this.detect(function(pair) { - return pair.value === value; - }); - return match && match.key; - } - - function merge(object) { - return this.clone().update(object); - } - - function update(object) { - return new Hash(object).inject(this, function(result, pair) { - result.set(pair.key, pair.value); - return result; - }); - } - - function toQueryPair(key, value) { - if (Object.isUndefined(value)) return key; - - var value = String.interpret(value); - - value = value.gsub(/(\r)?\n/, '\r\n'); - value = encodeURIComponent(value); - value = value.gsub(/%20/, '+'); - return key + '=' + value; - } - - function toQueryString() { - return this.inject([], function(results, pair) { - var key = encodeURIComponent(pair.key), values = pair.value; - - if (values && typeof values == 'object') { - if (Object.isArray(values)) { - var queryValues = []; - for (var i = 0, len = values.length, value; i < len; i++) { - value = values[i]; - queryValues.push(toQueryPair(key, value)); - } - return results.concat(queryValues); - } - } else results.push(toQueryPair(key, values)); - return results; - }).join('&'); - } - - function inspect() { - return '#'; - } - - function clone() { - return new Hash(this); - } - - return { - initialize: initialize, - _each: _each, - set: set, - get: get, - unset: unset, - toObject: toObject, - toTemplateReplacements: toObject, - keys: keys, - values: values, - index: index, - merge: merge, - update: update, - toQueryString: toQueryString, - inspect: inspect, - toJSON: toObject, - clone: clone - }; -})()); - -Hash.from = $H; -Object.extend(Number.prototype, (function() { - function toColorPart() { - return this.toPaddedString(2, 16); - } - - function succ() { - return this + 1; - } - - function times(iterator, context) { - $R(0, this, true).each(iterator, context); - return this; - } - - function toPaddedString(length, radix) { - var string = this.toString(radix || 10); - return '0'.times(length - string.length) + string; - } - - function abs() { - return Math.abs(this); - } - - function round() { - return Math.round(this); - } - - function ceil() { - return Math.ceil(this); - } - - function floor() { - return Math.floor(this); - } - - return { - toColorPart: toColorPart, - succ: succ, - times: times, - toPaddedString: toPaddedString, - abs: abs, - round: round, - ceil: ceil, - floor: floor - }; -})()); - -function $R(start, end, exclusive) { - return new ObjectRange(start, end, exclusive); -} - -var ObjectRange = Class.create(Enumerable, (function() { - function initialize(start, end, exclusive) { - this.start = start; - this.end = end; - this.exclusive = exclusive; - } - - function _each(iterator, context) { - var value = this.start; - while (this.include(value)) { - iterator.call(context, value); - value = value.succ(); - } - } - - function include(value) { - if (value < this.start) - return false; - if (this.exclusive) - return value < this.end; - return value <= this.end; - } - - return { - initialize: initialize, - _each: _each, - include: include - }; -})()); - - - -var Abstract = { }; - - -var Try = { - these: function() { - var returnValue; - - for (var i = 0, length = arguments.length; i < length; i++) { - var lambda = arguments[i]; - try { - returnValue = lambda(); - break; - } catch (e) { } - } - - return returnValue; - } -}; - -var Ajax = { - getTransport: function() { - return Try.these( - function() {return new XMLHttpRequest()}, - function() {return new ActiveXObject('Msxml2.XMLHTTP')}, - function() {return new ActiveXObject('Microsoft.XMLHTTP')} - ) || false; - }, - - activeRequestCount: 0 -}; - -Ajax.Responders = { - responders: [], - - _each: function(iterator, context) { - this.responders._each(iterator, context); - }, - - register: function(responder) { - if (!this.include(responder)) - this.responders.push(responder); - }, - - unregister: function(responder) { - this.responders = this.responders.without(responder); - }, - - dispatch: function(callback, request, transport, json) { - this.each(function(responder) { - if (Object.isFunction(responder[callback])) { - try { - responder[callback].apply(responder, [request, transport, json]); - } catch (e) { } - } - }); - } -}; - -Object.extend(Ajax.Responders, Enumerable); - -Ajax.Responders.register({ - onCreate: function() { Ajax.activeRequestCount++ }, - onComplete: function() { Ajax.activeRequestCount-- } -}); -Ajax.Base = Class.create({ - initialize: function(options) { - this.options = { - method: 'post', - asynchronous: true, - contentType: 'application/x-www-form-urlencoded', - encoding: 'UTF-8', - parameters: '', - evalJSON: true, - evalJS: true - }; - Object.extend(this.options, options || { }); - - this.options.method = this.options.method.toLowerCase(); - - if (Object.isHash(this.options.parameters)) - this.options.parameters = this.options.parameters.toObject(); - } -}); -Ajax.Request = Class.create(Ajax.Base, { - _complete: false, - - initialize: function($super, url, options) { - $super(options); - this.transport = Ajax.getTransport(); - this.request(url); - }, - - request: function(url) { - this.url = url; - this.method = this.options.method; - var params = Object.isString(this.options.parameters) ? - this.options.parameters : - Object.toQueryString(this.options.parameters); - - if (!['get', 'post'].include(this.method)) { - params += (params ? '&' : '') + "_method=" + this.method; - this.method = 'post'; - } - - if (params && this.method === 'get') { - this.url += (this.url.include('?') ? '&' : '?') + params; - } - - this.parameters = params.toQueryParams(); - - try { - var response = new Ajax.Response(this); - if (this.options.onCreate) this.options.onCreate(response); - Ajax.Responders.dispatch('onCreate', this, response); - - this.transport.open(this.method.toUpperCase(), this.url, - this.options.asynchronous); - - if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1); - - this.transport.onreadystatechange = this.onStateChange.bind(this); - this.setRequestHeaders(); - - this.body = this.method == 'post' ? (this.options.postBody || params) : null; - this.transport.send(this.body); - - /* Force Firefox to handle ready state 4 for synchronous requests */ - if (!this.options.asynchronous && this.transport.overrideMimeType) - this.onStateChange(); - - } - catch (e) { - this.dispatchException(e); - } - }, - - onStateChange: function() { - var readyState = this.transport.readyState; - if (readyState > 1 && !((readyState == 4) && this._complete)) - this.respondToReadyState(this.transport.readyState); - }, - - setRequestHeaders: function() { - var headers = { - 'X-Requested-With': 'XMLHttpRequest', - 'X-Prototype-Version': Prototype.Version, - 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' - }; - - if (this.method == 'post') { - headers['Content-type'] = this.options.contentType + - (this.options.encoding ? '; charset=' + this.options.encoding : ''); - - /* Force "Connection: close" for older Mozilla browsers to work - * around a bug where XMLHttpRequest sends an incorrect - * Content-length header. See Mozilla Bugzilla #246651. - */ - if (this.transport.overrideMimeType && - (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) - headers['Connection'] = 'close'; - } - - if (typeof this.options.requestHeaders == 'object') { - var extras = this.options.requestHeaders; - - if (Object.isFunction(extras.push)) - for (var i = 0, length = extras.length; i < length; i += 2) - headers[extras[i]] = extras[i+1]; - else - $H(extras).each(function(pair) { headers[pair.key] = pair.value }); - } - - for (var name in headers) - this.transport.setRequestHeader(name, headers[name]); - }, - - success: function() { - var status = this.getStatus(); - return !status || (status >= 200 && status < 300) || status == 304; - }, - - getStatus: function() { - try { - if (this.transport.status === 1223) return 204; - return this.transport.status || 0; - } catch (e) { return 0 } - }, - - respondToReadyState: function(readyState) { - var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this); - - if (state == 'Complete') { - try { - this._complete = true; - (this.options['on' + response.status] - || this.options['on' + (this.success() ? 'Success' : 'Failure')] - || Prototype.emptyFunction)(response, response.headerJSON); - } catch (e) { - this.dispatchException(e); - } - - var contentType = response.getHeader('Content-type'); - if (this.options.evalJS == 'force' - || (this.options.evalJS && this.isSameOrigin() && contentType - && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) - this.evalResponse(); - } - - try { - (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON); - Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON); - } catch (e) { - this.dispatchException(e); - } - - if (state == 'Complete') { - this.transport.onreadystatechange = Prototype.emptyFunction; - } - }, - - isSameOrigin: function() { - var m = this.url.match(/^\s*https?:\/\/[^\/]*/); - return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({ - protocol: location.protocol, - domain: document.domain, - port: location.port ? ':' + location.port : '' - })); - }, - - getHeader: function(name) { - try { - return this.transport.getResponseHeader(name) || null; - } catch (e) { return null; } - }, - - evalResponse: function() { - try { - return eval((this.transport.responseText || '').unfilterJSON()); - } catch (e) { - this.dispatchException(e); - } - }, - - dispatchException: function(exception) { - (this.options.onException || Prototype.emptyFunction)(this, exception); - Ajax.Responders.dispatch('onException', this, exception); - } -}); - -Ajax.Request.Events = - ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; - - - - - - - - -Ajax.Response = Class.create({ - initialize: function(request){ - this.request = request; - var transport = this.transport = request.transport, - readyState = this.readyState = transport.readyState; - - if ((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) { - this.status = this.getStatus(); - this.statusText = this.getStatusText(); - this.responseText = String.interpret(transport.responseText); - this.headerJSON = this._getHeaderJSON(); - } - - if (readyState == 4) { - var xml = transport.responseXML; - this.responseXML = Object.isUndefined(xml) ? null : xml; - this.responseJSON = this._getResponseJSON(); - } - }, - - status: 0, - - statusText: '', - - getStatus: Ajax.Request.prototype.getStatus, - - getStatusText: function() { - try { - return this.transport.statusText || ''; - } catch (e) { return '' } - }, - - getHeader: Ajax.Request.prototype.getHeader, - - getAllHeaders: function() { - try { - return this.getAllResponseHeaders(); - } catch (e) { return null } - }, - - getResponseHeader: function(name) { - return this.transport.getResponseHeader(name); - }, - - getAllResponseHeaders: function() { - return this.transport.getAllResponseHeaders(); - }, - - _getHeaderJSON: function() { - var json = this.getHeader('X-JSON'); - if (!json) return null; - - try { - json = decodeURIComponent(escape(json)); - } catch(e) { - } - - try { - return json.evalJSON(this.request.options.sanitizeJSON || - !this.request.isSameOrigin()); - } catch (e) { - this.request.dispatchException(e); - } - }, - - _getResponseJSON: function() { - var options = this.request.options; - if (!options.evalJSON || (options.evalJSON != 'force' && - !(this.getHeader('Content-type') || '').include('application/json')) || - this.responseText.blank()) - return null; - try { - return this.responseText.evalJSON(options.sanitizeJSON || - !this.request.isSameOrigin()); - } catch (e) { - this.request.dispatchException(e); - } - } -}); - -Ajax.Updater = Class.create(Ajax.Request, { - initialize: function($super, container, url, options) { - this.container = { - success: (container.success || container), - failure: (container.failure || (container.success ? null : container)) - }; - - options = Object.clone(options); - var onComplete = options.onComplete; - options.onComplete = (function(response, json) { - this.updateContent(response.responseText); - if (Object.isFunction(onComplete)) onComplete(response, json); - }).bind(this); - - $super(url, options); - }, - - updateContent: function(responseText) { - var receiver = this.container[this.success() ? 'success' : 'failure'], - options = this.options; - - if (!options.evalScripts) responseText = responseText.stripScripts(); - - if (receiver = $(receiver)) { - if (options.insertion) { - if (Object.isString(options.insertion)) { - var insertion = { }; insertion[options.insertion] = responseText; - receiver.insert(insertion); - } - else options.insertion(receiver, responseText); - } - else receiver.update(responseText); - } - } -}); - -Ajax.PeriodicalUpdater = Class.create(Ajax.Base, { - initialize: function($super, container, url, options) { - $super(options); - this.onComplete = this.options.onComplete; - - this.frequency = (this.options.frequency || 2); - this.decay = (this.options.decay || 1); - - this.updater = { }; - this.container = container; - this.url = url; - - this.start(); - }, - - start: function() { - this.options.onComplete = this.updateComplete.bind(this); - this.onTimerEvent(); - }, - - stop: function() { - this.updater.options.onComplete = undefined; - clearTimeout(this.timer); - (this.onComplete || Prototype.emptyFunction).apply(this, arguments); - }, - - updateComplete: function(response) { - if (this.options.decay) { - this.decay = (response.responseText == this.lastText ? - this.decay * this.options.decay : 1); - - this.lastText = response.responseText; - } - this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency); - }, - - onTimerEvent: function() { - this.updater = new Ajax.Updater(this.container, this.url, this.options); - } -}); - -(function(GLOBAL) { - - var UNDEFINED; - var SLICE = Array.prototype.slice; - - var DIV = document.createElement('div'); - - - function $(element) { - if (arguments.length > 1) { - for (var i = 0, elements = [], length = arguments.length; i < length; i++) - elements.push($(arguments[i])); - return elements; - } - - if (Object.isString(element)) - element = document.getElementById(element); - return Element.extend(element); - } - - GLOBAL.$ = $; - - - if (!GLOBAL.Node) GLOBAL.Node = {}; - - if (!GLOBAL.Node.ELEMENT_NODE) { - Object.extend(GLOBAL.Node, { - ELEMENT_NODE: 1, - ATTRIBUTE_NODE: 2, - TEXT_NODE: 3, - CDATA_SECTION_NODE: 4, - ENTITY_REFERENCE_NODE: 5, - ENTITY_NODE: 6, - PROCESSING_INSTRUCTION_NODE: 7, - COMMENT_NODE: 8, - DOCUMENT_NODE: 9, - DOCUMENT_TYPE_NODE: 10, - DOCUMENT_FRAGMENT_NODE: 11, - NOTATION_NODE: 12 - }); - } - - var ELEMENT_CACHE = {}; - - function shouldUseCreationCache(tagName, attributes) { - if (tagName === 'select') return false; - if ('type' in attributes) return false; - return true; - } - - var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){ - try { - var el = document.createElement(''); - return el.tagName.toLowerCase() === 'input' && el.name === 'x'; - } - catch(err) { - return false; - } - })(); - - - var oldElement = GLOBAL.Element; - function Element(tagName, attributes) { - attributes = attributes || {}; - tagName = tagName.toLowerCase(); - - if (HAS_EXTENDED_CREATE_ELEMENT_SYNTAX && attributes.name) { - tagName = '<' + tagName + ' name="' + attributes.name + '">'; - delete attributes.name; - return Element.writeAttribute(document.createElement(tagName), attributes); - } - - if (!ELEMENT_CACHE[tagName]) - ELEMENT_CACHE[tagName] = Element.extend(document.createElement(tagName)); - - var node = shouldUseCreationCache(tagName, attributes) ? - ELEMENT_CACHE[tagName].cloneNode(false) : document.createElement(tagName); - - return Element.writeAttribute(node, attributes); - } - - GLOBAL.Element = Element; - - Object.extend(GLOBAL.Element, oldElement || {}); - if (oldElement) GLOBAL.Element.prototype = oldElement.prototype; - - Element.Methods = { ByTag: {}, Simulated: {} }; - - var methods = {}; - - var INSPECT_ATTRIBUTES = { id: 'id', className: 'class' }; - function inspect(element) { - element = $(element); - var result = '<' + element.tagName.toLowerCase(); - - var attribute, value; - for (var property in INSPECT_ATTRIBUTES) { - attribute = INSPECT_ATTRIBUTES[property]; - value = (element[property] || '').toString(); - if (value) result += ' ' + attribute + '=' + value.inspect(true); - } - - return result + '>'; - } - - methods.inspect = inspect; - - - function visible(element) { - return $(element).style.display !== 'none'; - } - - function toggle(element, bool) { - element = $(element); - if (Object.isUndefined(bool)) - bool = !Element.visible(element); - Element[bool ? 'show' : 'hide'](element); - - return element; - } - - function hide(element) { - element = $(element); - element.style.display = 'none'; - return element; - } - - function show(element) { - element = $(element); - element.style.display = ''; - return element; - } - - - Object.extend(methods, { - visible: visible, - toggle: toggle, - hide: hide, - show: show - }); - - - function remove(element) { - element = $(element); - element.parentNode.removeChild(element); - return element; - } - - var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){ - var el = document.createElement("select"), - isBuggy = true; - el.innerHTML = ""; - if (el.options && el.options[0]) { - isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION"; - } - el = null; - return isBuggy; - })(); - - var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){ - try { - var el = document.createElement("table"); - if (el && el.tBodies) { - el.innerHTML = "
"; - var isBuggy = typeof el.tBodies[0] == "undefined"; - el = null; - return isBuggy; - } - } catch (e) { - return true; - } - })(); - - var LINK_ELEMENT_INNERHTML_BUGGY = (function() { - try { - var el = document.createElement('div'); - el.innerHTML = ""; - var isBuggy = (el.childNodes.length === 0); - el = null; - return isBuggy; - } catch(e) { - return true; - } - })(); - - var ANY_INNERHTML_BUGGY = SELECT_ELEMENT_INNERHTML_BUGGY || - TABLE_ELEMENT_INNERHTML_BUGGY || LINK_ELEMENT_INNERHTML_BUGGY; - - var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () { - var s = document.createElement("script"), - isBuggy = false; - try { - s.appendChild(document.createTextNode("")); - isBuggy = !s.firstChild || - s.firstChild && s.firstChild.nodeType !== 3; - } catch (e) { - isBuggy = true; - } - s = null; - return isBuggy; - })(); - - function update(element, content) { - element = $(element); - - var descendants = element.getElementsByTagName('*'), - i = descendants.length; - while (i--) purgeElement(descendants[i]); - - if (content && content.toElement) - content = content.toElement(); - - if (Object.isElement(content)) - return element.update().insert(content); - - - content = Object.toHTML(content); - var tagName = element.tagName.toUpperCase(); - - if (tagName === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) { - element.text = content; - return element; - } - - if (ANY_INNERHTML_BUGGY) { - if (tagName in INSERTION_TRANSLATIONS.tags) { - while (element.firstChild) - element.removeChild(element.firstChild); - - var nodes = getContentFromAnonymousElement(tagName, content.stripScripts()); - for (var i = 0, node; node = nodes[i]; i++) - element.appendChild(node); - - } else if (LINK_ELEMENT_INNERHTML_BUGGY && Object.isString(content) && content.indexOf(' -1) { - while (element.firstChild) - element.removeChild(element.firstChild); - - var nodes = getContentFromAnonymousElement(tagName, - content.stripScripts(), true); - - for (var i = 0, node; node = nodes[i]; i++) - element.appendChild(node); - } else { - element.innerHTML = content.stripScripts(); - } - } else { - element.innerHTML = content.stripScripts(); - } - - content.evalScripts.bind(content).defer(); - return element; - } - - function replace(element, content) { - element = $(element); - - if (content && content.toElement) { - content = content.toElement(); - } else if (!Object.isElement(content)) { - content = Object.toHTML(content); - var range = element.ownerDocument.createRange(); - range.selectNode(element); - content.evalScripts.bind(content).defer(); - content = range.createContextualFragment(content.stripScripts()); - } - - element.parentNode.replaceChild(content, element); - return element; - } - - var INSERTION_TRANSLATIONS = { - before: function(element, node) { - element.parentNode.insertBefore(node, element); - }, - top: function(element, node) { - element.insertBefore(node, element.firstChild); - }, - bottom: function(element, node) { - element.appendChild(node); - }, - after: function(element, node) { - element.parentNode.insertBefore(node, element.nextSibling); - }, - - tags: { - TABLE: ['
test
', '
', 1], - TBODY: ['', '
', 2], - TR: ['', '
', 3], - TD: ['
', '
', 4], - SELECT: ['', 1] - } - }; - - var tags = INSERTION_TRANSLATIONS.tags; - - Object.extend(tags, { - THEAD: tags.TBODY, - TFOOT: tags.TBODY, - TH: tags.TD - }); - - function replace_IE(element, content) { - element = $(element); - if (content && content.toElement) - content = content.toElement(); - if (Object.isElement(content)) { - element.parentNode.replaceChild(content, element); - return element; - } - - content = Object.toHTML(content); - var parent = element.parentNode, tagName = parent.tagName.toUpperCase(); - - if (tagName in INSERTION_TRANSLATIONS.tags) { - var nextSibling = Element.next(element); - var fragments = getContentFromAnonymousElement( - tagName, content.stripScripts()); - - parent.removeChild(element); - - var iterator; - if (nextSibling) - iterator = function(node) { parent.insertBefore(node, nextSibling) }; - else - iterator = function(node) { parent.appendChild(node); } - - fragments.each(iterator); - } else { - element.outerHTML = content.stripScripts(); - } - - content.evalScripts.bind(content).defer(); - return element; - } - - if ('outerHTML' in document.documentElement) - replace = replace_IE; - - function isContent(content) { - if (Object.isUndefined(content) || content === null) return false; - - if (Object.isString(content) || Object.isNumber(content)) return true; - if (Object.isElement(content)) return true; - if (content.toElement || content.toHTML) return true; - - return false; - } - - function insertContentAt(element, content, position) { - position = position.toLowerCase(); - var method = INSERTION_TRANSLATIONS[position]; - - if (content && content.toElement) content = content.toElement(); - if (Object.isElement(content)) { - method(element, content); - return element; - } - - content = Object.toHTML(content); - var tagName = ((position === 'before' || position === 'after') ? - element.parentNode : element).tagName.toUpperCase(); - - var childNodes = getContentFromAnonymousElement(tagName, content.stripScripts()); - - if (position === 'top' || position === 'after') childNodes.reverse(); - - for (var i = 0, node; node = childNodes[i]; i++) - method(element, node); - - content.evalScripts.bind(content).defer(); - } - - function insert(element, insertions) { - element = $(element); - - if (isContent(insertions)) - insertions = { bottom: insertions }; - - for (var position in insertions) - insertContentAt(element, insertions[position], position); - - return element; - } - - function wrap(element, wrapper, attributes) { - element = $(element); - - if (Object.isElement(wrapper)) { - $(wrapper).writeAttribute(attributes || {}); - } else if (Object.isString(wrapper)) { - wrapper = new Element(wrapper, attributes); - } else { - wrapper = new Element('div', wrapper); - } - - if (element.parentNode) - element.parentNode.replaceChild(wrapper, element); - - wrapper.appendChild(element); - - return wrapper; - } - - function cleanWhitespace(element) { - element = $(element); - var node = element.firstChild; - - while (node) { - var nextNode = node.nextSibling; - if (node.nodeType === Node.TEXT_NODE && !/\S/.test(node.nodeValue)) - element.removeChild(node); - node = nextNode; - } - return element; - } - - function empty(element) { - return $(element).innerHTML.blank(); - } - - function getContentFromAnonymousElement(tagName, html, force) { - var t = INSERTION_TRANSLATIONS.tags[tagName], div = DIV; - - var workaround = !!t; - if (!workaround && force) { - workaround = true; - t = ['', '', 0]; - } - - if (workaround) { - div.innerHTML = ' ' + t[0] + html + t[1]; - div.removeChild(div.firstChild); - for (var i = t[2]; i--; ) - div = div.firstChild; - } else { - div.innerHTML = html; - } - - return $A(div.childNodes); - } - - function clone(element, deep) { - if (!(element = $(element))) return; - var clone = element.cloneNode(deep); - if (!HAS_UNIQUE_ID_PROPERTY) { - clone._prototypeUID = UNDEFINED; - if (deep) { - var descendants = Element.select(clone, '*'), - i = descendants.length; - while (i--) - descendants[i]._prototypeUID = UNDEFINED; - } - } - return Element.extend(clone); - } - - function purgeElement(element) { - var uid = getUniqueElementID(element); - if (uid) { - Element.stopObserving(element); - if (!HAS_UNIQUE_ID_PROPERTY) - element._prototypeUID = UNDEFINED; - delete Element.Storage[uid]; - } - } - - function purgeCollection(elements) { - var i = elements.length; - while (i--) - purgeElement(elements[i]); - } - - function purgeCollection_IE(elements) { - var i = elements.length, element, uid; - while (i--) { - element = elements[i]; - uid = getUniqueElementID(element); - delete Element.Storage[uid]; - delete Event.cache[uid]; - } - } - - if (HAS_UNIQUE_ID_PROPERTY) { - purgeCollection = purgeCollection_IE; - } - - - function purge(element) { - if (!(element = $(element))) return; - purgeElement(element); - - var descendants = element.getElementsByTagName('*'), - i = descendants.length; - - while (i--) purgeElement(descendants[i]); - - return null; - } - - Object.extend(methods, { - remove: remove, - update: update, - replace: replace, - insert: insert, - wrap: wrap, - cleanWhitespace: cleanWhitespace, - empty: empty, - clone: clone, - purge: purge - }); - - - - function recursivelyCollect(element, property, maximumLength) { - element = $(element); - maximumLength = maximumLength || -1; - var elements = []; - - while (element = element[property]) { - if (element.nodeType === Node.ELEMENT_NODE) - elements.push(Element.extend(element)); - - if (elements.length === maximumLength) break; - } - - return elements; - } - - - function ancestors(element) { - return recursivelyCollect(element, 'parentNode'); - } - - function descendants(element) { - return Element.select(element, '*'); - } - - function firstDescendant(element) { - element = $(element).firstChild; - while (element && element.nodeType !== Node.ELEMENT_NODE) - element = element.nextSibling; - - return $(element); - } - - function immediateDescendants(element) { - var results = [], child = $(element).firstChild; - - while (child) { - if (child.nodeType === Node.ELEMENT_NODE) - results.push(Element.extend(child)); - - child = child.nextSibling; - } - - return results; - } - - function previousSiblings(element) { - return recursivelyCollect(element, 'previousSibling'); - } - - function nextSiblings(element) { - return recursivelyCollect(element, 'nextSibling'); - } - - function siblings(element) { - element = $(element); - var previous = previousSiblings(element), - next = nextSiblings(element); - return previous.reverse().concat(next); - } - - function match(element, selector) { - element = $(element); - - if (Object.isString(selector)) - return Prototype.Selector.match(element, selector); - - return selector.match(element); - } - - - function _recursivelyFind(element, property, expression, index) { - element = $(element), expression = expression || 0, index = index || 0; - if (Object.isNumber(expression)) { - index = expression, expression = null; - } - - while (element = element[property]) { - if (element.nodeType !== 1) continue; - if (expression && !Prototype.Selector.match(element, expression)) - continue; - if (--index >= 0) continue; - - return Element.extend(element); - } - } - - - function up(element, expression, index) { - element = $(element); - - if (arguments.length === 1) return $(element.parentNode); - return _recursivelyFind(element, 'parentNode', expression, index); - } - - function down(element, expression, index) { - element = $(element), expression = expression || 0, index = index || 0; - - if (Object.isNumber(expression)) - index = expression, expression = '*'; - - var node = Prototype.Selector.select(expression, element)[index]; - return Element.extend(node); - } - - function previous(element, expression, index) { - return _recursivelyFind(element, 'previousSibling', expression, index); - } - - function next(element, expression, index) { - return _recursivelyFind(element, 'nextSibling', expression, index); - } - - function select(element) { - element = $(element); - var expressions = SLICE.call(arguments, 1).join(', '); - return Prototype.Selector.select(expressions, element); - } - - function adjacent(element) { - element = $(element); - var expressions = SLICE.call(arguments, 1).join(', '); - var siblings = Element.siblings(element), results = []; - for (var i = 0, sibling; sibling = siblings[i]; i++) { - if (Prototype.Selector.match(sibling, expressions)) - results.push(sibling); - } - - return results; - } - - function descendantOf_DOM(element, ancestor) { - element = $(element), ancestor = $(ancestor); - while (element = element.parentNode) - if (element === ancestor) return true; - return false; - } - - function descendantOf_contains(element, ancestor) { - element = $(element), ancestor = $(ancestor); - if (!ancestor.contains) return descendantOf_DOM(element, ancestor); - return ancestor.contains(element) && ancestor !== element; - } - - function descendantOf_compareDocumentPosition(element, ancestor) { - element = $(element), ancestor = $(ancestor); - return (element.compareDocumentPosition(ancestor) & 8) === 8; - } - - var descendantOf; - if (DIV.compareDocumentPosition) { - descendantOf = descendantOf_compareDocumentPosition; - } else if (DIV.contains) { - descendantOf = descendantOf_contains; - } else { - descendantOf = descendantOf_DOM; - } - - - Object.extend(methods, { - recursivelyCollect: recursivelyCollect, - ancestors: ancestors, - descendants: descendants, - firstDescendant: firstDescendant, - immediateDescendants: immediateDescendants, - previousSiblings: previousSiblings, - nextSiblings: nextSiblings, - siblings: siblings, - match: match, - up: up, - down: down, - previous: previous, - next: next, - select: select, - adjacent: adjacent, - descendantOf: descendantOf, - - getElementsBySelector: select, - - childElements: immediateDescendants - }); - - - var idCounter = 1; - function identify(element) { - element = $(element); - var id = Element.readAttribute(element, 'id'); - if (id) return id; - - do { id = 'anonymous_element_' + idCounter++ } while ($(id)); - - Element.writeAttribute(element, 'id', id); - return id; - } - - - function readAttribute(element, name) { - return $(element).getAttribute(name); - } - - function readAttribute_IE(element, name) { - element = $(element); - - var table = ATTRIBUTE_TRANSLATIONS.read; - if (table.values[name]) - return table.values[name](element, name); - - if (table.names[name]) name = table.names[name]; - - if (name.include(':')) { - if (!element.attributes || !element.attributes[name]) return null; - return element.attributes[name].value; - } - - return element.getAttribute(name); - } - - function readAttribute_Opera(element, name) { - if (name === 'title') return element.title; - return element.getAttribute(name); - } - - var PROBLEMATIC_ATTRIBUTE_READING = (function() { - DIV.setAttribute('onclick', Prototype.emptyFunction); - var value = DIV.getAttribute('onclick'); - var isFunction = (typeof value === 'function'); - DIV.removeAttribute('onclick'); - return isFunction; - })(); - - if (PROBLEMATIC_ATTRIBUTE_READING) { - readAttribute = readAttribute_IE; - } else if (Prototype.Browser.Opera) { - readAttribute = readAttribute_Opera; - } - - - function writeAttribute(element, name, value) { - element = $(element); - var attributes = {}, table = ATTRIBUTE_TRANSLATIONS.write; - - if (typeof name === 'object') { - attributes = name; - } else { - attributes[name] = Object.isUndefined(value) ? true : value; - } - - for (var attr in attributes) { - name = table.names[attr] || attr; - value = attributes[attr]; - if (table.values[attr]) - name = table.values[attr](element, value); - if (value === false || value === null) - element.removeAttribute(name); - else if (value === true) - element.setAttribute(name, name); - else element.setAttribute(name, value); - } - - return element; - } - - function hasAttribute(element, attribute) { - attribute = ATTRIBUTE_TRANSLATIONS.has[attribute] || attribute; - var node = $(element).getAttributeNode(attribute); - return !!(node && node.specified); - } - - GLOBAL.Element.Methods.Simulated.hasAttribute = hasAttribute; - - function classNames(element) { - return new Element.ClassNames(element); - } - - var regExpCache = {}; - function getRegExpForClassName(className) { - if (regExpCache[className]) return regExpCache[className]; - - var re = new RegExp("(^|\\s+)" + className + "(\\s+|$)"); - regExpCache[className] = re; - return re; - } - - function hasClassName(element, className) { - if (!(element = $(element))) return; - - var elementClassName = element.className; - - if (elementClassName.length === 0) return false; - if (elementClassName === className) return true; - - return getRegExpForClassName(className).test(elementClassName); - } - - function addClassName(element, className) { - if (!(element = $(element))) return; - - if (!hasClassName(element, className)) - element.className += (element.className ? ' ' : '') + className; - - return element; - } - - function removeClassName(element, className) { - if (!(element = $(element))) return; - - element.className = element.className.replace( - getRegExpForClassName(className), ' ').strip(); - - return element; - } - - function toggleClassName(element, className, bool) { - if (!(element = $(element))) return; - - if (Object.isUndefined(bool)) - bool = !hasClassName(element, className); - - var method = Element[bool ? 'addClassName' : 'removeClassName']; - return method(element, className); - } - - var ATTRIBUTE_TRANSLATIONS = {}; - - var classProp = 'className', forProp = 'for'; - - DIV.setAttribute(classProp, 'x'); - if (DIV.className !== 'x') { - DIV.setAttribute('class', 'x'); - if (DIV.className === 'x') - classProp = 'class'; - } - - var LABEL = document.createElement('label'); - LABEL.setAttribute(forProp, 'x'); - if (LABEL.htmlFor !== 'x') { - LABEL.setAttribute('htmlFor', 'x'); - if (LABEL.htmlFor === 'x') - forProp = 'htmlFor'; - } - LABEL = null; - - function _getAttr(element, attribute) { - return element.getAttribute(attribute); - } - - function _getAttr2(element, attribute) { - return element.getAttribute(attribute, 2); - } - - function _getAttrNode(element, attribute) { - var node = element.getAttributeNode(attribute); - return node ? node.value : ''; - } - - function _getFlag(element, attribute) { - return $(element).hasAttribute(attribute) ? attribute : null; - } - - DIV.onclick = Prototype.emptyFunction; - var onclickValue = DIV.getAttribute('onclick'); - - var _getEv; - - if (String(onclickValue).indexOf('{') > -1) { - _getEv = function(element, attribute) { - var value = element.getAttribute(attribute); - if (!value) return null; - value = value.toString(); - value = value.split('{')[1]; - value = value.split('}')[0]; - return value.strip(); - }; - } - else if (onclickValue === '') { - _getEv = function(element, attribute) { - var value = element.getAttribute(attribute); - if (!value) return null; - return value.strip(); - }; - } - - ATTRIBUTE_TRANSLATIONS.read = { - names: { - 'class': classProp, - 'className': classProp, - 'for': forProp, - 'htmlFor': forProp - }, - - values: { - style: function(element) { - return element.style.cssText.toLowerCase(); - }, - title: function(element) { - return element.title; - } - } - }; - - ATTRIBUTE_TRANSLATIONS.write = { - names: { - className: 'class', - htmlFor: 'for', - cellpadding: 'cellPadding', - cellspacing: 'cellSpacing' - }, - - values: { - checked: function(element, value) { - element.checked = !!value; - }, - - style: function(element, value) { - element.style.cssText = value ? value : ''; - } - } - }; - - ATTRIBUTE_TRANSLATIONS.has = { names: {} }; - - Object.extend(ATTRIBUTE_TRANSLATIONS.write.names, - ATTRIBUTE_TRANSLATIONS.read.names); - - var CAMEL_CASED_ATTRIBUTE_NAMES = $w('colSpan rowSpan vAlign dateTime ' + - 'accessKey tabIndex encType maxLength readOnly longDesc frameBorder'); - - for (var i = 0, attr; attr = CAMEL_CASED_ATTRIBUTE_NAMES[i]; i++) { - ATTRIBUTE_TRANSLATIONS.write.names[attr.toLowerCase()] = attr; - ATTRIBUTE_TRANSLATIONS.has.names[attr.toLowerCase()] = attr; - } - - Object.extend(ATTRIBUTE_TRANSLATIONS.read.values, { - href: _getAttr2, - src: _getAttr2, - type: _getAttr, - action: _getAttrNode, - disabled: _getFlag, - checked: _getFlag, - readonly: _getFlag, - multiple: _getFlag, - onload: _getEv, - onunload: _getEv, - onclick: _getEv, - ondblclick: _getEv, - onmousedown: _getEv, - onmouseup: _getEv, - onmouseover: _getEv, - onmousemove: _getEv, - onmouseout: _getEv, - onfocus: _getEv, - onblur: _getEv, - onkeypress: _getEv, - onkeydown: _getEv, - onkeyup: _getEv, - onsubmit: _getEv, - onreset: _getEv, - onselect: _getEv, - onchange: _getEv - }); - - - Object.extend(methods, { - identify: identify, - readAttribute: readAttribute, - writeAttribute: writeAttribute, - classNames: classNames, - hasClassName: hasClassName, - addClassName: addClassName, - removeClassName: removeClassName, - toggleClassName: toggleClassName - }); - - - function normalizeStyleName(style) { - if (style === 'float' || style === 'styleFloat') - return 'cssFloat'; - return style.camelize(); - } - - function normalizeStyleName_IE(style) { - if (style === 'float' || style === 'cssFloat') - return 'styleFloat'; - return style.camelize(); - } - - function setStyle(element, styles) { - element = $(element); - var elementStyle = element.style, match; - - if (Object.isString(styles)) { - elementStyle.cssText += ';' + styles; - if (styles.include('opacity')) { - var opacity = styles.match(/opacity:\s*(\d?\.?\d*)/)[1]; - Element.setOpacity(element, opacity); - } - return element; - } - - for (var property in styles) { - if (property === 'opacity') { - Element.setOpacity(element, styles[property]); - } else { - var value = styles[property]; - if (property === 'float' || property === 'cssFloat') { - property = Object.isUndefined(elementStyle.styleFloat) ? - 'cssFloat' : 'styleFloat'; - } - elementStyle[property] = value; - } - } - - return element; - } - - - function getStyle(element, style) { - element = $(element); - style = normalizeStyleName(style); - - var value = element.style[style]; - if (!value || value === 'auto') { - var css = document.defaultView.getComputedStyle(element, null); - value = css ? css[style] : null; - } - - if (style === 'opacity') return value ? parseFloat(value) : 1.0; - return value === 'auto' ? null : value; - } - - function getStyle_Opera(element, style) { - switch (style) { - case 'height': case 'width': - if (!Element.visible(element)) return null; - - var dim = parseInt(getStyle(element, style), 10); - - if (dim !== element['offset' + style.capitalize()]) - return dim + 'px'; - - return Element.measure(element, style); - - default: return getStyle(element, style); - } - } - - function getStyle_IE(element, style) { - element = $(element); - style = normalizeStyleName_IE(style); - - var value = element.style[style]; - if (!value && element.currentStyle) { - value = element.currentStyle[style]; - } - - if (style === 'opacity' && !STANDARD_CSS_OPACITY_SUPPORTED) - return getOpacity_IE(element); - - if (value === 'auto') { - if ((style === 'width' || style === 'height') && Element.visible(element)) - return Element.measure(element, style) + 'px'; - return null; - } - - return value; - } - - function stripAlphaFromFilter_IE(filter) { - return (filter || '').replace(/alpha\([^\)]*\)/gi, ''); - } - - function hasLayout_IE(element) { - if (!element.currentStyle.hasLayout) - element.style.zoom = 1; - return element; - } - - var STANDARD_CSS_OPACITY_SUPPORTED = (function() { - DIV.style.cssText = "opacity:.55"; - return /^0.55/.test(DIV.style.opacity); - })(); - - function setOpacity(element, value) { - element = $(element); - if (value == 1 || value === '') value = ''; - else if (value < 0.00001) value = 0; - element.style.opacity = value; - return element; - } - - function setOpacity_IE(element, value) { - if (STANDARD_CSS_OPACITY_SUPPORTED) - return setOpacity(element, value); - - element = hasLayout_IE($(element)); - var filter = Element.getStyle(element, 'filter'), - style = element.style; - - if (value == 1 || value === '') { - filter = stripAlphaFromFilter_IE(filter); - if (filter) style.filter = filter; - else style.removeAttribute('filter'); - return element; - } - - if (value < 0.00001) value = 0; - - style.filter = stripAlphaFromFilter_IE(filter) + - 'alpha(opacity=' + (value * 100) + ')'; - - return element; - } - - - function getOpacity(element) { - return Element.getStyle(element, 'opacity'); - } - - function getOpacity_IE(element) { - if (STANDARD_CSS_OPACITY_SUPPORTED) - return getOpacity(element); - - var filter = Element.getStyle(element, 'filter'); - if (filter.length === 0) return 1.0; - var match = (filter || '').match(/alpha\(opacity=(.*)\)/); - if (match[1]) return parseFloat(match[1]) / 100; - return 1.0; - } - - - Object.extend(methods, { - setStyle: setStyle, - getStyle: getStyle, - setOpacity: setOpacity, - getOpacity: getOpacity - }); - - if ('styleFloat' in DIV.style) { - methods.getStyle = getStyle_IE; - methods.setOpacity = setOpacity_IE; - methods.getOpacity = getOpacity_IE; - } - - var UID = 0; - - GLOBAL.Element.Storage = { UID: 1 }; - - function getUniqueElementID(element) { - if (element === window) return 0; - - if (typeof element._prototypeUID === 'undefined') - element._prototypeUID = Element.Storage.UID++; - return element._prototypeUID; - } - - function getUniqueElementID_IE(element) { - if (element === window) return 0; - if (element == document) return 1; - return element.uniqueID; - } - - var HAS_UNIQUE_ID_PROPERTY = ('uniqueID' in DIV); - if (HAS_UNIQUE_ID_PROPERTY) - getUniqueElementID = getUniqueElementID_IE; - - function getStorage(element) { - if (!(element = $(element))) return; - - var uid = getUniqueElementID(element); - - if (!Element.Storage[uid]) - Element.Storage[uid] = $H(); - - return Element.Storage[uid]; - } - - function store(element, key, value) { - if (!(element = $(element))) return; - var storage = getStorage(element); - if (arguments.length === 2) { - storage.update(key); - } else { - storage.set(key, value); - } - return element; - } - - function retrieve(element, key, defaultValue) { - if (!(element = $(element))) return; - var storage = getStorage(element), value = storage.get(key); - - if (Object.isUndefined(value)) { - storage.set(key, defaultValue); - value = defaultValue; - } - - return value; - } - - - Object.extend(methods, { - getStorage: getStorage, - store: store, - retrieve: retrieve - }); - - - var Methods = {}, ByTag = Element.Methods.ByTag, - F = Prototype.BrowserFeatures; - - if (!F.ElementExtensions && ('__proto__' in DIV)) { - GLOBAL.HTMLElement = {}; - GLOBAL.HTMLElement.prototype = DIV['__proto__']; - F.ElementExtensions = true; - } - - function checkElementPrototypeDeficiency(tagName) { - if (typeof window.Element === 'undefined') return false; - var proto = window.Element.prototype; - if (proto) { - var id = '_' + (Math.random() + '').slice(2), - el = document.createElement(tagName); - proto[id] = 'x'; - var isBuggy = (el[id] !== 'x'); - delete proto[id]; - el = null; - return isBuggy; - } - - return false; - } - - var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = - checkElementPrototypeDeficiency('object'); - - function extendElementWith(element, methods) { - for (var property in methods) { - var value = methods[property]; - if (Object.isFunction(value) && !(property in element)) - element[property] = value.methodize(); - } - } - - var EXTENDED = {}; - function elementIsExtended(element) { - var uid = getUniqueElementID(element); - return (uid in EXTENDED); - } - - function extend(element) { - if (!element || elementIsExtended(element)) return element; - if (element.nodeType !== Node.ELEMENT_NODE || element == window) - return element; - - var methods = Object.clone(Methods), - tagName = element.tagName.toUpperCase(); - - if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); - - extendElementWith(element, methods); - EXTENDED[getUniqueElementID(element)] = true; - return element; - } - - function extend_IE8(element) { - if (!element || elementIsExtended(element)) return element; - - var t = element.tagName; - if (t && (/^(?:object|applet|embed)$/i.test(t))) { - extendElementWith(element, Element.Methods); - extendElementWith(element, Element.Methods.Simulated); - extendElementWith(element, Element.Methods.ByTag[t.toUpperCase()]); - } - - return element; - } - - if (F.SpecificElementExtensions) { - extend = HTMLOBJECTELEMENT_PROTOTYPE_BUGGY ? extend_IE8 : Prototype.K; - } - - function addMethodsToTagName(tagName, methods) { - tagName = tagName.toUpperCase(); - if (!ByTag[tagName]) ByTag[tagName] = {}; - Object.extend(ByTag[tagName], methods); - } - - function mergeMethods(destination, methods, onlyIfAbsent) { - if (Object.isUndefined(onlyIfAbsent)) onlyIfAbsent = false; - for (var property in methods) { - var value = methods[property]; - if (!Object.isFunction(value)) continue; - if (!onlyIfAbsent || !(property in destination)) - destination[property] = value.methodize(); - } - } - - function findDOMClass(tagName) { - var klass; - var trans = { - "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph", - "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList", - "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading", - "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote", - "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION": - "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD": - "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR": - "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET": - "FrameSet", "IFRAME": "IFrame" - }; - if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element'; - if (window[klass]) return window[klass]; - klass = 'HTML' + tagName + 'Element'; - if (window[klass]) return window[klass]; - klass = 'HTML' + tagName.capitalize() + 'Element'; - if (window[klass]) return window[klass]; - - var element = document.createElement(tagName), - proto = element['__proto__'] || element.constructor.prototype; - - element = null; - return proto; - } - - function addMethods(methods) { - if (arguments.length === 0) addFormMethods(); - - if (arguments.length === 2) { - var tagName = methods; - methods = arguments[1]; - } - - if (!tagName) { - Object.extend(Element.Methods, methods || {}); - } else { - if (Object.isArray(tagName)) { - for (var i = 0, tag; tag = tagName[i]; i++) - addMethodsToTagName(tag, methods); - } else { - addMethodsToTagName(tagName, methods); - } - } - - var ELEMENT_PROTOTYPE = window.HTMLElement ? HTMLElement.prototype : - Element.prototype; - - if (F.ElementExtensions) { - mergeMethods(ELEMENT_PROTOTYPE, Element.Methods); - mergeMethods(ELEMENT_PROTOTYPE, Element.Methods.Simulated, true); - } - - if (F.SpecificElementExtensions) { - for (var tag in Element.Methods.ByTag) { - var klass = findDOMClass(tag); - if (Object.isUndefined(klass)) continue; - mergeMethods(klass.prototype, ByTag[tag]); - } - } - - Object.extend(Element, Element.Methods); - Object.extend(Element, Element.Methods.Simulated); - delete Element.ByTag; - delete Element.Simulated; - - Element.extend.refresh(); - - ELEMENT_CACHE = {}; - } - - Object.extend(GLOBAL.Element, { - extend: extend, - addMethods: addMethods - }); - - if (extend === Prototype.K) { - GLOBAL.Element.extend.refresh = Prototype.emptyFunction; - } else { - GLOBAL.Element.extend.refresh = function() { - if (Prototype.BrowserFeatures.ElementExtensions) return; - Object.extend(Methods, Element.Methods); - Object.extend(Methods, Element.Methods.Simulated); - - EXTENDED = {}; - }; - } - - function addFormMethods() { - Object.extend(Form, Form.Methods); - Object.extend(Form.Element, Form.Element.Methods); - Object.extend(Element.Methods.ByTag, { - "FORM": Object.clone(Form.Methods), - "INPUT": Object.clone(Form.Element.Methods), - "SELECT": Object.clone(Form.Element.Methods), - "TEXTAREA": Object.clone(Form.Element.Methods), - "BUTTON": Object.clone(Form.Element.Methods) - }); - } - - Element.addMethods(methods); - -})(this); -(function() { - - function toDecimal(pctString) { - var match = pctString.match(/^(\d+)%?$/i); - if (!match) return null; - return (Number(match[1]) / 100); - } - - function getRawStyle(element, style) { - element = $(element); - - var value = element.style[style]; - if (!value || value === 'auto') { - var css = document.defaultView.getComputedStyle(element, null); - value = css ? css[style] : null; - } - - if (style === 'opacity') return value ? parseFloat(value) : 1.0; - return value === 'auto' ? null : value; - } - - function getRawStyle_IE(element, style) { - var value = element.style[style]; - if (!value && element.currentStyle) { - value = element.currentStyle[style]; - } - return value; - } - - function getContentWidth(element, context) { - var boxWidth = element.offsetWidth; - - var bl = getPixelValue(element, 'borderLeftWidth', context) || 0; - var br = getPixelValue(element, 'borderRightWidth', context) || 0; - var pl = getPixelValue(element, 'paddingLeft', context) || 0; - var pr = getPixelValue(element, 'paddingRight', context) || 0; - - return boxWidth - bl - br - pl - pr; - } - - if ('currentStyle' in document.documentElement) { - getRawStyle = getRawStyle_IE; - } - - - function getPixelValue(value, property, context) { - var element = null; - if (Object.isElement(value)) { - element = value; - value = getRawStyle(element, property); - } - - if (value === null || Object.isUndefined(value)) { - return null; - } - - if ((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)) { - return window.parseFloat(value); - } - - var isPercentage = value.include('%'), isViewport = (context === document.viewport); - - if (/\d/.test(value) && element && element.runtimeStyle && !(isPercentage && isViewport)) { - var style = element.style.left, rStyle = element.runtimeStyle.left; - element.runtimeStyle.left = element.currentStyle.left; - element.style.left = value || 0; - value = element.style.pixelLeft; - element.style.left = style; - element.runtimeStyle.left = rStyle; - - return value; - } - - if (element && isPercentage) { - context = context || element.parentNode; - var decimal = toDecimal(value), whole = null; - - var isHorizontal = property.include('left') || property.include('right') || - property.include('width'); - - var isVertical = property.include('top') || property.include('bottom') || - property.include('height'); - - if (context === document.viewport) { - if (isHorizontal) { - whole = document.viewport.getWidth(); - } else if (isVertical) { - whole = document.viewport.getHeight(); - } - } else { - if (isHorizontal) { - whole = $(context).measure('width'); - } else if (isVertical) { - whole = $(context).measure('height'); - } - } - - return (whole === null) ? 0 : whole * decimal; - } - - return 0; - } - - function toCSSPixels(number) { - if (Object.isString(number) && number.endsWith('px')) - return number; - return number + 'px'; - } - - function isDisplayed(element) { - while (element && element.parentNode) { - var display = element.getStyle('display'); - if (display === 'none') { - return false; - } - element = $(element.parentNode); - } - return true; - } - - var hasLayout = Prototype.K; - if ('currentStyle' in document.documentElement) { - hasLayout = function(element) { - if (!element.currentStyle.hasLayout) { - element.style.zoom = 1; - } - return element; - }; - } - - function cssNameFor(key) { - if (key.include('border')) key = key + '-width'; - return key.camelize(); - } - - Element.Layout = Class.create(Hash, { - initialize: function($super, element, preCompute) { - $super(); - this.element = $(element); - - Element.Layout.PROPERTIES.each( function(property) { - this._set(property, null); - }, this); - - if (preCompute) { - this._preComputing = true; - this._begin(); - Element.Layout.PROPERTIES.each( this._compute, this ); - this._end(); - this._preComputing = false; - } - }, - - _set: function(property, value) { - return Hash.prototype.set.call(this, property, value); - }, - - set: function(property, value) { - throw "Properties of Element.Layout are read-only."; - }, - - get: function($super, property) { - var value = $super(property); - return value === null ? this._compute(property) : value; - }, - - _begin: function() { - if (this._isPrepared()) return; - - var element = this.element; - if (isDisplayed(element)) { - this._setPrepared(true); - return; - } - - - var originalStyles = { - position: element.style.position || '', - width: element.style.width || '', - visibility: element.style.visibility || '', - display: element.style.display || '' - }; - - element.store('prototype_original_styles', originalStyles); - - var position = getRawStyle(element, 'position'), width = element.offsetWidth; - - if (width === 0 || width === null) { - element.style.display = 'block'; - width = element.offsetWidth; - } - - var context = (position === 'fixed') ? document.viewport : - element.parentNode; - - var tempStyles = { - visibility: 'hidden', - display: 'block' - }; - - if (position !== 'fixed') tempStyles.position = 'absolute'; - - element.setStyle(tempStyles); - - var positionedWidth = element.offsetWidth, newWidth; - if (width && (positionedWidth === width)) { - newWidth = getContentWidth(element, context); - } else if (position === 'absolute' || position === 'fixed') { - newWidth = getContentWidth(element, context); - } else { - var parent = element.parentNode, pLayout = $(parent).getLayout(); - - newWidth = pLayout.get('width') - - this.get('margin-left') - - this.get('border-left') - - this.get('padding-left') - - this.get('padding-right') - - this.get('border-right') - - this.get('margin-right'); - } - - element.setStyle({ width: newWidth + 'px' }); - - this._setPrepared(true); - }, - - _end: function() { - var element = this.element; - var originalStyles = element.retrieve('prototype_original_styles'); - element.store('prototype_original_styles', null); - element.setStyle(originalStyles); - this._setPrepared(false); - }, - - _compute: function(property) { - var COMPUTATIONS = Element.Layout.COMPUTATIONS; - if (!(property in COMPUTATIONS)) { - throw "Property not found."; - } - - return this._set(property, COMPUTATIONS[property].call(this, this.element)); - }, - - _isPrepared: function() { - return this.element.retrieve('prototype_element_layout_prepared', false); - }, - - _setPrepared: function(bool) { - return this.element.store('prototype_element_layout_prepared', bool); - }, - - toObject: function() { - var args = $A(arguments); - var keys = (args.length === 0) ? Element.Layout.PROPERTIES : - args.join(' ').split(' '); - var obj = {}; - keys.each( function(key) { - if (!Element.Layout.PROPERTIES.include(key)) return; - var value = this.get(key); - if (value != null) obj[key] = value; - }, this); - return obj; - }, - - toHash: function() { - var obj = this.toObject.apply(this, arguments); - return new Hash(obj); - }, - - toCSS: function() { - var args = $A(arguments); - var keys = (args.length === 0) ? Element.Layout.PROPERTIES : - args.join(' ').split(' '); - var css = {}; - - keys.each( function(key) { - if (!Element.Layout.PROPERTIES.include(key)) return; - if (Element.Layout.COMPOSITE_PROPERTIES.include(key)) return; - - var value = this.get(key); - if (value != null) css[cssNameFor(key)] = value + 'px'; - }, this); - return css; - }, - - inspect: function() { - return "#"; - } - }); - - Object.extend(Element.Layout, { - PROPERTIES: $w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height'), - - COMPOSITE_PROPERTIES: $w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'), - - COMPUTATIONS: { - 'height': function(element) { - if (!this._preComputing) this._begin(); - - var bHeight = this.get('border-box-height'); - if (bHeight <= 0) { - if (!this._preComputing) this._end(); - return 0; - } - - var bTop = this.get('border-top'), - bBottom = this.get('border-bottom'); - - var pTop = this.get('padding-top'), - pBottom = this.get('padding-bottom'); - - if (!this._preComputing) this._end(); - - return bHeight - bTop - bBottom - pTop - pBottom; - }, - - 'width': function(element) { - if (!this._preComputing) this._begin(); - - var bWidth = this.get('border-box-width'); - if (bWidth <= 0) { - if (!this._preComputing) this._end(); - return 0; - } - - var bLeft = this.get('border-left'), - bRight = this.get('border-right'); - - var pLeft = this.get('padding-left'), - pRight = this.get('padding-right'); - - if (!this._preComputing) this._end(); - return bWidth - bLeft - bRight - pLeft - pRight; - }, - - 'padding-box-height': function(element) { - var height = this.get('height'), - pTop = this.get('padding-top'), - pBottom = this.get('padding-bottom'); - - return height + pTop + pBottom; - }, - - 'padding-box-width': function(element) { - var width = this.get('width'), - pLeft = this.get('padding-left'), - pRight = this.get('padding-right'); - - return width + pLeft + pRight; - }, - - 'border-box-height': function(element) { - if (!this._preComputing) this._begin(); - var height = element.offsetHeight; - if (!this._preComputing) this._end(); - return height; - }, - - 'border-box-width': function(element) { - if (!this._preComputing) this._begin(); - var width = element.offsetWidth; - if (!this._preComputing) this._end(); - return width; - }, - - 'margin-box-height': function(element) { - var bHeight = this.get('border-box-height'), - mTop = this.get('margin-top'), - mBottom = this.get('margin-bottom'); - - if (bHeight <= 0) return 0; - - return bHeight + mTop + mBottom; - }, - - 'margin-box-width': function(element) { - var bWidth = this.get('border-box-width'), - mLeft = this.get('margin-left'), - mRight = this.get('margin-right'); - - if (bWidth <= 0) return 0; - - return bWidth + mLeft + mRight; - }, - - 'top': function(element) { - var offset = element.positionedOffset(); - return offset.top; - }, - - 'bottom': function(element) { - var offset = element.positionedOffset(), - parent = element.getOffsetParent(), - pHeight = parent.measure('height'); - - var mHeight = this.get('border-box-height'); - - return pHeight - mHeight - offset.top; - }, - - 'left': function(element) { - var offset = element.positionedOffset(); - return offset.left; - }, - - 'right': function(element) { - var offset = element.positionedOffset(), - parent = element.getOffsetParent(), - pWidth = parent.measure('width'); - - var mWidth = this.get('border-box-width'); - - return pWidth - mWidth - offset.left; - }, - - 'padding-top': function(element) { - return getPixelValue(element, 'paddingTop'); - }, - - 'padding-bottom': function(element) { - return getPixelValue(element, 'paddingBottom'); - }, - - 'padding-left': function(element) { - return getPixelValue(element, 'paddingLeft'); - }, - - 'padding-right': function(element) { - return getPixelValue(element, 'paddingRight'); - }, - - 'border-top': function(element) { - return getPixelValue(element, 'borderTopWidth'); - }, - - 'border-bottom': function(element) { - return getPixelValue(element, 'borderBottomWidth'); - }, - - 'border-left': function(element) { - return getPixelValue(element, 'borderLeftWidth'); - }, - - 'border-right': function(element) { - return getPixelValue(element, 'borderRightWidth'); - }, - - 'margin-top': function(element) { - return getPixelValue(element, 'marginTop'); - }, - - 'margin-bottom': function(element) { - return getPixelValue(element, 'marginBottom'); - }, - - 'margin-left': function(element) { - return getPixelValue(element, 'marginLeft'); - }, - - 'margin-right': function(element) { - return getPixelValue(element, 'marginRight'); - } - } - }); - - if ('getBoundingClientRect' in document.documentElement) { - Object.extend(Element.Layout.COMPUTATIONS, { - 'right': function(element) { - var parent = hasLayout(element.getOffsetParent()); - var rect = element.getBoundingClientRect(), - pRect = parent.getBoundingClientRect(); - - return (pRect.right - rect.right).round(); - }, - - 'bottom': function(element) { - var parent = hasLayout(element.getOffsetParent()); - var rect = element.getBoundingClientRect(), - pRect = parent.getBoundingClientRect(); - - return (pRect.bottom - rect.bottom).round(); - } - }); - } - - Element.Offset = Class.create({ - initialize: function(left, top) { - this.left = left.round(); - this.top = top.round(); - - this[0] = this.left; - this[1] = this.top; - }, - - relativeTo: function(offset) { - return new Element.Offset( - this.left - offset.left, - this.top - offset.top - ); - }, - - inspect: function() { - return "#".interpolate(this); - }, - - toString: function() { - return "[#{left}, #{top}]".interpolate(this); - }, - - toArray: function() { - return [this.left, this.top]; - } - }); - - function getLayout(element, preCompute) { - return new Element.Layout(element, preCompute); - } - - function measure(element, property) { - return $(element).getLayout().get(property); - } - - function getHeight(element) { - return Element.getDimensions(element).height; - } - - function getWidth(element) { - return Element.getDimensions(element).width; - } - - function getDimensions(element) { - element = $(element); - var display = Element.getStyle(element, 'display'); - - if (display && display !== 'none') { - return { width: element.offsetWidth, height: element.offsetHeight }; - } - - var style = element.style; - var originalStyles = { - visibility: style.visibility, - position: style.position, - display: style.display - }; - - var newStyles = { - visibility: 'hidden', - display: 'block' - }; - - if (originalStyles.position !== 'fixed') - newStyles.position = 'absolute'; - - Element.setStyle(element, newStyles); - - var dimensions = { - width: element.offsetWidth, - height: element.offsetHeight - }; - - Element.setStyle(element, originalStyles); - - return dimensions; - } - - function getOffsetParent(element) { - element = $(element); - - if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) - return $(document.body); - - var isInline = (Element.getStyle(element, 'display') === 'inline'); - if (!isInline && element.offsetParent) return $(element.offsetParent); - - while ((element = element.parentNode) && element !== document.body) { - if (Element.getStyle(element, 'position') !== 'static') { - return isHtml(element) ? $(document.body) : $(element); - } - } - - return $(document.body); - } - - - function cumulativeOffset(element) { - element = $(element); - var valueT = 0, valueL = 0; - if (element.parentNode) { - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - } while (element); - } - return new Element.Offset(valueL, valueT); - } - - function positionedOffset(element) { - element = $(element); - - var layout = element.getLayout(); - - var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - if (element) { - if (isBody(element)) break; - var p = Element.getStyle(element, 'position'); - if (p !== 'static') break; - } - } while (element); - - valueL -= layout.get('margin-top'); - valueT -= layout.get('margin-left'); - - return new Element.Offset(valueL, valueT); - } - - function cumulativeScrollOffset(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.scrollTop || 0; - valueL += element.scrollLeft || 0; - element = element.parentNode; - } while (element); - return new Element.Offset(valueL, valueT); - } - - function viewportOffset(forElement) { - var valueT = 0, valueL = 0, docBody = document.body; - - var element = $(forElement); - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - if (element.offsetParent == docBody && - Element.getStyle(element, 'position') == 'absolute') break; - } while (element = element.offsetParent); - - element = forElement; - do { - if (element != docBody) { - valueT -= element.scrollTop || 0; - valueL -= element.scrollLeft || 0; - } - } while (element = element.parentNode); - return new Element.Offset(valueL, valueT); - } - - function absolutize(element) { - element = $(element); - - if (Element.getStyle(element, 'position') === 'absolute') { - return element; - } - - var offsetParent = getOffsetParent(element); - var eOffset = element.viewportOffset(), - pOffset = offsetParent.viewportOffset(); - - var offset = eOffset.relativeTo(pOffset); - var layout = element.getLayout(); - - element.store('prototype_absolutize_original_styles', { - left: element.getStyle('left'), - top: element.getStyle('top'), - width: element.getStyle('width'), - height: element.getStyle('height') - }); - - element.setStyle({ - position: 'absolute', - top: offset.top + 'px', - left: offset.left + 'px', - width: layout.get('width') + 'px', - height: layout.get('height') + 'px' - }); - - return element; - } - - function relativize(element) { - element = $(element); - if (Element.getStyle(element, 'position') === 'relative') { - return element; - } - - var originalStyles = - element.retrieve('prototype_absolutize_original_styles'); - - if (originalStyles) element.setStyle(originalStyles); - return element; - } - - - function scrollTo(element) { - element = $(element); - var pos = Element.cumulativeOffset(element); - window.scrollTo(pos.left, pos.top); - return element; - } - - - function makePositioned(element) { - element = $(element); - var position = Element.getStyle(element, 'position'), styles = {}; - if (position === 'static' || !position) { - styles.position = 'relative'; - if (Prototype.Browser.Opera) { - styles.top = 0; - styles.left = 0; - } - Element.setStyle(element, styles); - Element.store(element, 'prototype_made_positioned', true); - } - return element; - } - - function undoPositioned(element) { - element = $(element); - var storage = Element.getStorage(element), - madePositioned = storage.get('prototype_made_positioned'); - - if (madePositioned) { - storage.unset('prototype_made_positioned'); - Element.setStyle(element, { - position: '', - top: '', - bottom: '', - left: '', - right: '' - }); - } - return element; - } - - function makeClipping(element) { - element = $(element); - - var storage = Element.getStorage(element), - madeClipping = storage.get('prototype_made_clipping'); - - if (Object.isUndefined(madeClipping)) { - var overflow = Element.getStyle(element, 'overflow'); - storage.set('prototype_made_clipping', overflow); - if (overflow !== 'hidden') - element.style.overflow = 'hidden'; - } - - return element; - } - - function undoClipping(element) { - element = $(element); - var storage = Element.getStorage(element), - overflow = storage.get('prototype_made_clipping'); - - if (!Object.isUndefined(overflow)) { - storage.unset('prototype_made_clipping'); - element.style.overflow = overflow || ''; - } - - return element; - } - - function clonePosition(element, source, options) { - options = Object.extend({ - setLeft: true, - setTop: true, - setWidth: true, - setHeight: true, - offsetTop: 0, - offsetLeft: 0 - }, options || {}); - - source = $(source); - element = $(element); - var p, delta, layout, styles = {}; - - if (options.setLeft || options.setTop) { - p = Element.viewportOffset(source); - delta = [0, 0]; - if (Element.getStyle(element, 'position') === 'absolute') { - var parent = Element.getOffsetParent(element); - if (parent !== document.body) delta = Element.viewportOffset(parent); - } - } - - if (options.setWidth || options.setHeight) { - layout = Element.getLayout(source); - } - - if (options.setLeft) - styles.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; - if (options.setTop) - styles.top = (p[1] - delta[1] + options.offsetTop) + 'px'; - - if (options.setWidth) - styles.width = layout.get('border-box-width') + 'px'; - if (options.setHeight) - styles.height = layout.get('border-box-height') + 'px'; - - return Element.setStyle(element, styles); - } - - - if (Prototype.Browser.IE) { - getOffsetParent = getOffsetParent.wrap( - function(proceed, element) { - element = $(element); - - if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) - return $(document.body); - - var position = element.getStyle('position'); - if (position !== 'static') return proceed(element); - - element.setStyle({ position: 'relative' }); - var value = proceed(element); - element.setStyle({ position: position }); - return value; - } - ); - - positionedOffset = positionedOffset.wrap(function(proceed, element) { - element = $(element); - if (!element.parentNode) return new Element.Offset(0, 0); - var position = element.getStyle('position'); - if (position !== 'static') return proceed(element); - - var offsetParent = element.getOffsetParent(); - if (offsetParent && offsetParent.getStyle('position') === 'fixed') - hasLayout(offsetParent); - - element.setStyle({ position: 'relative' }); - var value = proceed(element); - element.setStyle({ position: position }); - return value; - }); - } else if (Prototype.Browser.Webkit) { - cumulativeOffset = function(element) { - element = $(element); - var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - if (element.offsetParent == document.body) { - if (Element.getStyle(element, 'position') == 'absolute') break; - } - - element = element.offsetParent; - } while (element); - - return new Element.Offset(valueL, valueT); - }; - } - - - Element.addMethods({ - getLayout: getLayout, - measure: measure, - getWidth: getWidth, - getHeight: getHeight, - getDimensions: getDimensions, - getOffsetParent: getOffsetParent, - cumulativeOffset: cumulativeOffset, - positionedOffset: positionedOffset, - cumulativeScrollOffset: cumulativeScrollOffset, - viewportOffset: viewportOffset, - absolutize: absolutize, - relativize: relativize, - scrollTo: scrollTo, - makePositioned: makePositioned, - undoPositioned: undoPositioned, - makeClipping: makeClipping, - undoClipping: undoClipping, - clonePosition: clonePosition - }); - - function isBody(element) { - return element.nodeName.toUpperCase() === 'BODY'; - } - - function isHtml(element) { - return element.nodeName.toUpperCase() === 'HTML'; - } - - function isDocument(element) { - return element.nodeType === Node.DOCUMENT_NODE; - } - - function isDetached(element) { - return element !== document.body && - !Element.descendantOf(element, document.body); - } - - if ('getBoundingClientRect' in document.documentElement) { - Element.addMethods({ - viewportOffset: function(element) { - element = $(element); - if (isDetached(element)) return new Element.Offset(0, 0); - - var rect = element.getBoundingClientRect(), - docEl = document.documentElement; - return new Element.Offset(rect.left - docEl.clientLeft, - rect.top - docEl.clientTop); - } - }); - } - - -})(); - -(function() { - - var IS_OLD_OPERA = Prototype.Browser.Opera && - (window.parseFloat(window.opera.version()) < 9.5); - var ROOT = null; - function getRootElement() { - if (ROOT) return ROOT; - ROOT = IS_OLD_OPERA ? document.body : document.documentElement; - return ROOT; - } - - function getDimensions() { - return { width: this.getWidth(), height: this.getHeight() }; - } - - function getWidth() { - return getRootElement().clientWidth; - } - - function getHeight() { - return getRootElement().clientHeight; - } - - function getScrollOffsets() { - var x = window.pageXOffset || document.documentElement.scrollLeft || - document.body.scrollLeft; - var y = window.pageYOffset || document.documentElement.scrollTop || - document.body.scrollTop; - - return new Element.Offset(x, y); - } - - document.viewport = { - getDimensions: getDimensions, - getWidth: getWidth, - getHeight: getHeight, - getScrollOffsets: getScrollOffsets - }; - -})(); -window.$$ = function() { - var expression = $A(arguments).join(', '); - return Prototype.Selector.select(expression, document); -}; - -Prototype.Selector = (function() { - - function select() { - throw new Error('Method "Prototype.Selector.select" must be defined.'); - } - - function match() { - throw new Error('Method "Prototype.Selector.match" must be defined.'); - } - - function find(elements, expression, index) { - index = index || 0; - var match = Prototype.Selector.match, length = elements.length, matchIndex = 0, i; - - for (i = 0; i < length; i++) { - if (match(elements[i], expression) && index == matchIndex++) { - return Element.extend(elements[i]); - } - } - } - - function extendElements(elements) { - for (var i = 0, length = elements.length; i < length; i++) { - Element.extend(elements[i]); - } - return elements; - } - - - var K = Prototype.K; - - return { - select: select, - match: match, - find: find, - extendElements: (Element.extend === K) ? K : extendElements, - extendElement: Element.extend - }; -})(); -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rNonWord = /\W/; - -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - - var origContext = context; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context ); - - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set ); - } - } - - } else { - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set; - - if ( !expr ) { - return []; - } - - for ( var i = 0, l = Expr.order.length; i < l; i++ ) { - var match, - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - var left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( var type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - var found, item, - filter = Expr.filter[ type ], - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( var i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - var pass = not ^ !!found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw "Syntax error, unrecognized expression: " + msg; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, - - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, - - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } - - match[0] = done++; - - return match; - }, - - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if ( !inplace ) { - result.push.apply( result, ret ); - } - - return false; - } - - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - - POS: function( match ) { - match.unshift( true ); - - return match; - } - }, - - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - var attr = elem.getAttribute( "type" ), type = elem.type; - return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); - }, - - radio: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - }, - - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } - - return true; - - } else { - Sizzle.error( name ); - } - }, - - CHILD: function( elem, match ) { - var type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - if ( type === "first" ) { - return true; - } - - node = elem; - - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - return true; - - case "nth": - var first = match[2], - last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - var doneName = match[0], - parent = elem.parentNode; - - if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { - var count = 0; - - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - - parent.sizcache = doneName; - } - - var diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; - -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - - } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - if ( aup === bup ) { - return siblingCheck( a, b ); - - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - -Sizzle.getText = function( elems ) { - var ret = "", elem; - - for ( var i = 0; elems[i]; i++ ) { - elem = elems[i]; - - if ( elem.nodeType === 3 || elem.nodeType === 4 ) { - ret += elem.nodeValue; - - } else if ( elem.nodeType !== 8 ) { - ret += Sizzle.getText( elem.childNodes ); - } - } - - return ret; -}; - -(function(){ - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - root.insertBefore( form, root.firstChild ); - - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - root = form = null; -})(); - -(function(){ - - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - } - - div.innerHTML = ""; - - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } - - div = null; -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

"; - - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - if ( !seed && !Sizzle.isXML(context) ) { - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); - } - } - - if ( context.nodeType === 9 ) { - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); - - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); - - if ( elem && elem.parentNode ) { - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); - } - - } else { - return makeArray( [], extra ); - } - } - - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} - - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - div = null; - })(); -} - -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; - - if ( matches ) { - var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), - pseudoWorks = false; - - try { - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function( node, expr ) { - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { - try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - var ret = matches.call( node, expr ); - - if ( ret || !disconnectedMatch || - node.document && node.document.nodeType !== 11 ) { - return ret; - } - } - } catch(e) {} - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
"; - - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet ); - } - - return Sizzle.filter( later, tmpSet ); -}; - - -window.Sizzle = Sizzle; - -})(); - -Prototype._original_property = window.Sizzle; - -;(function(engine) { - var extendElements = Prototype.Selector.extendElements; - - function select(selector, scope) { - return extendElements(engine(selector, scope || document)); - } - - function match(element, selector) { - return engine.matches(selector, [element]).length == 1; - } - - Prototype.Selector.engine = engine; - Prototype.Selector.select = select; - Prototype.Selector.match = match; -})(Sizzle); - -window.Sizzle = Prototype._original_property; -delete Prototype._original_property; - -var Form = { - reset: function(form) { - form = $(form); - form.reset(); - return form; - }, - - serializeElements: function(elements, options) { - if (typeof options != 'object') options = { hash: !!options }; - else if (Object.isUndefined(options.hash)) options.hash = true; - var key, value, submitted = false, submit = options.submit, accumulator, initial; - - if (options.hash) { - initial = {}; - accumulator = function(result, key, value) { - if (key in result) { - if (!Object.isArray(result[key])) result[key] = [result[key]]; - result[key].push(value); - } else result[key] = value; - return result; - }; - } else { - initial = ''; - accumulator = function(result, key, value) { - value = value.gsub(/(\r)?\n/, '\r\n'); - value = encodeURIComponent(value); - value = value.gsub(/%20/, '+'); - return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + value; - } - } - - return elements.inject(initial, function(result, element) { - if (!element.disabled && element.name) { - key = element.name; value = $(element).getValue(); - if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted && - submit !== false && (!submit || key == submit) && (submitted = true)))) { - result = accumulator(result, key, value); - } - } - return result; - }); - } -}; - -Form.Methods = { - serialize: function(form, options) { - return Form.serializeElements(Form.getElements(form), options); - }, - - - getElements: function(form) { - var elements = $(form).getElementsByTagName('*'); - var element, results = [], serializers = Form.Element.Serializers; - - for (var i = 0; element = elements[i]; i++) { - if (serializers[element.tagName.toLowerCase()]) - results.push(Element.extend(element)); - } - return results; - }, - - getInputs: function(form, typeName, name) { - form = $(form); - var inputs = form.getElementsByTagName('input'); - - if (!typeName && !name) return $A(inputs).map(Element.extend); - - for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { - var input = inputs[i]; - if ((typeName && input.type != typeName) || (name && input.name != name)) - continue; - matchingInputs.push(Element.extend(input)); - } - - return matchingInputs; - }, - - disable: function(form) { - form = $(form); - Form.getElements(form).invoke('disable'); - return form; - }, - - enable: function(form) { - form = $(form); - Form.getElements(form).invoke('enable'); - return form; - }, - - findFirstElement: function(form) { - var elements = $(form).getElements().findAll(function(element) { - return 'hidden' != element.type && !element.disabled; - }); - var firstByIndex = elements.findAll(function(element) { - return element.hasAttribute('tabIndex') && element.tabIndex >= 0; - }).sortBy(function(element) { return element.tabIndex }).first(); - - return firstByIndex ? firstByIndex : elements.find(function(element) { - return /^(?:input|select|textarea)$/i.test(element.tagName); - }); - }, - - focusFirstElement: function(form) { - form = $(form); - var element = form.findFirstElement(); - if (element) element.activate(); - return form; - }, - - request: function(form, options) { - form = $(form), options = Object.clone(options || { }); - - var params = options.parameters, action = form.readAttribute('action') || ''; - if (action.blank()) action = window.location.href; - options.parameters = form.serialize(true); - - if (params) { - if (Object.isString(params)) params = params.toQueryParams(); - Object.extend(options.parameters, params); - } - - if (form.hasAttribute('method') && !options.method) - options.method = form.method; - - return new Ajax.Request(action, options); - } -}; - -/*--------------------------------------------------------------------------*/ - - -Form.Element = { - focus: function(element) { - $(element).focus(); - return element; - }, - - select: function(element) { - $(element).select(); - return element; - } -}; - -Form.Element.Methods = { - - serialize: function(element) { - element = $(element); - if (!element.disabled && element.name) { - var value = element.getValue(); - if (value != undefined) { - var pair = { }; - pair[element.name] = value; - return Object.toQueryString(pair); - } - } - return ''; - }, - - getValue: function(element) { - element = $(element); - var method = element.tagName.toLowerCase(); - return Form.Element.Serializers[method](element); - }, - - setValue: function(element, value) { - element = $(element); - var method = element.tagName.toLowerCase(); - Form.Element.Serializers[method](element, value); - return element; - }, - - clear: function(element) { - $(element).value = ''; - return element; - }, - - present: function(element) { - return $(element).value != ''; - }, - - activate: function(element) { - element = $(element); - try { - element.focus(); - if (element.select && (element.tagName.toLowerCase() != 'input' || - !(/^(?:button|reset|submit)$/i.test(element.type)))) - element.select(); - } catch (e) { } - return element; - }, - - disable: function(element) { - element = $(element); - element.disabled = true; - return element; - }, - - enable: function(element) { - element = $(element); - element.disabled = false; - return element; - } -}; - -/*--------------------------------------------------------------------------*/ - -var Field = Form.Element; - -var $F = Form.Element.Methods.getValue; - -/*--------------------------------------------------------------------------*/ - -Form.Element.Serializers = (function() { - function input(element, value) { - switch (element.type.toLowerCase()) { - case 'checkbox': - case 'radio': - return inputSelector(element, value); - default: - return valueSelector(element, value); - } - } - - function inputSelector(element, value) { - if (Object.isUndefined(value)) - return element.checked ? element.value : null; - else element.checked = !!value; - } - - function valueSelector(element, value) { - if (Object.isUndefined(value)) return element.value; - else element.value = value; - } - - function select(element, value) { - if (Object.isUndefined(value)) - return (element.type === 'select-one' ? selectOne : selectMany)(element); - - var opt, currentValue, single = !Object.isArray(value); - for (var i = 0, length = element.length; i < length; i++) { - opt = element.options[i]; - currentValue = this.optionValue(opt); - if (single) { - if (currentValue == value) { - opt.selected = true; - return; - } - } - else opt.selected = value.include(currentValue); - } - } - - function selectOne(element) { - var index = element.selectedIndex; - return index >= 0 ? optionValue(element.options[index]) : null; - } - - function selectMany(element) { - var values, length = element.length; - if (!length) return null; - - for (var i = 0, values = []; i < length; i++) { - var opt = element.options[i]; - if (opt.selected) values.push(optionValue(opt)); - } - return values; - } - - function optionValue(opt) { - return Element.hasAttribute(opt, 'value') ? opt.value : opt.text; - } - - return { - input: input, - inputSelector: inputSelector, - textarea: valueSelector, - select: select, - selectOne: selectOne, - selectMany: selectMany, - optionValue: optionValue, - button: valueSelector - }; -})(); - -/*--------------------------------------------------------------------------*/ - - -Abstract.TimedObserver = Class.create(PeriodicalExecuter, { - initialize: function($super, element, frequency, callback) { - $super(callback, frequency); - this.element = $(element); - this.lastValue = this.getValue(); - }, - - execute: function() { - var value = this.getValue(); - if (Object.isString(this.lastValue) && Object.isString(value) ? - this.lastValue != value : String(this.lastValue) != String(value)) { - this.callback(this.element, value); - this.lastValue = value; - } - } -}); - -Form.Element.Observer = Class.create(Abstract.TimedObserver, { - getValue: function() { - return Form.Element.getValue(this.element); - } -}); - -Form.Observer = Class.create(Abstract.TimedObserver, { - getValue: function() { - return Form.serialize(this.element); - } -}); - -/*--------------------------------------------------------------------------*/ - -Abstract.EventObserver = Class.create({ - initialize: function(element, callback) { - this.element = $(element); - this.callback = callback; - - this.lastValue = this.getValue(); - if (this.element.tagName.toLowerCase() == 'form') - this.registerFormCallbacks(); - else - this.registerCallback(this.element); - }, - - onElementEvent: function() { - var value = this.getValue(); - if (this.lastValue != value) { - this.callback(this.element, value); - this.lastValue = value; - } - }, - - registerFormCallbacks: function() { - Form.getElements(this.element).each(this.registerCallback, this); - }, - - registerCallback: function(element) { - if (element.type) { - switch (element.type.toLowerCase()) { - case 'checkbox': - case 'radio': - Event.observe(element, 'click', this.onElementEvent.bind(this)); - break; - default: - Event.observe(element, 'change', this.onElementEvent.bind(this)); - break; - } - } - } -}); - -Form.Element.EventObserver = Class.create(Abstract.EventObserver, { - getValue: function() { - return Form.Element.getValue(this.element); - } -}); - -Form.EventObserver = Class.create(Abstract.EventObserver, { - getValue: function() { - return Form.serialize(this.element); - } -}); -(function(GLOBAL) { - var DIV = document.createElement('div'); - var docEl = document.documentElement; - var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl - && 'onmouseleave' in docEl; - - var Event = { - KEY_BACKSPACE: 8, - KEY_TAB: 9, - KEY_RETURN: 13, - KEY_ESC: 27, - KEY_LEFT: 37, - KEY_UP: 38, - KEY_RIGHT: 39, - KEY_DOWN: 40, - KEY_DELETE: 46, - KEY_HOME: 36, - KEY_END: 35, - KEY_PAGEUP: 33, - KEY_PAGEDOWN: 34, - KEY_INSERT: 45 - }; - - - var isIELegacyEvent = function(event) { return false; }; - - if (window.attachEvent) { - if (window.addEventListener) { - isIELegacyEvent = function(event) { - return !(event instanceof window.Event); - }; - } else { - isIELegacyEvent = function(event) { return true; }; - } - } - - var _isButton; - - function _isButtonForDOMEvents(event, code) { - return event.which ? (event.which === code + 1) : (event.button === code); - } - - var legacyButtonMap = { 0: 1, 1: 4, 2: 2 }; - function _isButtonForLegacyEvents(event, code) { - return event.button === legacyButtonMap[code]; - } - - function _isButtonForWebKit(event, code) { - switch (code) { - case 0: return event.which == 1 && !event.metaKey; - case 1: return event.which == 2 || (event.which == 1 && event.metaKey); - case 2: return event.which == 3; - default: return false; - } - } - - if (window.attachEvent) { - if (!window.addEventListener) { - _isButton = _isButtonForLegacyEvents; - } else { - _isButton = function(event, code) { - return isIELegacyEvent(event) ? _isButtonForLegacyEvents(event, code) : - _isButtonForDOMEvents(event, code); - } - } - } else if (Prototype.Browser.WebKit) { - _isButton = _isButtonForWebKit; - } else { - _isButton = _isButtonForDOMEvents; - } - - function isLeftClick(event) { return _isButton(event, 0) } - - function isMiddleClick(event) { return _isButton(event, 1) } - - function isRightClick(event) { return _isButton(event, 2) } - - function element(event) { - return Element.extend(_element(event)); - } - - function _element(event) { - event = Event.extend(event); - - var node = event.target, type = event.type, - currentTarget = event.currentTarget; - - if (currentTarget && currentTarget.tagName) { - if (type === 'load' || type === 'error' || - (type === 'click' && currentTarget.tagName.toLowerCase() === 'input' - && currentTarget.type === 'radio')) - node = currentTarget; - } - - if (node.nodeType == Node.TEXT_NODE) - node = node.parentNode; - - return Element.extend(node); - } - - function findElement(event, expression) { - var element = _element(event), match = Prototype.Selector.match; - if (!expression) return Element.extend(element); - while (element) { - if (Object.isElement(element) && match(element, expression)) - return Element.extend(element); - element = element.parentNode; - } - } - - function pointer(event) { - return { x: pointerX(event), y: pointerY(event) }; - } - - function pointerX(event) { - var docElement = document.documentElement, - body = document.body || { scrollLeft: 0 }; - - return event.pageX || (event.clientX + - (docElement.scrollLeft || body.scrollLeft) - - (docElement.clientLeft || 0)); - } - - function pointerY(event) { - var docElement = document.documentElement, - body = document.body || { scrollTop: 0 }; - - return event.pageY || (event.clientY + - (docElement.scrollTop || body.scrollTop) - - (docElement.clientTop || 0)); - } - - - function stop(event) { - Event.extend(event); - event.preventDefault(); - event.stopPropagation(); - - event.stopped = true; - } - - - Event.Methods = { - isLeftClick: isLeftClick, - isMiddleClick: isMiddleClick, - isRightClick: isRightClick, - - element: element, - findElement: findElement, - - pointer: pointer, - pointerX: pointerX, - pointerY: pointerY, - - stop: stop - }; - - var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { - m[name] = Event.Methods[name].methodize(); - return m; - }); - - if (window.attachEvent) { - function _relatedTarget(event) { - var element; - switch (event.type) { - case 'mouseover': - case 'mouseenter': - element = event.fromElement; - break; - case 'mouseout': - case 'mouseleave': - element = event.toElement; - break; - default: - return null; - } - return Element.extend(element); - } - - var additionalMethods = { - stopPropagation: function() { this.cancelBubble = true }, - preventDefault: function() { this.returnValue = false }, - inspect: function() { return '[object Event]' } - }; - - Event.extend = function(event, element) { - if (!event) return false; - - if (!isIELegacyEvent(event)) return event; - - if (event._extendedByPrototype) return event; - event._extendedByPrototype = Prototype.emptyFunction; - - var pointer = Event.pointer(event); - - Object.extend(event, { - target: event.srcElement || element, - relatedTarget: _relatedTarget(event), - pageX: pointer.x, - pageY: pointer.y - }); - - Object.extend(event, methods); - Object.extend(event, additionalMethods); - - return event; - }; - } else { - Event.extend = Prototype.K; - } - - if (window.addEventListener) { - Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__; - Object.extend(Event.prototype, methods); - } - - var EVENT_TRANSLATIONS = { - mouseenter: 'mouseover', - mouseleave: 'mouseout' - }; - - function getDOMEventName(eventName) { - return EVENT_TRANSLATIONS[eventName] || eventName; - } - - if (MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED) - getDOMEventName = Prototype.K; - - function getUniqueElementID(element) { - if (element === window) return 0; - - if (typeof element._prototypeUID === 'undefined') - element._prototypeUID = Element.Storage.UID++; - return element._prototypeUID; - } - - function getUniqueElementID_IE(element) { - if (element === window) return 0; - if (element == document) return 1; - return element.uniqueID; - } - - if ('uniqueID' in DIV) - getUniqueElementID = getUniqueElementID_IE; - - function isCustomEvent(eventName) { - return eventName.include(':'); - } - - Event._isCustomEvent = isCustomEvent; - - function getRegistryForElement(element, uid) { - var CACHE = GLOBAL.Event.cache; - if (Object.isUndefined(uid)) - uid = getUniqueElementID(element); - if (!CACHE[uid]) CACHE[uid] = { element: element }; - return CACHE[uid]; - } - - function destroyRegistryForElement(element, uid) { - if (Object.isUndefined(uid)) - uid = getUniqueElementID(element); - delete GLOBAL.Event.cache[uid]; - } - - - function register(element, eventName, handler) { - var registry = getRegistryForElement(element); - if (!registry[eventName]) registry[eventName] = []; - var entries = registry[eventName]; - - var i = entries.length; - while (i--) - if (entries[i].handler === handler) return null; - - var uid = getUniqueElementID(element); - var responder = GLOBAL.Event._createResponder(uid, eventName, handler); - var entry = { - responder: responder, - handler: handler - }; - - entries.push(entry); - return entry; - } - - function unregister(element, eventName, handler) { - var registry = getRegistryForElement(element); - var entries = registry[eventName]; - if (!entries) return; - - var i = entries.length, entry; - while (i--) { - if (entries[i].handler === handler) { - entry = entries[i]; - break; - } - } - - if (!entry) return; - - var index = entries.indexOf(entry); - entries.splice(index, 1); - - return entry; - } - - - function observe(element, eventName, handler) { - element = $(element); - var entry = register(element, eventName, handler); - - if (entry === null) return element; - - var responder = entry.responder; - if (isCustomEvent(eventName)) - observeCustomEvent(element, eventName, responder); - else - observeStandardEvent(element, eventName, responder); - - return element; - } - - function observeStandardEvent(element, eventName, responder) { - var actualEventName = getDOMEventName(eventName); - if (element.addEventListener) { - element.addEventListener(actualEventName, responder, false); - } else { - element.attachEvent('on' + actualEventName, responder); - } - } - - function observeCustomEvent(element, eventName, responder) { - if (element.addEventListener) { - element.addEventListener('dataavailable', responder, false); - } else { - element.attachEvent('ondataavailable', responder); - element.attachEvent('onlosecapture', responder); - } - } - - function stopObserving(element, eventName, handler) { - element = $(element); - var handlerGiven = !Object.isUndefined(handler), - eventNameGiven = !Object.isUndefined(eventName); - - if (!eventNameGiven && !handlerGiven) { - stopObservingElement(element); - return element; - } - - if (!handlerGiven) { - stopObservingEventName(element, eventName); - return element; - } - - var entry = unregister(element, eventName, handler); - - if (!entry) return element; - removeEvent(element, eventName, entry.responder); - return element; - } - - function stopObservingStandardEvent(element, eventName, responder) { - var actualEventName = getDOMEventName(eventName); - if (element.removeEventListener) { - element.removeEventListener(actualEventName, responder, false); - } else { - element.detachEvent('on' + actualEventName, responder); - } - } - - function stopObservingCustomEvent(element, eventName, responder) { - if (element.removeEventListener) { - element.removeEventListener('dataavailable', responder, false); - } else { - element.detachEvent('ondataavailable', responder); - element.detachEvent('onlosecapture', responder); - } - } - - - - function stopObservingElement(element) { - var uid = getUniqueElementID(element), - registry = getRegistryForElement(element, uid); - - destroyRegistryForElement(element, uid); - - var entries, i; - for (var eventName in registry) { - if (eventName === 'element') continue; - - entries = registry[eventName]; - i = entries.length; - while (i--) - removeEvent(element, eventName, entries[i].responder); - } - } - - function stopObservingEventName(element, eventName) { - var registry = getRegistryForElement(element); - var entries = registry[eventName]; - if (!entries) return; - delete registry[eventName]; - - var i = entries.length; - while (i--) - removeEvent(element, eventName, entries[i].responder); - } - - - function removeEvent(element, eventName, handler) { - if (isCustomEvent(eventName)) - stopObservingCustomEvent(element, eventName, handler); - else - stopObservingStandardEvent(element, eventName, handler); - } - - - - function getFireTarget(element) { - if (element !== document) return element; - if (document.createEvent && !element.dispatchEvent) - return document.documentElement; - return element; - } - - function fire(element, eventName, memo, bubble) { - element = getFireTarget($(element)); - if (Object.isUndefined(bubble)) bubble = true; - memo = memo || {}; - - var event = fireEvent(element, eventName, memo, bubble); - return Event.extend(event); - } - - function fireEvent_DOM(element, eventName, memo, bubble) { - var event = document.createEvent('HTMLEvents'); - event.initEvent('dataavailable', bubble, true); - - event.eventName = eventName; - event.memo = memo; - - element.dispatchEvent(event); - return event; - } - - function fireEvent_IE(element, eventName, memo, bubble) { - var event = document.createEventObject(); - event.eventType = bubble ? 'ondataavailable' : 'onlosecapture'; - - event.eventName = eventName; - event.memo = memo; - - element.fireEvent(event.eventType, event); - return event; - } - - var fireEvent = document.createEvent ? fireEvent_DOM : fireEvent_IE; - - - - Event.Handler = Class.create({ - initialize: function(element, eventName, selector, callback) { - this.element = $(element); - this.eventName = eventName; - this.selector = selector; - this.callback = callback; - this.handler = this.handleEvent.bind(this); - }, - - - start: function() { - Event.observe(this.element, this.eventName, this.handler); - return this; - }, - - stop: function() { - Event.stopObserving(this.element, this.eventName, this.handler); - return this; - }, - - handleEvent: function(event) { - var element = Event.findElement(event, this.selector); - if (element) this.callback.call(this.element, event, element); - } - }); - - function on(element, eventName, selector, callback) { - element = $(element); - if (Object.isFunction(selector) && Object.isUndefined(callback)) { - callback = selector, selector = null; - } - - return new Event.Handler(element, eventName, selector, callback).start(); - } - - Object.extend(Event, Event.Methods); - - Object.extend(Event, { - fire: fire, - observe: observe, - stopObserving: stopObserving, - on: on - }); - - Element.addMethods({ - fire: fire, - - observe: observe, - - stopObserving: stopObserving, - - on: on - }); - - Object.extend(document, { - fire: fire.methodize(), - - observe: observe.methodize(), - - stopObserving: stopObserving.methodize(), - - on: on.methodize(), - - loaded: false - }); - - if (GLOBAL.Event) Object.extend(window.Event, Event); - else GLOBAL.Event = Event; - - GLOBAL.Event.cache = {}; - - function destroyCache_IE() { - GLOBAL.Event.cache = null; - } - - if (window.attachEvent) - window.attachEvent('onunload', destroyCache_IE); - - DIV = null; - docEl = null; -})(this); - -(function(GLOBAL) { - /* Code for creating leak-free event responders is based on work by - John-David Dalton. */ - - var docEl = document.documentElement; - var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl - && 'onmouseleave' in docEl; - - function isSimulatedMouseEnterLeaveEvent(eventName) { - return !MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED && - (eventName === 'mouseenter' || eventName === 'mouseleave'); - } - - function createResponder(uid, eventName, handler) { - if (Event._isCustomEvent(eventName)) - return createResponderForCustomEvent(uid, eventName, handler); - if (isSimulatedMouseEnterLeaveEvent(eventName)) - return createMouseEnterLeaveResponder(uid, eventName, handler); - - return function(event) { - var cacheEntry = Event.cache[uid]; - var element = cacheEntry.element; - - Event.extend(event, element); - handler.call(element, event); - }; - } - - function createResponderForCustomEvent(uid, eventName, handler) { - return function(event) { - var cacheEntry = Event.cache[uid], element = cacheEntry.element; - - if (Object.isUndefined(event.eventName)) - return false; - - if (event.eventName !== eventName) - return false; - - Event.extend(event, element); - handler.call(element, event); - }; - } - - function createMouseEnterLeaveResponder(uid, eventName, handler) { - return function(event) { - var cacheEntry = Event.cache[uid], element = cacheEntry.element; - - Event.extend(event, element); - var parent = event.relatedTarget; - - while (parent && parent !== element) { - try { parent = parent.parentNode; } - catch(e) { parent = element; } - } - - if (parent === element) return; - handler.call(element, event); - } - } - - GLOBAL.Event._createResponder = createResponder; - docEl = null; -})(this); - -(function(GLOBAL) { - /* Support for the DOMContentLoaded event is based on work by Dan Webb, - Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */ - - var TIMER; - - function fireContentLoadedEvent() { - if (document.loaded) return; - if (TIMER) window.clearTimeout(TIMER); - document.loaded = true; - document.fire('dom:loaded'); - } - - function checkReadyState() { - if (document.readyState === 'complete') { - document.detachEvent('onreadystatechange', checkReadyState); - fireContentLoadedEvent(); - } - } - - function pollDoScroll() { - try { - document.documentElement.doScroll('left'); - } catch (e) { - TIMER = pollDoScroll.defer(); - return; - } - - fireContentLoadedEvent(); - } - - if (document.addEventListener) { - document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false); - } else { - document.attachEvent('onreadystatechange', checkReadyState); - if (window == top) TIMER = pollDoScroll.defer(); - } - - Event.observe(window, 'load', fireContentLoadedEvent); -})(this); - - -Element.addMethods(); -/*------------------------------- DEPRECATED -------------------------------*/ - -Hash.toQueryString = Object.toQueryString; - -var Toggle = { display: Element.toggle }; - -Element.Methods.childOf = Element.Methods.descendantOf; - -var Insertion = { - Before: function(element, content) { - return Element.insert(element, {before:content}); - }, - - Top: function(element, content) { - return Element.insert(element, {top:content}); - }, - - Bottom: function(element, content) { - return Element.insert(element, {bottom:content}); - }, - - After: function(element, content) { - return Element.insert(element, {after:content}); - } -}; - -var $continue = new Error('"throw $continue" is deprecated, use "return" instead'); - -var Position = { - includeScrollOffsets: false, - - prepare: function() { - this.deltaX = window.pageXOffset - || document.documentElement.scrollLeft - || document.body.scrollLeft - || 0; - this.deltaY = window.pageYOffset - || document.documentElement.scrollTop - || document.body.scrollTop - || 0; - }, - - within: function(element, x, y) { - if (this.includeScrollOffsets) - return this.withinIncludingScrolloffsets(element, x, y); - this.xcomp = x; - this.ycomp = y; - this.offset = Element.cumulativeOffset(element); - - return (y >= this.offset[1] && - y < this.offset[1] + element.offsetHeight && - x >= this.offset[0] && - x < this.offset[0] + element.offsetWidth); - }, - - withinIncludingScrolloffsets: function(element, x, y) { - var offsetcache = Element.cumulativeScrollOffset(element); - - this.xcomp = x + offsetcache[0] - this.deltaX; - this.ycomp = y + offsetcache[1] - this.deltaY; - this.offset = Element.cumulativeOffset(element); - - return (this.ycomp >= this.offset[1] && - this.ycomp < this.offset[1] + element.offsetHeight && - this.xcomp >= this.offset[0] && - this.xcomp < this.offset[0] + element.offsetWidth); - }, - - overlap: function(mode, element) { - if (!mode) return 0; - if (mode == 'vertical') - return ((this.offset[1] + element.offsetHeight) - this.ycomp) / - element.offsetHeight; - if (mode == 'horizontal') - return ((this.offset[0] + element.offsetWidth) - this.xcomp) / - element.offsetWidth; - }, - - - cumulativeOffset: Element.Methods.cumulativeOffset, - - positionedOffset: Element.Methods.positionedOffset, - - absolutize: function(element) { - Position.prepare(); - return Element.absolutize(element); - }, - - relativize: function(element) { - Position.prepare(); - return Element.relativize(element); - }, - - realOffset: Element.Methods.cumulativeScrollOffset, - - offsetParent: Element.Methods.getOffsetParent, - - page: Element.Methods.viewportOffset, - - clone: function(source, target, options) { - options = options || { }; - return Element.clonePosition(target, source, options); - } -}; - -/*--------------------------------------------------------------------------*/ - -if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){ - function iter(name) { - return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]"; - } - - instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ? - function(element, className) { - className = className.toString().strip(); - var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className); - return cond ? document._getElementsByXPath('.//*' + cond, element) : []; - } : function(element, className) { - className = className.toString().strip(); - var elements = [], classNames = (/\s/.test(className) ? $w(className) : null); - if (!classNames && !className) return elements; - - var nodes = $(element).getElementsByTagName('*'); - className = ' ' + className + ' '; - - for (var i = 0, child, cn; child = nodes[i]; i++) { - if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) || - (classNames && classNames.all(function(name) { - return !name.toString().blank() && cn.include(' ' + name + ' '); - })))) - elements.push(Element.extend(child)); - } - return elements; - }; - - return function(className, parentElement) { - return $(parentElement || document.body).getElementsByClassName(className); - }; -}(Element.Methods); - -/*--------------------------------------------------------------------------*/ - -Element.ClassNames = Class.create(); -Element.ClassNames.prototype = { - initialize: function(element) { - this.element = $(element); - }, - - _each: function(iterator, context) { - this.element.className.split(/\s+/).select(function(name) { - return name.length > 0; - })._each(iterator, context); - }, - - set: function(className) { - this.element.className = className; - }, - - add: function(classNameToAdd) { - if (this.include(classNameToAdd)) return; - this.set($A(this).concat(classNameToAdd).join(' ')); - }, - - remove: function(classNameToRemove) { - if (!this.include(classNameToRemove)) return; - this.set($A(this).without(classNameToRemove).join(' ')); - }, - - toString: function() { - return $A(this).join(' '); - } -}; - -Object.extend(Element.ClassNames.prototype, Enumerable); - -/*--------------------------------------------------------------------------*/ - -(function() { - window.Selector = Class.create({ - initialize: function(expression) { - this.expression = expression.strip(); - }, - - findElements: function(rootElement) { - return Prototype.Selector.select(this.expression, rootElement); - }, - - match: function(element) { - return Prototype.Selector.match(element, this.expression); - }, - - toString: function() { - return this.expression; - }, - - inspect: function() { - return "#"; - } - }); - - Object.extend(Selector, { - matchElements: function(elements, expression) { - var match = Prototype.Selector.match, - results = []; - - for (var i = 0, length = elements.length; i < length; i++) { - var element = elements[i]; - if (match(element, expression)) { - results.push(Element.extend(element)); - } - } - return results; - }, - - findElement: function(elements, expression, index) { - index = index || 0; - var matchIndex = 0, element; - for (var i = 0, length = elements.length; i < length; i++) { - element = elements[i]; - if (Prototype.Selector.match(element, expression) && index === matchIndex++) { - return Element.extend(element); - } - } - }, - - findChildElements: function(element, expressions) { - var selector = expressions.toArray().join(', '); - return Prototype.Selector.select(selector, element || document); - } - }); -})(); \ No newline at end of file diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/tests/lib/right.js b/extension/sandbox/chrome-extensions-samples/apps/samples/clock/tests/lib/right.js deleted file mode 100644 index 52c7b47..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/clock/tests/lib/right.js +++ /dev/null @@ -1,7 +0,0 @@ -/** - * RightJS v2.3.1 - http://rightjs.org - * Released under the terms of MIT license - * - * Copyright (C) 2008-2012 Nikolay Nemshilov - */ -var RightJS=function(a,b,c,d,e,f,g,h,i){function cL(a,b,c,d){var e={},f=a.marginLeft.toFloat()||0,g=a.marginTop.toFloat()||0,h=c==="right",i=c==="bottom",j=c==="top"||i;d==="out"?(e[j?"height":"width"]="0px",h?e.marginLeft=f+b.x+"px":i&&(e.marginTop=g+b.y+"px")):(j?(e.height=b.y+"px",a.height="0px"):(e.width=b.x+"px",a.width="0px"),h?(e.marginLeft=f+"px",a.marginLeft=f+b.x+"px"):i&&(e.marginTop=g+"px",a.marginTop=g+b.y+"px"));return e}function cK(a,b,c){var d=a.clone().setStyle("position:absolute;z-index:-1;visibility:hidden").setWidth(a.size().x).setStyle(b),e;a.parent()&&a.insert(d,"before"),e=cJ(d,c),d.remove();return e}function cJ(a,b){var c=0,d=b.length,e=a.computedStyles(),f={},g;for(;c"+b+""+e[1];while(f--!==0)d=d.firstChild;b=d.childNodes;while(b.length!==0)bO.appendChild(b[0])}else for(var g=0,h=b.length,i;gb?1:a-1;c--)if(a.call(b,this[c],c,this))return this[c];return i};d.include({indexOf:k.indexOf||function(a,b){for(var c=b<0?h.max(0,this.length+b):b||0,d=this.length;c-1;b--)if(this[b]===a)return b;return-1},first:function(){return arguments.length?_(X,this,arguments):this[0]},last:function(){return arguments.length?_(Y,this,arguments):this[this.length-1]},random:function(){return this.length===0?i:this[h.random(this.length-1)]},size:function(){return this.length},clean:function(){this.length=0;return this},empty:function(){return this.length===0},clone:function(){return this.slice(0)},each:function(){_(R,this,arguments);return this},forEach:R,map:function(){return _(U,this,arguments)},filter:function(){return _(S,this,arguments)},reject:function(){return _(T,this,arguments)},some:function(a){return _(V,this,a?arguments:[ba])},every:function(a){return _(W,this,a?arguments:[ba])},walk:function(){this.map.apply(this,arguments).forEach(function(a,b){this[b]=a},this);return this},merge:function(){for(var a=this.clone(),b,c=0;c0;b=h.random(d-1),c=a[--d],a[d]=a[b],a[b]=c){}return a},sort:function(a){return Q.apply(this,a||!z(this[0])?arguments:[bb])},sortBy:function(){var a=Z(arguments,this);return this.sort(function(b,c){return bb(a[0].call(a[1],b),a[0].call(a[1],c))})},min:function(){return h.min.apply(h,this)},max:function(){return h.max.apply(h,this)},sum:function(){for(var a=0,b=0,c=this.length;b]+>/ig,"")},stripScripts:function(a){var b="",c=this.replace(/]*>([\s\S]*?)<\/script>/img,function(a,c){b+=c+"\n";return""});a===!0?t(b):x(a)&&a(b,c);return c},extractScripts:function(){var a="";this.stripScripts(function(b){a=b});return a},evalScripts:function(){this.stripScripts(!0);return this},camelize:function(){return this.replace(/(\-|_)+(.)?/g,function(a,b,c){return c?c.toUpperCase():""})},underscored:function(){return this.replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/\-/g,"_").toLowerCase()},capitalize:function(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase()},dasherize:function(){return this.underscored().replace(/_/g,"-")},includes:function(a){return this.indexOf(a)!=-1},startsWith:function(a,b){return(b!==!0?this.indexOf(a):this.toLowerCase().indexOf(a.toLowerCase()))===0},endsWith:function(a,b){return this.length-(b!==!0?this.lastIndexOf(a):this.toLowerCase().lastIndexOf(a.toLowerCase()))===a.length},toInt:function(a){return parseInt(this,a===i?10:a)},toFloat:function(a){return parseFloat(a===!0?this:this.replace(",",".").replace(/(\d)-(\d)/,"$1.$2"))}}),e.prototype.include=e.prototype.includes,f.include({bind:function(){var a=J(arguments),b=a.shift(),c=this;return function(){return c.apply(b,a.length!==0||arguments.length!==0?a.concat(J(arguments)):a)}},bindAsEventListener:function(){var a=J(arguments),b=a.shift(),c=this;return function(d){return c.apply(b,[d].concat(a).concat(J(arguments)))}},curry:function(){return this.bind.apply(this,[this].concat(J(arguments)))},rcurry:function(){var a=J(arguments),b=this;return function(){return b.apply(b,J(arguments).concat(a))}},delay:function(){var a=J(arguments),b=a.shift(),c=new g(setTimeout(this.bind.apply(this,[this].concat(a)),b));c.cancel=function(){clearTimeout(this)};return c},periodical:function(){var a=J(arguments),b=a.shift(),c=new g(setInterval(this.bind.apply(this,[this].concat(a)),b));c.stop=function(){clearInterval(this)};return c},chain:function(){var a=J(arguments),b=a.shift(),c=this;return function(){var d=c.apply(c,arguments);b.apply(b,a);return d}}}),g.include({times:function(a,b){for(var c=0;c=a;d--)b.call(c,d);return this},to:function(a,b,c){var d=this+0,e=a,f=[],g=d;b=b||function(a){return a};if(e>d)for(;g<=e;g++)f.push(b.call(c,g));else for(;g>=e;g--)f.push(b.call(c,g));return f},abs:function(){return h.abs(this)},round:function(a){return a?parseFloat(this.toFixed(a)):h.round(this)},ceil:function(){return h.ceil(this)},floor:function(){return h.floor(this)},min:function(a){return thisa?a:this+0}}),RegExp.escape=function(a){return(""+a).replace(/([.*+?\^=!:${}()|\[\]\/\\])/g,"\\$1")},a.JSON||(a.JSON=function(){function g(a){return(a<10?"0":"")+a}function d(a){return a.replace(c,function(a){return b[a]||"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}var a=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,b={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},c=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;return{stringify:function(a){switch(typeof a){case"boolean":return e(a);case"number":return e(a+0);case"string":return'"'+d(a)+'"';case"object":if(a===null)return"null";if(B(a))return"["+J(a).map(JSON.stringify).join(",")+"]";if(m.call(a)==="[object Date]")return'"'+a.getUTCFullYear()+"-"+g(a.getUTCMonth()+1)+"-"+g(a.getUTCDate())+"T"+g(a.getUTCHours())+":"+g(a.getUTCMinutes())+":"+g(a.getUTCSeconds())+"."+g(a.getMilliseconds())+'Z"';var b=[],c;for(c in a)b.push('"'+c+'":'+JSON.stringify(a[c]));return"{"+b.join(",")+"}"}},parse:function(b){if(y(b)&&b){b=b.replace(a,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)});if(/^[\],:{}\s]*$/.test(b.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return(new f("return "+b))()}throw"JSON parse error: "+b}}}());var bc=j.Class=function(){var a=J(arguments).slice(0,2),b=a.pop()||{},c=a.pop(),d=arguments[2],e=function(){};!a.length&&!A(b)&&(c=b,b={}),!d&&c&&(c===bw||c.ancestors.include(bw))&&(d=bx()),d=s(d||function(){bi(this);return"initialize"in this?this.initialize.apply(this,arguments):this},bd),c=c||bc,e.prototype=c.prototype,d.prototype=new e,d.parent=c,d.prototype.constructor=d,d.ancestors=[];while(c)d.ancestors.push(c),c=c.parent;["extend","include"].each(function(a){a in b&&d[a].apply(d,N(b[a]))});return d.include(b)},bd={extend:function(){J(arguments).filter(A).each(function(a){s(this,bf(a,!0)),bg(this,a,!0)},this);return this},include:function(){var a=[this].concat(this.ancestors);J(arguments).filter(A).each(function(b){c.each(bf(b,!1),function(b,c){for(var d,e=0,f=a.length;e"),bs.OLD=bs.IE8L=bt=!0}catch(bv){}var bw=j.Wrapper=new bc({_:i,initialize:function(a){this._=a}});bw.Cache=q,bw.Cast=function(a){return a.tagName in bH?bH[a.tagName]:i};var bB=j.Document=new bc(bw,{win:function(){return bA(this._.defaultView||this._.parentWindow)}}),bC=bA(b),bD=j.Window=new bc(bw,{win:function(){return this},size:function(){var a=this._,b=a.document.documentElement;return a.innerWidth?{x:a.innerWidth,y:a.innerHeight}:{x:b.clientWidth,y:b.clientHeight}},scrolls:function(){var a=this._,b=a.document,c=b.body,d=b.documentElement;return a.pageXOffset||a.pageYOffset?{x:a.pageXOffset,y:a.pageYOffset}:c&&(c.scrollLeft||c.scrollTop)?{x:c.scrollLeft,y:c.scrollTop}:{x:d.scrollLeft,y:d.scrollTop}},scrollTo:function(a,b,c){var d=a,e=b,f=z(a)?null:E(a);f instanceof bG&&(a=f.position()),A(a)&&(e=a.y,d=a.x),A(c=c||b)&&j.Fx?(new cg.Scroll(this,c)).start({x:d,y:e}):this._.scrollTo(d,e);return this}}),bE=j.Event=new bc(bw,{type:null,which:null,keyCode:null,target:null,currentTarget:null,relatedTarget:null,pageX:null,pageY:null,initialize:bz,stopPropagation:function(){this._.stopPropagation?this._.stopPropagation():this._.cancelBubble=!0,this.stopped=!0;return this},preventDefault:function(){this._.preventDefault?this._.preventDefault():this._.returnValue=!1;return this},stop:function(){return this.stopPropagation().preventDefault()},position:function(){return{x:this.pageX,y:this.pageY}},offset:function(){if(this.target instanceof bG){var a=this.target.position();return{x:this.pageX-a.x,y:this.pageY-a.y}}return null},find:function(a){if(this.target instanceof bw&&this.currentTarget instanceof bw){var b=this.target._,c=this.currentTarget.find(a,!0);while(b){if(c.indexOf(b)!==-1)return bA(b);b=b.parentNode}}return i}},bz),bF=[],bG=j.Element=new bc(bw,{initialize:function(a,b){bK(this,a,b)}},by),bH=bG.Wrappers={},bI={},bJ=function(a,c){return(a in bI?bI[a]:bI[a]=b.createElement(a)).cloneNode(!1)};bt&&(bJ=function(a,c){c!==i&&(a==="input"||a==="button")&&(a="<"+a+' name="'+c.name+'" type="'+c.type+'"'+(c.checked?" checked":"")+" />",delete c.name,delete c.type);return b.createElement(a)}),bG.include({parent:function(a){var b=this._.parentNode,c=b&&b.nodeType;return a?this.parents(a)[0]:c===1||c===9?bA(b):null},parents:function(a){return bL(this,"parentNode",a)},children:function(a){return this.find(a).filter(function(a){return a._.parentNode===this._},this)},siblings:function(a){return this.prevSiblings(a).reverse().concat(this.nextSiblings(a))},nextSiblings:function(a){return bL(this,"nextSibling",a)},prevSiblings:function(a){return bL(this,"previousSibling",a)},next:function(a){return!a&&this._.nextElementSibling!==i?bA(this._.nextElementSibling):this.nextSiblings(a)[0]},prev:function(a){return!a&&this._.previousElementSibling!==i?bA(this._.previousElementSibling):this.prevSiblings(a)[0]},remove:function(){var a=this._,b=a.parentNode;b&&b.removeChild(a);return this},insert:function(a,b){var c=null,d=this._;b=b===i?"bottom":b,typeof a!=="object"?c=a=""+a:a instanceof bG&&(a=a._),bM[b](d,a.nodeType===i?bQ(b==="bottom"||b==="top"?d:d.parentNode,a):a),c!==null&&c.evalScripts();return this},insertTo:function(a,b){E(a).insert(this,b);return this},append:function(a){return this.insert(y(a)?J(arguments).join(""):arguments)},update:function(a){if(typeof a!=="object"){a=""+a;try{this._.innerHTML=a}catch(b){return this.clean().insert(a)}a.evalScripts();return this}return this.clean().insert(a)},html:function(a){return a===i?this._.innerHTML:this.update(a)},text:function(a){return a===i?this._.textContent===i?this._.innerText:this._.textContent:this.update(this.doc()._.createTextNode(a))},replace:function(a){return this.insert(a,"instead")},wrap:function(a){var b=this._,c=b.parentNode;c&&(a=E(a)._,c.replaceChild(a,b),a.appendChild(b));return this},clean:function(){while(this._.firstChild)this._.removeChild(this._.firstChild);return this},empty:function(){return this.html().blank()},clone:function(){return new bG(this._.cloneNode(!0))},index:function(){var a=this._,b=a.parentNode.firstChild,c=0;while(b!==a)b.nodeType===1&&c++,b=b.nextSibling;return c}});var bM={bottom:function(a,b){a.appendChild(b)},top:function(a,b){a.firstChild!==null?a.insertBefore(b,a.firstChild):a.appendChild(b)},after:function(a,b){var c=a.parentNode,d=a.nextSibling;d!==null?c.insertBefore(b,d):c.appendChild(b)},before:function(a,b){a.parentNode.insertBefore(b,a)},instead:function(a,b){a.parentNode.replaceChild(b,a)}},bN={TBODY:["","
",2],TR:["","
",3],TD:["","
",4],COL:["","
",2],LEGEND:["
","
",2],AREA:["","",2],OPTION:["",2]};v(bN,{OPTGROUP:"OPTION",THEAD:"TBODY",TFOOT:"TBODY",TH:"TD"});var bO=b.createDocumentFragment(),bP=b.createElement("DIV");bG.include({setStyle:function(a,b){var c,d,e={},f=this._.style;b!==i?(e[a]=b,a=e):y(a)&&(a.split(";").each(function(a){var b=a.split(":").map("trim");b[0]&&b[1]&&(e[b[0]]=b[1])}),a=e);for(c in a)d=c.indexOf("-")<0?c:c.camelize(),bu&&c==="opacity"?f.filter="alpha(opacity="+a[c]*100+")":c==="float"&&(d=br?"styleFloat":"cssFloat"),f[d]=a[c];return this},getStyle:function(a){return bR(this._.style,a)||bR(this.computedStyles(),a)},computedStyles:o.currentStyle?function(){return this._.currentStyle||{}}:o.runtimeStyle?function(){return this._.runtimeStyle||{}}:function(){return this._.ownerDocument.defaultView.getComputedStyle(this._,null)},hasClass:function(a){return(" "+this._.className+" ").indexOf(" "+a+" ")!=-1},setClass:function(a){this._.className=a;return this},getClass:function(){return this._.className},addClass:function(a){var b=" "+this._.className+" ";b.indexOf(" "+a+" ")==-1&&(this._.className+=(b===" "?"":" ")+a);return this},removeClass:function(a){this._.className=(" "+this._.className+" ").replace(" "+a+" "," ").trim();return this},toggleClass:function(a){return this[this.hasClass(a)?"removeClass":"addClass"](a)},radioClass:function(a){this.siblings().each("removeClass",a);return this.addClass(a)}}),bG.include({set:function(a,b){if(typeof a==="string"){var c={};c[a]=b,a=c}var d,e=this._;for(d in a)d==="style"?this.setStyle(a[d]):(d in e||e.setAttribute(d,""+a[d]),d.substr(0,5)!=="data-"&&(e[d]=a[d]));return this},get:function(a){var b=this._,c=b[a]||b.getAttribute(a);return c===""?null:c},has:function(a){return this.get(a)!==null},erase:function(a){this._.removeAttribute(a);return this},hidden:function(){return this.getStyle("display")==="none"},visible:function(){return!this.hidden()},hide:function(a,b){this.visible()&&(this._d=this.getStyle("display"),this._.style.display="none");return this},show:function(){if(this.hidden()){var a=this._,b=this._d,c;if(!b||b==="none")c=G(a.tagName).insertTo(o),b=c.getStyle("display"),c.remove();b==="none"&&(b="block"),a.style.display=b}return this},toggle:function(){return this[this.visible()?"hide":"show"]()},radio:function(a,b){this.siblings().each("hide",a,b);return this.show()},data:function(a,b){var c,d,e,f,g,h;if(A(a))for(c in a)b=this.data(c,a[c]);else if(b===i){a="data-"+(""+a).dasherize();for(d={},e=!1,f=this._.attributes,h=0;hb.x&&a.xb.y&&a.y1)e=f.shift(),e.endsWith("]")&&(e=e.substr(0,e.length-1)),d[e]||(d[e]=f[0]==="]"?[]:{}),d=d[e];e=f.shift(),e.endsWith("]")&&(e=e.substr(0,e.length-1)),e===""?d.push(b.value()):d[e]=b.value()}});return a},serialize:function(){return c.toQueryString(this.values())},submit:function(){this._.submit();return this},reset:function(){this._.reset();return this}});bS("submit reset focus blur disable enable change");var bU=j.Input=bH.INPUT=bH.BUTTON=bH.SELECT=bH.TEXTAREA=bH.OPTGROUP=new bc(bG,{initialize:function(a,b){if(!a||A(a)&&!C(a))b=a||{},/textarea|select/.test(b.type||"")?(a=b.type,delete b.type):a="input";this.$super(a,b)},form:function(){return bA(this._.form)},insert:function(a,b){this.$super(a,b),this.find("option").each(function(a){a._.selected=!!a.get("selected")});return this},update:function(a){return this.clean().insert(a)},getValue:function(){return this._.type=="select-multiple"?this.find("option").map(function(a){return a._.selected?a._.value:null}).compact():this._.value},setValue:function(a){this._.type=="select-multiple"?(a=N(a).map(e),this.find("option").each(function(b){b._.selected=a.include(b._.value)})):this._.value=a;return this},value:function(a){return this[a===i?"getValue":"setValue"](a)},focus:function(){this._.focus(),this.focused=!0,br&&this.fire("focus",{bubbles:!1});return this},blur:function(){this._.blur(),this.focused=!1,br&&this.fire("blur",{bubbles:!1});return this},select:function(){this._.select();return this.focus()},disable:function(){this._.disabled=!0;return this.fire("disable")},enable:function(){this._.disabled=!1;return this.fire("enable")},disabled:function(a){return a===i?this._.disabled:this[a?"disable":"enable"]()},checked:function(a){a===i?a=this._.checked:(this._.checked=a,a=this);return a}});bt?(b.attachEvent("onfocusin",bV),b.attachEvent("onfocusout",bV)):(b.addEventListener("focus",bV,!0),b.addEventListener("blur",bV,!0));var bW=[],bX=!0;bS("mouseenter mouseleave"),[bG,bB].each("include",{delegate:function(a){var b=cb(arguments),c,d,e,f;for(c in b)for(d=0,f=b[c];d=200&&this.status<300},send:function(a){var b={},c=this.url,d=this.method.toLowerCase(),e=this.headers,f,g;if(d=="put"||d=="delete")b._method=d,d="post";var h=this.prepareData(this.params,this.prepareParams(a),b);this.urlEncoded&&d=="post"&&!e["Content-type"]&&this.setHeader("Content-type","application/x-www-form-urlencoded;charset="+this.encoding),d=="get"&&(h&&(c+=(c.include("?")?"&":"?")+h),h=null),g=this.xhr=this.createXhr(),this.fire("create"),g.open(d,c,this.async),g.onreadystatechange=this.stateChanged.bind(this);for(f in e)g.setRequestHeader(f,e[f]);g.send(h),this.fire("request"),this.async||this.stateChanged();return this},update:function(a,b){return this.onSuccess(function(b){a.update(b.text)}).send(b)},cancel:function(){var a=this.xhr;if(!a||a.canceled)return this;a.abort(),a.onreadystatechange=function(){},a.canceled=!0;return this.fire("cancel")},fire:function(a){return this.$super(a,this,this.xhr)},createXhr:function(){return this.jsonp?new ce.JSONP(this):this.form&&this.form.first("input[type=file]")?new ce.IFramed(this.form):"ActiveXObject"in a?new ActiveXObject("MSXML2.XMLHTTP"):new XMLHttpRequest},prepareParams:function(a){return a},prepareData:function(){return J(arguments).map(function(a){y(a)||(a=c.toQueryString(a));return a.blank()?null:a}).compact().join("&")},stateChanged:function(){var a=this.xhr;if(a.readyState==4&&!a.canceled){try{this.status=a.status}catch(b){this.status=0}this.text=this.responseText=a.responseText,this.xml=this.responseXML=a.responseXML,this.fire("complete").fire(this.successful()?"success":"failure")}},tryScripts:function(a){var b=this.getHeader("Content-type"),c=this.getHeader("X-JSON");c&&(this.json=this.responseJSON=this.headerJSON=JSON.parse(c)),this.evalResponse||this.evalJS&&/(ecma|java)script/i.test(b)?t(this.text):/json/.test(b)&&this.evalJSON?this.json=this.responseJSON=JSON.parse(this.text):this.evalScripts&&this.text.evalScripts()},initCallbacks:function(){this.on({create:"showSpinner",complete:"hideSpinner",cancel:"hideSpinner"}),this.on("complete","tryScripts"),ce.EVENTS.each(function(a){this.on(a,function(){ce.fire(a,this,this.xhr)})},this)},showSpinner:function(){ce.showSpinner.call(this,this)},hideSpinner:function(){ce.hideSpinner.call(this,this)}});s(bl(ce),{counter:0,showSpinner:function(a){ce.trySpinner(a,"show")},hideSpinner:function(a){ce.trySpinner(a,"hide")},trySpinner:function(a,b){var c=a||ce.Options,d=E(c.spinner);d&&d[b](c.spinnerFx,{duration:100})},countIn:function(){ce.counter++,ce.showSpinner()},countOut:function(){ce.counter--,ce.counter<1&&ce.hideSpinner()}}).on({create:"countIn",complete:"countOut",cancel:"countOut"}),bT.include({send:function(a){a=a||{},a.method=a.method||this._.method||"post",this.xhr=(new ce(this._.action||b.location.href,s({spinner:this.first(".spinner")},a))).onComplete(this.enable.bind(this)).onCancel(this.enable.bind(this)).send(this),this.disable.bind(this).delay(1);return this},cancelXhr:function(){this.xhr instanceof ce&&this.xhr.cancel();return this},remotize:function(a){this.remote||(this.on("submit",cf,a),this.remote=!0);return this},unremotize:function(){this.stopObserving("submit",cf),this.remote=!1;return this}}),ce.include({prepareParams:function(a){a&&a instanceof bT&&(this.form=a,a=a.values());return a}}),bG.include({load:function(a,b){(new ce(a,s({method:"get"},b))).update(this);return this}}),ce.Dummy={open:function(){},setRequestHeader:function(){},onreadystatechange:function(){}},ce.IFramed=new bc({include:ce.Dummy,initialize:function(a){this.form=a,this.id="xhr_"+(new Date).getTime(),this.form.doc().first("body").append('',"after"),E(this.id).on("load",this.onLoad.bind(this))},send:function(){this.form.set("target",this.id).submit()},onLoad:function(){this.status=200,this.readyState=4,this.form.set("target","");try{this.responseText=a[this.id].document.documentElement.innerHTML}catch(b){}this.onreadystatechange()},abort:function(){E(this.id).set("src","about:blank")}}),ce.JSONP=new bc({include:ce.Dummy,prefix:"jsonp",initialize:function(a){this.xhr=a,this.name=this.prefix+(new Date).getTime(),this.param=(y(a.jsonp)?a.jsonp:"callback")+"="+this.name,this.script=G("script",{charset:a.encoding,async:a.async})},open:function(a,b,c){this.url=b,this.method=a},send:function(b){a[this.name]=this.finish.bind(this),this.script.set("src",this.url+(this.url.include("?")?"&":"?")+this.param+"&"+b).insertTo(F("script").last(),"after")},finish:function(a){this.status=200,this.readyState=4,this.xhr.json=this.xhr.responseJSON=a,this.onreadystatechange()},abort:function(){a[this.name]=function(){}}});var cg=j.Fx=new bc(bk,{extend:{EVENTS:H("start finish cancel"),Durations:{"short":200,normal:400,"long":800},Options:{fps:bt?40:60,duration:"normal",transition:"default",queue:!0,engine:"css"}},initialize:function(a,b){this.$super(b),this.element=E(a),cj(this)},start:function(){if(ck(this,arguments))return this;cl(this),this.prepare.apply(this,arguments),cp(this);return this.fire("start",this)},finish:function(){cq(this),cm(this),this.fire("finish"),cn(this);return this},cancel:function(){cq(this),cm(this);return this.fire("cancel")},prepare:function(){},render:function(){}}),ch=[],ci=[],cr={"default":"(.25,.1,.25,1)",linear:"(0,0,1,1)","ease-in":"(.42,0,1,1)","ease-out":"(0,0,.58,1)","ease-in-out":"(.42,0,.58,1)","ease-out-in":"(0,.42,1,.58)"},cs={};e.COLORS={maroon:"#800000",red:"#ff0000",orange:"#ffA500",yellow:"#ffff00",olive:"#808000",purple:"#800080",fuchsia:"#ff00ff",white:"#ffffff",lime:"#00ff00",green:"#008000",navy:"#000080",blue:"#0000ff",aqua:"#00ffff",teal:"#008080",black:"#000000",silver:"#c0c0c0",gray:"#808080",brown:"#a52a2a"},e.include({toHex:function(){var a=/^#(\w)(\w)(\w)$/.exec(this);a?a="#"+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]:(a=/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/.exec(this))?a="#"+a.slice(1).map(function(a){a=(a-0).toString(16);return a.length==1?"0"+a:a}).join(""):a=e.COLORS[this]||this;return a},toRgb:function(a){var b=/#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})/i.exec(this.toHex()||"");b&&(b=b.slice(1).map("toInt",16),b=a?b:"rgb("+b+")");return b}}),bG.include({stop:function(){co(this);return this},hide:function(a,b){return a&&this.visible()?cu(this,a,["out",b]):this.$super()},show:function(a,b){return a&&!this.visible()?cu(this,a,["in",b]):this.$super()},toggle:function(a,b){return a?cu(this,a,["toggle",b]):this.$super()},remove:function(a,b){return a&&this.visible()?cu(this,a,["out",s(b||{},{onFinish:this.$super.bind(this)})]):this.$super()},morph:function(a,b){return cu(this,"morph",[a,b||{}])},highlight:function(){return cu(this,"highlight",arguments)},fade:function(){return cu(this,"fade",arguments)},slide:function(){return cu(this,"slide",arguments)},scroll:function(a,b){return cu(this,"scroll",[a,b||{}])},scrollTo:function(a,b){return A(b)?this.scroll(a,b):this.$super.apply(this,arguments)}});var cv=["WebkitT","OT","MozT","MsT","t"].first(function(a){return a+"ransition"in o.style}),cw=cv+"ransition",cx=cw+"Property",cy=cw+"Duration",cz=cw+"TimingFunction",cA={Sin:"cubic-bezier(.3,0,.6,1)",Cos:"cubic-bezier(0,.3,.6,0)",Log:"cubic-bezier(0,.6,.3,.8)",Exp:"cubic-bezier(.6,0,.8,.3)",Lin:"cubic-bezier(0,0,1,1)"};cg.Options.engine=cv===i||bq?"javascript":"native",cg.Morph=new bc(cg,{prepare:function(a){if(this.options.engine==="native"&&cv!==i)this.render=this.transition=function(){},cB.call(this,a);else{var b=cE(a),c=cJ(this.element,b),d=cK(this.element,a,b);cI(this.element,c,d),this.before=cH(c),this.after=cH(d)}},render:function(a){var b,c,d,e=this.element._.style,f,g,i;for(f in this.after){b=this.before[f],c=this.after[f];for(g=0,i=c.length;g=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1E3*this.Diff_Timeout);if(null==a||null==b)throw Error("Null input. (diff_main)");if(a==b)return a?[[0,a]]:[];"undefined"==typeof c&&(c=!0);var e=c,f=this.diff_commonPrefix(a,b),c=a.substring(0,f),a=a.substring(f),b=b.substring(f),f=this.diff_commonSuffix(a,b),g=a.substring(a.length-f),a=a.substring(0,a.length-f),b=b.substring(0,b.length-f),a=this.diff_compute_(a, -b,e,d);c&&a.unshift([0,c]);g&&a.push([0,g]);this.diff_cleanupMerge(a);return a}; -diff_match_patch.prototype.diff_compute_=function(a,b,c,d){if(!a)return[[1,b]];if(!b)return[[-1,a]];var e=a.length>b.length?a:b,f=a.length>b.length?b:a,g=e.indexOf(f);if(-1!=g)return c=[[1,e.substring(0,g)],[0,f],[1,e.substring(g+f.length)]],a.length>b.length&&(c[0][0]=c[2][0]=-1),c;if(1==f.length)return[[-1,a],[1,b]];return(e=this.diff_halfMatch_(a,b))?(f=e[0],a=e[1],g=e[2],b=e[3],e=e[4],f=this.diff_main(f,g,c,d),c=this.diff_main(a,b,c,d),f.concat([[0,e]],c)):c&&100c);u++){for(var n=-u+q;n<=u-s;n+=2){var l=g+n,m;m=n==-u||n!=u&&j[l-1]d)s+=2;else if(r>e)q+=2;else if(p&&(l=g+k-n,0<=l&&l= -t)return this.diff_bisectSplit_(a,b,m,r,c)}}for(n=-u+o;n<=u-v;n+=2){l=g+n;t=n==-u||n!=u&&i[l-1]d)v+=2;else if(m>e)o+=2;else if(!p&&(l=g+k-n,0<=l&&l=t)))return this.diff_bisectSplit_(a,b,m,r,c)}}return[[-1,a],[1,b]]}; -diff_match_patch.prototype.diff_bisectSplit_=function(a,b,c,d,e){var f=a.substring(0,c),g=b.substring(0,d),a=a.substring(c),b=b.substring(d),f=this.diff_main(f,g,!1,e),e=this.diff_main(a,b,!1,e);return f.concat(e)}; -diff_match_patch.prototype.diff_linesToChars_=function(a,b){function c(a){for(var b="",c=0,f=-1,g=d.length;fd?a=a.substring(c-d):c=a.length?[h,j,n,l,g]:null}if(0>=this.Diff_Timeout)return null; -var d=a.length>b.length?a:b,e=a.length>b.length?b:a;if(4>d.length||2*e.lengthd[4].length?g:d:d:g;var j;a.length>b.length?(g=h[0],d=h[1],e=h[2],j=h[3]):(e=h[0],j=h[1],g=h[2],d=h[3]);h=h[4];return[g,d,e,j,h]}; -diff_match_patch.prototype.diff_cleanupSemantic=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=0,h=0,j=0,i=0;f=e){if(d>=b.length/2||d>=c.length/2)a.splice(f,0,[0,c.substring(0,d)]),a[f-1][1]=b.substring(0,b.length-d),a[f+1][1]=c.substring(d),f++}else if(e>=b.length/2||e>=c.length/2)a.splice(f,0,[0,b.substring(0,e)]),a[f-1][0]=1,a[f-1][1]=c.substring(0,c.length-e),a[f+1][0]=-1,a[f+1][1]=b.substring(e),f++;f++}f++}}; -diff_match_patch.prototype.diff_cleanupSemanticLossless=function(a){function b(a,b){if(!a||!b)return 6;var c=a.charAt(a.length-1),d=b.charAt(0),e=c.match(diff_match_patch.nonAlphaNumericRegex_),f=d.match(diff_match_patch.nonAlphaNumericRegex_),g=e&&c.match(diff_match_patch.whitespaceRegex_),h=f&&d.match(diff_match_patch.whitespaceRegex_),c=g&&c.match(diff_match_patch.linebreakRegex_),d=h&&d.match(diff_match_patch.linebreakRegex_),i=c&&a.match(diff_match_patch.blanklineEndRegex_),j=d&&b.match(diff_match_patch.blanklineStartRegex_); -return i||j?5:c||d?4:e&&!g&&h?3:g||h?2:e||f?1:0}for(var c=1;c=i&&(i=k,g=d,h=e,j=f)}a[c-1][1]!=g&&(g?a[c-1][1]=g:(a.splice(c-1,1),c--),a[c][1]= -h,j?a[c+1][1]=j:(a.splice(c+1,1),c--))}c++}};diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch.whitespaceRegex_=/\s/;diff_match_patch.linebreakRegex_=/[\r\n]/;diff_match_patch.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/; -diff_match_patch.prototype.diff_cleanupEfficiency=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=!1,h=!1,j=!1,i=!1;fb)break;e=c;f=d}return a.length!=g&&-1===a[g][0]?f:f+(b-e)}; -diff_match_patch.prototype.diff_prettyHtml=function(a){for(var b=[],c=/&/g,d=//g,f=/\n/g,g=0;g");switch(h){case 1:b[g]=''+j+"";break;case -1:b[g]=''+j+"";break;case 0:b[g]=""+j+""}}return b.join("")}; -diff_match_patch.prototype.diff_text1=function(a){for(var b=[],c=0;cthis.Match_MaxBits)throw Error("Pattern too long for this browser.");var e=this.match_alphabet_(b),f=this,g=this.Match_Threshold,h=a.indexOf(b,c);-1!=h&&(g=Math.min(d(0,h),g),h=a.lastIndexOf(b,c+b.length),-1!=h&&(g=Math.min(d(0,h),g)));for(var j=1<=i;o--){var v=e[a.charAt(o-1)];k[o]=0===s?(k[o+1]<<1|1)&v:(k[o+1]<<1|1)&v|(q[o+1]|q[o])<<1|1|q[o+1];if(k[o]&j&&(v=d(s,o-1),v<=g))if(g=v,h=o-1,h>c)i=Math.max(1,2*c-h);else break}if(d(s+1,c)>g)break;q=k}return h}; -diff_match_patch.prototype.match_alphabet_=function(a){for(var b={},c=0;c=2*this.Patch_Margin&& -e&&(this.patch_addContext_(a,h),c.push(a),a=new diff_match_patch.patch_obj,e=0,h=d,f=g)}1!==i&&(f+=k.length);-1!==i&&(g+=k.length)}e&&(this.patch_addContext_(a,h),c.push(a));return c};diff_match_patch.prototype.patch_deepCopy=function(a){for(var b=[],c=0;cthis.Match_MaxBits){if(j=this.match_main(b,h.substring(0,this.Match_MaxBits),g),-1!=j&&(i=this.match_main(b,h.substring(h.length-this.Match_MaxBits),g+h.length-this.Match_MaxBits),-1==i||j>=i))j=-1}else j=this.match_main(b,h,g); -if(-1==j)e[f]=!1,d-=a[f].length2-a[f].length1;else if(e[f]=!0,d=j-g,g=-1==i?b.substring(j,j+h.length):b.substring(j,i+this.Match_MaxBits),h==g)b=b.substring(0,j)+this.diff_text2(a[f].diffs)+b.substring(j+h.length);else if(g=this.diff_main(h,g,!1),h.length>this.Match_MaxBits&&this.diff_levenshtein(g)/h.length>this.Patch_DeleteThreshold)e[f]=!1;else{this.diff_cleanupSemanticLossless(g);for(var h=0,k,i=0;ie[0][1].length){var f=b-e[0][1].length;e[0][1]=c.substring(e[0][1].length)+e[0][1];d.start1-=f;d.start2-=f;d.length1+=f;d.length2+=f}d=a[a.length-1];e=d.diffs;0==e.length||0!=e[e.length-1][0]?(e.push([0, -c]),d.length1+=b,d.length2+=b):b>e[e.length-1][1].length&&(f=b-e[e.length-1][1].length,e[e.length-1][1]+=c.substring(0,f),d.length1+=f,d.length2+=f);return c}; -diff_match_patch.prototype.patch_splitMax=function(a){for(var b=this.Match_MaxBits,c=0;c2*b?(h.length1+=i.length,e+=i.length,j=!1,h.diffs.push([g,i]),d.diffs.shift()):(i=i.substring(0,b-h.length1-this.Patch_Margin),h.length1+=i.length,e+=i.length,0===g?(h.length2+=i.length,f+=i.length):j=!1,h.diffs.push([g,i]),i==d.diffs[0][1]?d.diffs.shift():d.diffs[0][1]=d.diffs[0][1].substring(i.length))}g=this.diff_text2(h.diffs);g=g.substring(g.length-this.Patch_Margin);i=this.diff_text1(d.diffs).substring(0,this.Patch_Margin);""!==i&& -(h.length1+=i.length,h.length2+=i.length,0!==h.diffs.length&&0===h.diffs[h.diffs.length-1][0]?h.diffs[h.diffs.length-1][1]+=i:h.diffs.push([0,i]));j||a.splice(++c,0,h)}}};diff_match_patch.prototype.patch_toText=function(a){for(var b=[],c=0;c - - - - - - - - - - - - - - -

If debugging errors, start with the first reported error, - subsequent tests often rely on earlier ones.

- - - - diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/diff_match_patch_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/diff_match_patch_test.js deleted file mode 100644 index ed76e79..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/diff_match_patch_test.js +++ /dev/null @@ -1,938 +0,0 @@ -/** - * Test Harness for Diff Match and Patch - * - * Copyright 2006 Google Inc. - * http://code.google.com/p/google-diff-match-patch/ - * - * 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. - */ - - -// If expected and actual are the equivalent, pass the test. -function assertEquivalent(msg, expected, actual) { - if (typeof actual == 'undefined') { - // msg is optional. - actual = expected; - expected = msg; - msg = 'Expected: \'' + expected + '\' Actual: \'' + actual + '\''; - } - if (_equivalent(expected, actual)) { - assertEquals(msg, String.toString(expected), String.toString(actual)); - } else { - assertEquals(msg, expected, actual); - } -} - - -// Are a and b the equivalent? -- Recursive. -function _equivalent(a, b) { - if (a == b) { - return true; - } - if (typeof a == 'object' && typeof b == 'object' && a !== null && b !== null) { - if (a.toString() != b.toString()) { - return false; - } - for (var p in a) { - if (!_equivalent(a[p], b[p])) { - return false; - } - } - for (var p in b) { - if (!_equivalent(a[p], b[p])) { - return false; - } - } - return true; - } - return false; -} - - -function diff_rebuildtexts(diffs) { - // Construct the two texts which made up the diff originally. - var text1 = ''; - var text2 = ''; - for (var x = 0; x < diffs.length; x++) { - if (diffs[x][0] != DIFF_INSERT) { - text1 += diffs[x][1]; - } - if (diffs[x][0] != DIFF_DELETE) { - text2 += diffs[x][1]; - } - } - return [text1, text2]; -} - -var dmp = new diff_match_patch(); - - -// DIFF TEST FUNCTIONS - - -function testDiffCommonPrefix() { - // Detect any common prefix. - // Null case. - assertEquals(0, dmp.diff_commonPrefix('abc', 'xyz')); - - // Non-null case. - assertEquals(4, dmp.diff_commonPrefix('1234abcdef', '1234xyz')); - - // Whole case. - assertEquals(4, dmp.diff_commonPrefix('1234', '1234xyz')); -} - -function testDiffCommonSuffix() { - // Detect any common suffix. - // Null case. - assertEquals(0, dmp.diff_commonSuffix('abc', 'xyz')); - - // Non-null case. - assertEquals(4, dmp.diff_commonSuffix('abcdef1234', 'xyz1234')); - - // Whole case. - assertEquals(4, dmp.diff_commonSuffix('1234', 'xyz1234')); -} - -function testDiffCommonOverlap() { - // Detect any suffix/prefix overlap. - // Null case. - assertEquals(0, dmp.diff_commonOverlap_('', 'abcd')); - - // Whole case. - assertEquals(3, dmp.diff_commonOverlap_('abc', 'abcd')); - - // No overlap. - assertEquals(0, dmp.diff_commonOverlap_('123456', 'abcd')); - - // Overlap. - assertEquals(3, dmp.diff_commonOverlap_('123456xxx', 'xxxabcd')); - - // Unicode. - // Some overly clever languages (C#) may treat ligatures as equal to their - // component letters. E.g. U+FB01 == 'fi' - assertEquals(0, dmp.diff_commonOverlap_('fi', '\ufb01i')); -} - -function testDiffHalfMatch() { - // Detect a halfmatch. - dmp.Diff_Timeout = 1; - // No match. - assertEquals(null, dmp.diff_halfMatch_('1234567890', 'abcdef')); - - assertEquals(null, dmp.diff_halfMatch_('12345', '23')); - - // Single Match. - assertEquivalent(['12', '90', 'a', 'z', '345678'], dmp.diff_halfMatch_('1234567890', 'a345678z')); - - assertEquivalent(['a', 'z', '12', '90', '345678'], dmp.diff_halfMatch_('a345678z', '1234567890')); - - assertEquivalent(['abc', 'z', '1234', '0', '56789'], dmp.diff_halfMatch_('abc56789z', '1234567890')); - - assertEquivalent(['a', 'xyz', '1', '7890', '23456'], dmp.diff_halfMatch_('a23456xyz', '1234567890')); - - // Multiple Matches. - assertEquivalent(['12123', '123121', 'a', 'z', '1234123451234'], dmp.diff_halfMatch_('121231234123451234123121', 'a1234123451234z')); - - assertEquivalent(['', '-=-=-=-=-=', 'x', '', 'x-=-=-=-=-=-=-='], dmp.diff_halfMatch_('x-=-=-=-=-=-=-=-=-=-=-=-=', 'xx-=-=-=-=-=-=-=')); - - assertEquivalent(['-=-=-=-=-=', '', '', 'y', '-=-=-=-=-=-=-=y'], dmp.diff_halfMatch_('-=-=-=-=-=-=-=-=-=-=-=-=y', '-=-=-=-=-=-=-=yy')); - - // Non-optimal halfmatch. - // Optimal diff would be -q+x=H-i+e=lloHe+Hu=llo-Hew+y not -qHillo+x=HelloHe-w+Hulloy - assertEquivalent(['qHillo', 'w', 'x', 'Hulloy', 'HelloHe'], dmp.diff_halfMatch_('qHilloHelloHew', 'xHelloHeHulloy')); - - // Optimal no halfmatch. - dmp.Diff_Timeout = 0; - assertEquals(null, dmp.diff_halfMatch_('qHilloHelloHew', 'xHelloHeHulloy')); -} - -function testDiffLinesToChars() { - function assertLinesToCharsResultEquals(a, b) { - assertEquals(a.chars1, b.chars1); - assertEquals(a.chars2, b.chars2); - assertEquivalent(a.lineArray, b.lineArray); - } - - // Convert lines down to characters. - assertLinesToCharsResultEquals({chars1: '\x01\x02\x01', chars2: '\x02\x01\x02', lineArray: ['', 'alpha\n', 'beta\n']}, dmp.diff_linesToChars_('alpha\nbeta\nalpha\n', 'beta\nalpha\nbeta\n')); - - assertLinesToCharsResultEquals({chars1: '', chars2: '\x01\x02\x03\x03', lineArray: ['', 'alpha\r\n', 'beta\r\n', '\r\n']}, dmp.diff_linesToChars_('', 'alpha\r\nbeta\r\n\r\n\r\n')); - - assertLinesToCharsResultEquals({chars1: '\x01', chars2: '\x02', lineArray: ['', 'a', 'b']}, dmp.diff_linesToChars_('a', 'b')); - - // More than 256 to reveal any 8-bit limitations. - var n = 300; - var lineList = []; - var charList = []; - for (var x = 1; x < n + 1; x++) { - lineList[x - 1] = x + '\n'; - charList[x - 1] = String.fromCharCode(x); - } - assertEquals(n, lineList.length); - var lines = lineList.join(''); - var chars = charList.join(''); - assertEquals(n, chars.length); - lineList.unshift(''); - assertLinesToCharsResultEquals({chars1: chars, chars2: '', lineArray: lineList}, dmp.diff_linesToChars_(lines, '')); -} - -function testDiffCharsToLines() { - // Convert chars up to lines. - var diffs = [[DIFF_EQUAL, '\x01\x02\x01'], [DIFF_INSERT, '\x02\x01\x02']]; - dmp.diff_charsToLines_(diffs, ['', 'alpha\n', 'beta\n']); - assertEquivalent([[DIFF_EQUAL, 'alpha\nbeta\nalpha\n'], [DIFF_INSERT, 'beta\nalpha\nbeta\n']], diffs); - - // More than 256 to reveal any 8-bit limitations. - var n = 300; - var lineList = []; - var charList = []; - for (var x = 1; x < n + 1; x++) { - lineList[x - 1] = x + '\n'; - charList[x - 1] = String.fromCharCode(x); - } - assertEquals(n, lineList.length); - var lines = lineList.join(''); - var chars = charList.join(''); - assertEquals(n, chars.length); - lineList.unshift(''); - var diffs = [[DIFF_DELETE, chars]]; - dmp.diff_charsToLines_(diffs, lineList); - assertEquivalent([[DIFF_DELETE, lines]], diffs); -} - -function testDiffCleanupMerge() { - // Cleanup a messy diff. - // Null case. - var diffs = []; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([], diffs); - - // No change case. - diffs = [[DIFF_EQUAL, 'a'], [DIFF_DELETE, 'b'], [DIFF_INSERT, 'c']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_EQUAL, 'a'], [DIFF_DELETE, 'b'], [DIFF_INSERT, 'c']], diffs); - - // Merge equalities. - diffs = [[DIFF_EQUAL, 'a'], [DIFF_EQUAL, 'b'], [DIFF_EQUAL, 'c']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_EQUAL, 'abc']], diffs); - - // Merge deletions. - diffs = [[DIFF_DELETE, 'a'], [DIFF_DELETE, 'b'], [DIFF_DELETE, 'c']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_DELETE, 'abc']], diffs); - - // Merge insertions. - diffs = [[DIFF_INSERT, 'a'], [DIFF_INSERT, 'b'], [DIFF_INSERT, 'c']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_INSERT, 'abc']], diffs); - - // Merge interweave. - diffs = [[DIFF_DELETE, 'a'], [DIFF_INSERT, 'b'], [DIFF_DELETE, 'c'], [DIFF_INSERT, 'd'], [DIFF_EQUAL, 'e'], [DIFF_EQUAL, 'f']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_DELETE, 'ac'], [DIFF_INSERT, 'bd'], [DIFF_EQUAL, 'ef']], diffs); - - // Prefix and suffix detection. - diffs = [[DIFF_DELETE, 'a'], [DIFF_INSERT, 'abc'], [DIFF_DELETE, 'dc']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_EQUAL, 'a'], [DIFF_DELETE, 'd'], [DIFF_INSERT, 'b'], [DIFF_EQUAL, 'c']], diffs); - - // Prefix and suffix detection with equalities. - diffs = [[DIFF_EQUAL, 'x'], [DIFF_DELETE, 'a'], [DIFF_INSERT, 'abc'], [DIFF_DELETE, 'dc'], [DIFF_EQUAL, 'y']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_EQUAL, 'xa'], [DIFF_DELETE, 'd'], [DIFF_INSERT, 'b'], [DIFF_EQUAL, 'cy']], diffs); - - // Slide edit left. - diffs = [[DIFF_EQUAL, 'a'], [DIFF_INSERT, 'ba'], [DIFF_EQUAL, 'c']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_INSERT, 'ab'], [DIFF_EQUAL, 'ac']], diffs); - - // Slide edit right. - diffs = [[DIFF_EQUAL, 'c'], [DIFF_INSERT, 'ab'], [DIFF_EQUAL, 'a']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_EQUAL, 'ca'], [DIFF_INSERT, 'ba']], diffs); - - // Slide edit left recursive. - diffs = [[DIFF_EQUAL, 'a'], [DIFF_DELETE, 'b'], [DIFF_EQUAL, 'c'], [DIFF_DELETE, 'ac'], [DIFF_EQUAL, 'x']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_DELETE, 'abc'], [DIFF_EQUAL, 'acx']], diffs); - - // Slide edit right recursive. - diffs = [[DIFF_EQUAL, 'x'], [DIFF_DELETE, 'ca'], [DIFF_EQUAL, 'c'], [DIFF_DELETE, 'b'], [DIFF_EQUAL, 'a']]; - dmp.diff_cleanupMerge(diffs); - assertEquivalent([[DIFF_EQUAL, 'xca'], [DIFF_DELETE, 'cba']], diffs); -} - -function testDiffCleanupSemanticLossless() { - // Slide diffs to match logical boundaries. - // Null case. - var diffs = []; - dmp.diff_cleanupSemanticLossless(diffs); - assertEquivalent([], diffs); - - // Blank lines. - diffs = [[DIFF_EQUAL, 'AAA\r\n\r\nBBB'], [DIFF_INSERT, '\r\nDDD\r\n\r\nBBB'], [DIFF_EQUAL, '\r\nEEE']]; - dmp.diff_cleanupSemanticLossless(diffs); - assertEquivalent([[DIFF_EQUAL, 'AAA\r\n\r\n'], [DIFF_INSERT, 'BBB\r\nDDD\r\n\r\n'], [DIFF_EQUAL, 'BBB\r\nEEE']], diffs); - - // Line boundaries. - diffs = [[DIFF_EQUAL, 'AAA\r\nBBB'], [DIFF_INSERT, ' DDD\r\nBBB'], [DIFF_EQUAL, ' EEE']]; - dmp.diff_cleanupSemanticLossless(diffs); - assertEquivalent([[DIFF_EQUAL, 'AAA\r\n'], [DIFF_INSERT, 'BBB DDD\r\n'], [DIFF_EQUAL, 'BBB EEE']], diffs); - - // Word boundaries. - diffs = [[DIFF_EQUAL, 'The c'], [DIFF_INSERT, 'ow and the c'], [DIFF_EQUAL, 'at.']]; - dmp.diff_cleanupSemanticLossless(diffs); - assertEquivalent([[DIFF_EQUAL, 'The '], [DIFF_INSERT, 'cow and the '], [DIFF_EQUAL, 'cat.']], diffs); - - // Alphanumeric boundaries. - diffs = [[DIFF_EQUAL, 'The-c'], [DIFF_INSERT, 'ow-and-the-c'], [DIFF_EQUAL, 'at.']]; - dmp.diff_cleanupSemanticLossless(diffs); - assertEquivalent([[DIFF_EQUAL, 'The-'], [DIFF_INSERT, 'cow-and-the-'], [DIFF_EQUAL, 'cat.']], diffs); - - // Hitting the start. - diffs = [[DIFF_EQUAL, 'a'], [DIFF_DELETE, 'a'], [DIFF_EQUAL, 'ax']]; - dmp.diff_cleanupSemanticLossless(diffs); - assertEquivalent([[DIFF_DELETE, 'a'], [DIFF_EQUAL, 'aax']], diffs); - - // Hitting the end. - diffs = [[DIFF_EQUAL, 'xa'], [DIFF_DELETE, 'a'], [DIFF_EQUAL, 'a']]; - dmp.diff_cleanupSemanticLossless(diffs); - assertEquivalent([[DIFF_EQUAL, 'xaa'], [DIFF_DELETE, 'a']], diffs); - - // Sentence boundaries. - diffs = [[DIFF_EQUAL, 'The xxx. The '], [DIFF_INSERT, 'zzz. The '], [DIFF_EQUAL, 'yyy.']]; - dmp.diff_cleanupSemanticLossless(diffs); - assertEquivalent([[DIFF_EQUAL, 'The xxx.'], [DIFF_INSERT, ' The zzz.'], [DIFF_EQUAL, ' The yyy.']], diffs); -} - -function testDiffCleanupSemantic() { - // Cleanup semantically trivial equalities. - // Null case. - var diffs = []; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([], diffs); - - // No elimination #1. - diffs = [[DIFF_DELETE, 'ab'], [DIFF_INSERT, 'cd'], [DIFF_EQUAL, '12'], [DIFF_DELETE, 'e']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_DELETE, 'ab'], [DIFF_INSERT, 'cd'], [DIFF_EQUAL, '12'], [DIFF_DELETE, 'e']], diffs); - - // No elimination #2. - diffs = [[DIFF_DELETE, 'abc'], [DIFF_INSERT, 'ABC'], [DIFF_EQUAL, '1234'], [DIFF_DELETE, 'wxyz']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_DELETE, 'abc'], [DIFF_INSERT, 'ABC'], [DIFF_EQUAL, '1234'], [DIFF_DELETE, 'wxyz']], diffs); - - // Simple elimination. - diffs = [[DIFF_DELETE, 'a'], [DIFF_EQUAL, 'b'], [DIFF_DELETE, 'c']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_DELETE, 'abc'], [DIFF_INSERT, 'b']], diffs); - - // Backpass elimination. - diffs = [[DIFF_DELETE, 'ab'], [DIFF_EQUAL, 'cd'], [DIFF_DELETE, 'e'], [DIFF_EQUAL, 'f'], [DIFF_INSERT, 'g']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_DELETE, 'abcdef'], [DIFF_INSERT, 'cdfg']], diffs); - - // Multiple eliminations. - diffs = [[DIFF_INSERT, '1'], [DIFF_EQUAL, 'A'], [DIFF_DELETE, 'B'], [DIFF_INSERT, '2'], [DIFF_EQUAL, '_'], [DIFF_INSERT, '1'], [DIFF_EQUAL, 'A'], [DIFF_DELETE, 'B'], [DIFF_INSERT, '2']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_DELETE, 'AB_AB'], [DIFF_INSERT, '1A2_1A2']], diffs); - - // Word boundaries. - diffs = [[DIFF_EQUAL, 'The c'], [DIFF_DELETE, 'ow and the c'], [DIFF_EQUAL, 'at.']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_EQUAL, 'The '], [DIFF_DELETE, 'cow and the '], [DIFF_EQUAL, 'cat.']], diffs); - - // No overlap elimination. - diffs = [[DIFF_DELETE, 'abcxx'], [DIFF_INSERT, 'xxdef']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_DELETE, 'abcxx'], [DIFF_INSERT, 'xxdef']], diffs); - - // Overlap elimination. - diffs = [[DIFF_DELETE, 'abcxxx'], [DIFF_INSERT, 'xxxdef']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_DELETE, 'abc'], [DIFF_EQUAL, 'xxx'], [DIFF_INSERT, 'def']], diffs); - - // Reverse overlap elimination. - diffs = [[DIFF_DELETE, 'xxxabc'], [DIFF_INSERT, 'defxxx']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_INSERT, 'def'], [DIFF_EQUAL, 'xxx'], [DIFF_DELETE, 'abc']], diffs); - - // Two overlap eliminations. - diffs = [[DIFF_DELETE, 'abcd1212'], [DIFF_INSERT, '1212efghi'], [DIFF_EQUAL, '----'], [DIFF_DELETE, 'A3'], [DIFF_INSERT, '3BC']]; - dmp.diff_cleanupSemantic(diffs); - assertEquivalent([[DIFF_DELETE, 'abcd'], [DIFF_EQUAL, '1212'], [DIFF_INSERT, 'efghi'], [DIFF_EQUAL, '----'], [DIFF_DELETE, 'A'], [DIFF_EQUAL, '3'], [DIFF_INSERT, 'BC']], diffs); -} - -function testDiffCleanupEfficiency() { - // Cleanup operationally trivial equalities. - dmp.Diff_EditCost = 4; - // Null case. - var diffs = []; - dmp.diff_cleanupEfficiency(diffs); - assertEquivalent([], diffs); - - // No elimination. - diffs = [[DIFF_DELETE, 'ab'], [DIFF_INSERT, '12'], [DIFF_EQUAL, 'wxyz'], [DIFF_DELETE, 'cd'], [DIFF_INSERT, '34']]; - dmp.diff_cleanupEfficiency(diffs); - assertEquivalent([[DIFF_DELETE, 'ab'], [DIFF_INSERT, '12'], [DIFF_EQUAL, 'wxyz'], [DIFF_DELETE, 'cd'], [DIFF_INSERT, '34']], diffs); - - // Four-edit elimination. - diffs = [[DIFF_DELETE, 'ab'], [DIFF_INSERT, '12'], [DIFF_EQUAL, 'xyz'], [DIFF_DELETE, 'cd'], [DIFF_INSERT, '34']]; - dmp.diff_cleanupEfficiency(diffs); - assertEquivalent([[DIFF_DELETE, 'abxyzcd'], [DIFF_INSERT, '12xyz34']], diffs); - - // Three-edit elimination. - diffs = [[DIFF_INSERT, '12'], [DIFF_EQUAL, 'x'], [DIFF_DELETE, 'cd'], [DIFF_INSERT, '34']]; - dmp.diff_cleanupEfficiency(diffs); - assertEquivalent([[DIFF_DELETE, 'xcd'], [DIFF_INSERT, '12x34']], diffs); - - // Backpass elimination. - diffs = [[DIFF_DELETE, 'ab'], [DIFF_INSERT, '12'], [DIFF_EQUAL, 'xy'], [DIFF_INSERT, '34'], [DIFF_EQUAL, 'z'], [DIFF_DELETE, 'cd'], [DIFF_INSERT, '56']]; - dmp.diff_cleanupEfficiency(diffs); - assertEquivalent([[DIFF_DELETE, 'abxyzcd'], [DIFF_INSERT, '12xy34z56']], diffs); - - // High cost elimination. - dmp.Diff_EditCost = 5; - diffs = [[DIFF_DELETE, 'ab'], [DIFF_INSERT, '12'], [DIFF_EQUAL, 'wxyz'], [DIFF_DELETE, 'cd'], [DIFF_INSERT, '34']]; - dmp.diff_cleanupEfficiency(diffs); - assertEquivalent([[DIFF_DELETE, 'abwxyzcd'], [DIFF_INSERT, '12wxyz34']], diffs); - dmp.Diff_EditCost = 4; -} - -function testDiffPrettyHtml() { - // Pretty print. - var diffs = [[DIFF_EQUAL, 'a\n'], [DIFF_DELETE, 'b'], [DIFF_INSERT, 'c&d']]; - assertEquals('
<B>b</B>c&d', dmp.diff_prettyHtml(diffs)); -} - -function testDiffText() { - // Compute the source and destination texts. - var diffs = [[DIFF_EQUAL, 'jump'], [DIFF_DELETE, 's'], [DIFF_INSERT, 'ed'], [DIFF_EQUAL, ' over '], [DIFF_DELETE, 'the'], [DIFF_INSERT, 'a'], [DIFF_EQUAL, ' lazy']]; - assertEquals('jumps over the lazy', dmp.diff_text1(diffs)); - - assertEquals('jumped over a lazy', dmp.diff_text2(diffs)); -} - -function testDiffDelta() { - // Convert a diff into delta string. - var diffs = [[DIFF_EQUAL, 'jump'], [DIFF_DELETE, 's'], [DIFF_INSERT, 'ed'], [DIFF_EQUAL, ' over '], [DIFF_DELETE, 'the'], [DIFF_INSERT, 'a'], [DIFF_EQUAL, ' lazy'], [DIFF_INSERT, 'old dog']]; - var text1 = dmp.diff_text1(diffs); - assertEquals('jumps over the lazy', text1); - - var delta = dmp.diff_toDelta(diffs); - assertEquals('=4\t-1\t+ed\t=6\t-3\t+a\t=5\t+old dog', delta); - - // Convert delta string into a diff. - assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta)); - - // Generates error (19 != 20). - try { - dmp.diff_fromDelta(text1 + 'x', delta); - assertEquals(Error, null); - } catch (e) { - // Exception expected. - } - - // Generates error (19 != 18). - try { - dmp.diff_fromDelta(text1.substring(1), delta); - assertEquals(Error, null); - } catch (e) { - // Exception expected. - } - - // Generates error (%c3%xy invalid Unicode). - try { - dmp.diff_fromDelta('', '+%c3%xy'); - assertEquals(Error, null); - } catch (e) { - // Exception expected. - } - - // Test deltas with special characters. - diffs = [[DIFF_EQUAL, '\u0680 \x00 \t %'], [DIFF_DELETE, '\u0681 \x01 \n ^'], [DIFF_INSERT, '\u0682 \x02 \\ |']]; - text1 = dmp.diff_text1(diffs); - assertEquals('\u0680 \x00 \t %\u0681 \x01 \n ^', text1); - - delta = dmp.diff_toDelta(diffs); - assertEquals('=7\t-7\t+%DA%82 %02 %5C %7C', delta); - - // Convert delta string into a diff. - assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta)); - - // Verify pool of unchanged characters. - diffs = [[DIFF_INSERT, 'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ']]; - var text2 = dmp.diff_text2(diffs); - assertEquals('A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ', text2); - - delta = dmp.diff_toDelta(diffs); - assertEquals('+A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ', delta); - - // Convert delta string into a diff. - assertEquivalent(diffs, dmp.diff_fromDelta('', delta)); -} - -function testDiffXIndex() { - // Translate a location in text1 to text2. - // Translation on equality. - assertEquals(5, dmp.diff_xIndex([[DIFF_DELETE, 'a'], [DIFF_INSERT, '1234'], [DIFF_EQUAL, 'xyz']], 2)); - - // Translation on deletion. - assertEquals(1, dmp.diff_xIndex([[DIFF_EQUAL, 'a'], [DIFF_DELETE, '1234'], [DIFF_EQUAL, 'xyz']], 3)); -} - -function testDiffLevenshtein() { - // Levenshtein with trailing equality. - assertEquals(4, dmp.diff_levenshtein([[DIFF_DELETE, 'abc'], [DIFF_INSERT, '1234'], [DIFF_EQUAL, 'xyz']])); - // Levenshtein with leading equality. - assertEquals(4, dmp.diff_levenshtein([[DIFF_EQUAL, 'xyz'], [DIFF_DELETE, 'abc'], [DIFF_INSERT, '1234']])); - // Levenshtein with middle equality. - assertEquals(7, dmp.diff_levenshtein([[DIFF_DELETE, 'abc'], [DIFF_EQUAL, 'xyz'], [DIFF_INSERT, '1234']])); -} - -function testDiffBisect() { - // Normal. - var a = 'cat'; - var b = 'map'; - // Since the resulting diff hasn't been normalized, it would be ok if - // the insertion and deletion pairs are swapped. - // If the order changes, tweak this test as required. - assertEquivalent([[DIFF_DELETE, 'c'], [DIFF_INSERT, 'm'], [DIFF_EQUAL, 'a'], [DIFF_DELETE, 't'], [DIFF_INSERT, 'p']], dmp.diff_bisect_(a, b, Number.MAX_VALUE)); - - // Timeout. - assertEquivalent([[DIFF_DELETE, 'cat'], [DIFF_INSERT, 'map']], dmp.diff_bisect_(a, b, 0)); -} - -function testDiffMain() { - // Perform a trivial diff. - // Null case. - assertEquivalent([], dmp.diff_main('', '', false)); - - // Equality. - assertEquivalent([[DIFF_EQUAL, 'abc']], dmp.diff_main('abc', 'abc', false)); - - // Simple insertion. - assertEquivalent([[DIFF_EQUAL, 'ab'], [DIFF_INSERT, '123'], [DIFF_EQUAL, 'c']], dmp.diff_main('abc', 'ab123c', false)); - - // Simple deletion. - assertEquivalent([[DIFF_EQUAL, 'a'], [DIFF_DELETE, '123'], [DIFF_EQUAL, 'bc']], dmp.diff_main('a123bc', 'abc', false)); - - // Two insertions. - assertEquivalent([[DIFF_EQUAL, 'a'], [DIFF_INSERT, '123'], [DIFF_EQUAL, 'b'], [DIFF_INSERT, '456'], [DIFF_EQUAL, 'c']], dmp.diff_main('abc', 'a123b456c', false)); - - // Two deletions. - assertEquivalent([[DIFF_EQUAL, 'a'], [DIFF_DELETE, '123'], [DIFF_EQUAL, 'b'], [DIFF_DELETE, '456'], [DIFF_EQUAL, 'c']], dmp.diff_main('a123b456c', 'abc', false)); - - // Perform a real diff. - // Switch off the timeout. - dmp.Diff_Timeout = 0; - // Simple cases. - assertEquivalent([[DIFF_DELETE, 'a'], [DIFF_INSERT, 'b']], dmp.diff_main('a', 'b', false)); - - assertEquivalent([[DIFF_DELETE, 'Apple'], [DIFF_INSERT, 'Banana'], [DIFF_EQUAL, 's are a'], [DIFF_INSERT, 'lso'], [DIFF_EQUAL, ' fruit.']], dmp.diff_main('Apples are a fruit.', 'Bananas are also fruit.', false)); - - assertEquivalent([[DIFF_DELETE, 'a'], [DIFF_INSERT, '\u0680'], [DIFF_EQUAL, 'x'], [DIFF_DELETE, '\t'], [DIFF_INSERT, '\0']], dmp.diff_main('ax\t', '\u0680x\0', false)); - - // Overlaps. - assertEquivalent([[DIFF_DELETE, '1'], [DIFF_EQUAL, 'a'], [DIFF_DELETE, 'y'], [DIFF_EQUAL, 'b'], [DIFF_DELETE, '2'], [DIFF_INSERT, 'xab']], dmp.diff_main('1ayb2', 'abxab', false)); - - assertEquivalent([[DIFF_INSERT, 'xaxcx'], [DIFF_EQUAL, 'abc'], [DIFF_DELETE, 'y']], dmp.diff_main('abcy', 'xaxcxabc', false)); - - assertEquivalent([[DIFF_DELETE, 'ABCD'], [DIFF_EQUAL, 'a'], [DIFF_DELETE, '='], [DIFF_INSERT, '-'], [DIFF_EQUAL, 'bcd'], [DIFF_DELETE, '='], [DIFF_INSERT, '-'], [DIFF_EQUAL, 'efghijklmnopqrs'], [DIFF_DELETE, 'EFGHIJKLMNOefg']], dmp.diff_main('ABCDa=bcd=efghijklmnopqrsEFGHIJKLMNOefg', 'a-bcd-efghijklmnopqrs', false)); - - // Large equality. - assertEquivalent([[DIFF_INSERT, ' '], [DIFF_EQUAL, 'a'], [DIFF_INSERT, 'nd'], [DIFF_EQUAL, ' [[Pennsylvania]]'], [DIFF_DELETE, ' and [[New']], dmp.diff_main('a [[Pennsylvania]] and [[New', ' and [[Pennsylvania]]', false)); - - // Timeout. - dmp.Diff_Timeout = 0.1; // 100ms - var a = '`Twas brillig, and the slithy toves\nDid gyre and gimble in the wabe:\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.\n'; - var b = 'I am the very model of a modern major general,\nI\'ve information vegetable, animal, and mineral,\nI know the kings of England, and I quote the fights historical,\nFrom Marathon to Waterloo, in order categorical.\n'; - // Increase the text lengths by 1024 times to ensure a timeout. - for (var x = 0; x < 10; x++) { - a = a + a; - b = b + b; - } - var startTime = (new Date()).getTime(); - dmp.diff_main(a, b); - var endTime = (new Date()).getTime(); - // Test that we took at least the timeout period. - assertTrue(dmp.Diff_Timeout * 1000 <= endTime - startTime); - // Test that we didn't take forever (be forgiving). - // Theoretically this test could fail very occasionally if the - // OS task swaps or locks up for a second at the wrong moment. - // **** - // TODO(fraser): For unknown reasons this is taking 500 ms on Google's - // internal test system. Whereas browsers take 140 ms. - //assertTrue(dmp.Diff_Timeout * 1000 * 2 > endTime - startTime); - // **** - dmp.Diff_Timeout = 0; - - // Test the linemode speedup. - // Must be long to pass the 100 char cutoff. - // Simple line-mode. - a = '1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n'; - b = 'abcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\n'; - assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true)); - - // Single line-mode. - a = '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'; - b = 'abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij'; - assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true)); - - // Overlap line-mode. - a = '1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n'; - b = 'abcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n'; - var texts_linemode = diff_rebuildtexts(dmp.diff_main(a, b, true)); - var texts_textmode = diff_rebuildtexts(dmp.diff_main(a, b, false)); - assertEquivalent(texts_textmode, texts_linemode); - - // Test null inputs. - try { - dmp.diff_main(null, null); - assertEquals(Error, null); - } catch (e) { - // Exception expected. - } -} - - -// MATCH TEST FUNCTIONS - - -function testMatchAlphabet() { - // Initialise the bitmasks for Bitap. - // Unique. - assertEquivalent({'a':4, 'b':2, 'c':1}, dmp.match_alphabet_('abc')); - - // Duplicates. - assertEquivalent({'a':37, 'b':18, 'c':8}, dmp.match_alphabet_('abcaba')); -} - -function testMatchBitap() { - // Bitap algorithm. - dmp.Match_Distance = 100; - dmp.Match_Threshold = 0.5; - // Exact matches. - assertEquals(5, dmp.match_bitap_('abcdefghijk', 'fgh', 5)); - - assertEquals(5, dmp.match_bitap_('abcdefghijk', 'fgh', 0)); - - // Fuzzy matches. - assertEquals(4, dmp.match_bitap_('abcdefghijk', 'efxhi', 0)); - - assertEquals(2, dmp.match_bitap_('abcdefghijk', 'cdefxyhijk', 5)); - - assertEquals(-1, dmp.match_bitap_('abcdefghijk', 'bxy', 1)); - - // Overflow. - assertEquals(2, dmp.match_bitap_('123456789xx0', '3456789x0', 2)); - - // Threshold test. - dmp.Match_Threshold = 0.4; - assertEquals(4, dmp.match_bitap_('abcdefghijk', 'efxyhi', 1)); - - dmp.Match_Threshold = 0.3; - assertEquals(-1, dmp.match_bitap_('abcdefghijk', 'efxyhi', 1)); - - dmp.Match_Threshold = 0.0; - assertEquals(1, dmp.match_bitap_('abcdefghijk', 'bcdef', 1)); - dmp.Match_Threshold = 0.5; - - // Multiple select. - assertEquals(0, dmp.match_bitap_('abcdexyzabcde', 'abccde', 3)); - - assertEquals(8, dmp.match_bitap_('abcdexyzabcde', 'abccde', 5)); - - // Distance test. - dmp.Match_Distance = 10; // Strict location. - assertEquals(-1, dmp.match_bitap_('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 24)); - - assertEquals(0, dmp.match_bitap_('abcdefghijklmnopqrstuvwxyz', 'abcdxxefg', 1)); - - dmp.Match_Distance = 1000; // Loose location. - assertEquals(0, dmp.match_bitap_('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 24)); -} - -function testMatchMain() { - // Full match. - // Shortcut matches. - assertEquals(0, dmp.match_main('abcdef', 'abcdef', 1000)); - - assertEquals(-1, dmp.match_main('', 'abcdef', 1)); - - assertEquals(3, dmp.match_main('abcdef', '', 3)); - - assertEquals(3, dmp.match_main('abcdef', 'de', 3)); - - // Beyond end match. - assertEquals(3, dmp.match_main("abcdef", "defy", 4)); - - // Oversized pattern. - assertEquals(0, dmp.match_main("abcdef", "abcdefy", 0)); - - // Complex match. - assertEquals(4, dmp.match_main('I am the very model of a modern major general.', ' that berry ', 5)); - - // Test null inputs. - try { - dmp.match_main(null, null, 0); - assertEquals(Error, null); - } catch (e) { - // Exception expected. - } -} - - -// PATCH TEST FUNCTIONS - - -function testPatchObj() { - // Patch Object. - var p = new diff_match_patch.patch_obj(); - p.start1 = 20; - p.start2 = 21; - p.length1 = 18; - p.length2 = 17; - p.diffs = [[DIFF_EQUAL, 'jump'], [DIFF_DELETE, 's'], [DIFF_INSERT, 'ed'], [DIFF_EQUAL, ' over '], [DIFF_DELETE, 'the'], [DIFF_INSERT, 'a'], [DIFF_EQUAL, '\nlaz']]; - var strp = p.toString(); - assertEquals('@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n', strp); -} - -function testPatchFromText() { - assertEquivalent([], dmp.patch_fromText(strp)); - - var strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n'; - assertEquals(strp, dmp.patch_fromText(strp)[0].toString()); - - assertEquals('@@ -1 +1 @@\n-a\n+b\n', dmp.patch_fromText('@@ -1 +1 @@\n-a\n+b\n')[0].toString()); - - assertEquals('@@ -1,3 +0,0 @@\n-abc\n', dmp.patch_fromText('@@ -1,3 +0,0 @@\n-abc\n')[0].toString()); - - assertEquals('@@ -0,0 +1,3 @@\n+abc\n', dmp.patch_fromText('@@ -0,0 +1,3 @@\n+abc\n')[0].toString()); - - // Generates error. - try { - dmp.patch_fromText('Bad\nPatch\n'); - assertEquals(Error, null); - } catch (e) { - // Exception expected. - } -} - -function testPatchToText() { - var strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'; - var p = dmp.patch_fromText(strp); - assertEquals(strp, dmp.patch_toText(p)); - - strp = '@@ -1,9 +1,9 @@\n-f\n+F\n oo+fooba\n@@ -7,9 +7,9 @@\n obar\n-,\n+.\n tes\n'; - p = dmp.patch_fromText(strp); - assertEquals(strp, dmp.patch_toText(p)); -} - -function testPatchAddContext() { - dmp.Patch_Margin = 4; - var p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[0]; - dmp.patch_addContext_(p, 'The quick brown fox jumps over the lazy dog.'); - assertEquals('@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n', p.toString()); - - // Same, but not enough trailing context. - p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[0]; - dmp.patch_addContext_(p, 'The quick brown fox jumps.'); - assertEquals('@@ -17,10 +17,16 @@\n fox \n-jump\n+somersault\n s.\n', p.toString()); - - // Same, but not enough leading context. - p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[0]; - dmp.patch_addContext_(p, 'The quick brown fox jumps.'); - assertEquals('@@ -1,7 +1,8 @@\n Th\n-e\n+at\n qui\n', p.toString()); - - // Same, but with ambiguity. - p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[0]; - dmp.patch_addContext_(p, 'The quick brown fox jumps. The quick brown fox crashes.'); - assertEquals('@@ -1,27 +1,28 @@\n Th\n-e\n+at\n quick brown fox jumps. \n', p.toString()); -} - -function testPatchMake() { - // Null case. - var patches = dmp.patch_make('', ''); - assertEquals('', dmp.patch_toText(patches)); - - var text1 = 'The quick brown fox jumps over the lazy dog.'; - var text2 = 'That quick brown fox jumped over a lazy dog.'; - // Text2+Text1 inputs. - var expectedPatch = '@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n'; - // The second patch must be "-21,17 +21,18", not "-22,17 +21,18" due to rolling context. - patches = dmp.patch_make(text2, text1); - assertEquals(expectedPatch, dmp.patch_toText(patches)); - - // Text1+Text2 inputs. - expectedPatch = '@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'; - patches = dmp.patch_make(text1, text2); - assertEquals(expectedPatch, dmp.patch_toText(patches)); - - // Diff input. - var diffs = dmp.diff_main(text1, text2, false); - patches = dmp.patch_make(diffs); - assertEquals(expectedPatch, dmp.patch_toText(patches)); - - // Text1+Diff inputs. - patches = dmp.patch_make(text1, diffs); - assertEquals(expectedPatch, dmp.patch_toText(patches)); - - // Text1+Text2+Diff inputs (deprecated). - patches = dmp.patch_make(text1, text2, diffs); - assertEquals(expectedPatch, dmp.patch_toText(patches)); - - // Character encoding. - patches = dmp.patch_make('`1234567890-=[]\\;\',./', '~!@#$%^&*()_+{}|:"<>?'); - assertEquals('@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;\',./\n+~!@#$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n', dmp.patch_toText(patches)); - - // Character decoding. - diffs = [[DIFF_DELETE, '`1234567890-=[]\\;\',./'], [DIFF_INSERT, '~!@#$%^&*()_+{}|:"<>?']]; - assertEquivalent(diffs, dmp.patch_fromText('@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;\',./\n+~!@#$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n')[0].diffs); - - // Long string with repeats. - text1 = ''; - for (var x = 0; x < 100; x++) { - text1 += 'abcdef'; - } - text2 = text1 + '123'; - expectedPatch = '@@ -573,28 +573,31 @@\n cdefabcdefabcdefabcdefabcdef\n+123\n'; - patches = dmp.patch_make(text1, text2); - assertEquals(expectedPatch, dmp.patch_toText(patches)); - - // Test null inputs. - try { - dmp.patch_make(null); - assertEquals(Error, null); - } catch (e) { - // Exception expected. - } -} - -function testPatchSplitMax() { - // Assumes that dmp.Match_MaxBits is 32. - var patches = dmp.patch_make('abcdefghijklmnopqrstuvwxyz01234567890', 'XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0'); - dmp.patch_splitMax(patches); - assertEquals('@@ -1,32 +1,46 @@\n+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\n uv\n+X\n wx\n+X\n yz\n+X\n 012345\n@@ -25,13 +39,18 @@\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n', dmp.patch_toText(patches)); - - patches = dmp.patch_make('abcdef1234567890123456789012345678901234567890123456789012345678901234567890uvwxyz', 'abcdefuvwxyz'); - var oldToText = dmp.patch_toText(patches); - dmp.patch_splitMax(patches); - assertEquals(oldToText, dmp.patch_toText(patches)); - - patches = dmp.patch_make('1234567890123456789012345678901234567890123456789012345678901234567890', 'abc'); - dmp.patch_splitMax(patches); - assertEquals('@@ -1,32 +1,4 @@\n-1234567890123456789012345678\n 9012\n@@ -29,32 +1,4 @@\n-9012345678901234567890123456\n 7890\n@@ -57,14 +1,3 @@\n-78901234567890\n+abc\n', dmp.patch_toText(patches)); - - patches = dmp.patch_make('abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1', 'abcdefghij , h : 1 , t : 1 abcdefghij , h : 1 , t : 1 abcdefghij , h : 0 , t : 1'); - dmp.patch_splitMax(patches); - assertEquals('@@ -2,32 +2,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n@@ -29,32 +29,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n', dmp.patch_toText(patches)); -} - -function testPatchAddPadding() { - // Both edges full. - var patches = dmp.patch_make('', 'test'); - assertEquals('@@ -0,0 +1,4 @@\n+test\n', dmp.patch_toText(patches)); - dmp.patch_addPadding(patches); - assertEquals('@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n', dmp.patch_toText(patches)); - - // Both edges partial. - patches = dmp.patch_make('XY', 'XtestY'); - assertEquals('@@ -1,2 +1,6 @@\n X\n+test\n Y\n', dmp.patch_toText(patches)); - dmp.patch_addPadding(patches); - assertEquals('@@ -2,8 +2,12 @@\n %02%03%04X\n+test\n Y%01%02%03\n', dmp.patch_toText(patches)); - - // Both edges none. - patches = dmp.patch_make('XXXXYYYY', 'XXXXtestYYYY'); - assertEquals('@@ -1,8 +1,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches)); - dmp.patch_addPadding(patches); - assertEquals('@@ -5,8 +5,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches)); -} - -function testPatchApply() { - dmp.Match_Distance = 1000; - dmp.Match_Threshold = 0.5; - dmp.Patch_DeleteThreshold = 0.5; - // Null case. - var patches = dmp.patch_make('', ''); - var results = dmp.patch_apply(patches, 'Hello world.'); - assertEquivalent(['Hello world.', []], results); - - // Exact match. - patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.', 'That quick brown fox jumped over a lazy dog.'); - results = dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.'); - assertEquivalent(['That quick brown fox jumped over a lazy dog.', [true, true]], results); - - // Partial match. - results = dmp.patch_apply(patches, 'The quick red rabbit jumps over the tired tiger.'); - assertEquivalent(['That quick red rabbit jumped over a tired tiger.', [true, true]], results); - - // Failed match. - results = dmp.patch_apply(patches, 'I am the very model of a modern major general.'); - assertEquivalent(['I am the very model of a modern major general.', [false, false]], results); - - // Big delete, small change. - patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789012345678901234567890y', 'xabcy'); - results = dmp.patch_apply(patches, 'x123456789012345678901234567890-----++++++++++-----123456789012345678901234567890y'); - assertEquivalent(['xabcy', [true, true]], results); - - // Big delete, big change 1. - patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789012345678901234567890y', 'xabcy'); - results = dmp.patch_apply(patches, 'x12345678901234567890---------------++++++++++---------------12345678901234567890y'); - assertEquivalent(['xabc12345678901234567890---------------++++++++++---------------12345678901234567890y', [false, true]], results); - - // Big delete, big change 2. - dmp.Patch_DeleteThreshold = 0.6; - patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789012345678901234567890y', 'xabcy'); - results = dmp.patch_apply(patches, 'x12345678901234567890---------------++++++++++---------------12345678901234567890y'); - assertEquivalent(['xabcy', [true, true]], results); - dmp.Patch_DeleteThreshold = 0.5; - - // Compensate for failed patch. - dmp.Match_Threshold = 0.0; - dmp.Match_Distance = 0; - patches = dmp.patch_make('abcdefghijklmnopqrstuvwxyz--------------------1234567890', 'abcXXXXXXXXXXdefghijklmnopqrstuvwxyz--------------------1234567YYYYYYYYYY890'); - results = dmp.patch_apply(patches, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567890'); - assertEquivalent(['ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567YYYYYYYYYY890', [false, true]], results); - dmp.Match_Threshold = 0.5; - dmp.Match_Distance = 1000; - - // No side effects. - patches = dmp.patch_make('', 'test'); - var patchstr = dmp.patch_toText(patches); - dmp.patch_apply(patches, ''); - assertEquals(patchstr, dmp.patch_toText(patches)); - - // No side effects with major delete. - patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.', 'Woof'); - patchstr = dmp.patch_toText(patches); - dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.'); - assertEquals(patchstr, dmp.patch_toText(patches)); - - // Edge exact match. - patches = dmp.patch_make('', 'test'); - results = dmp.patch_apply(patches, ''); - assertEquivalent(['test', [true]], results); - - // Near edge exact match. - patches = dmp.patch_make('XY', 'XtestY'); - results = dmp.patch_apply(patches, 'XY'); - assertEquivalent(['XtestY', [true]], results); - - // Edge partial match. - patches = dmp.patch_make('y', 'y123'); - results = dmp.patch_apply(patches, 'x'); - assertEquivalent(['x123', [true]], results); -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/diff_match_patch_uncompressed.js b/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/diff_match_patch_uncompressed.js deleted file mode 100644 index 11c8fcf..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/diff_match_patch_uncompressed.js +++ /dev/null @@ -1,2196 +0,0 @@ -/** - * Diff Match and Patch - * - * Copyright 2006 Google Inc. - * http://code.google.com/p/google-diff-match-patch/ - * - * 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 Computes the difference between two texts to create a patch. - * Applies the patch onto another text, allowing for errors. - * @author fraser@google.com (Neil Fraser) - */ - -/** - * Class containing the diff, match and patch methods. - * @constructor - */ -function diff_match_patch() { - - // Defaults. - // Redefine these in your program to override the defaults. - - // Number of seconds to map a diff before giving up (0 for infinity). - this.Diff_Timeout = 1.0; - // Cost of an empty edit operation in terms of edit characters. - this.Diff_EditCost = 4; - // At what point is no match declared (0.0 = perfection, 1.0 = very loose). - this.Match_Threshold = 0.5; - // How far to search for a match (0 = exact location, 1000+ = broad match). - // A match this many characters away from the expected location will add - // 1.0 to the score (0.0 is a perfect match). - this.Match_Distance = 1000; - // When deleting a large block of text (over ~64 characters), how close do - // the contents have to be to match the expected contents. (0.0 = perfection, - // 1.0 = very loose). Note that Match_Threshold controls how closely the - // end points of a delete need to match. - this.Patch_DeleteThreshold = 0.5; - // Chunk size for context length. - this.Patch_Margin = 4; - - // The number of bits in an int. - this.Match_MaxBits = 32; -} - - -// DIFF FUNCTIONS - - -/** - * The data structure representing a diff is an array of tuples: - * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] - * which means: delete 'Hello', add 'Goodbye' and keep ' world.' - */ -var DIFF_DELETE = -1; -var DIFF_INSERT = 1; -var DIFF_EQUAL = 0; - -/** @typedef {{0: number, 1: string}} */ -diff_match_patch.Diff; - - -/** - * Find the differences between two texts. Simplifies the problem by stripping - * any common prefix or suffix off the texts before diffing. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {boolean=} opt_checklines Optional speedup flag. If present and false, - * then don't run a line-level diff first to identify the changed areas. - * Defaults to true, which does a faster, slightly less optimal diff. - * @param {number} opt_deadline Optional time when the diff should be complete - * by. Used internally for recursive calls. Users should set DiffTimeout - * instead. - * @return {!Array.} Array of diff tuples. - */ -diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines, - opt_deadline) { - // Set a deadline by which time the diff must be complete. - if (typeof opt_deadline == 'undefined') { - if (this.Diff_Timeout <= 0) { - opt_deadline = Number.MAX_VALUE; - } else { - opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000; - } - } - var deadline = opt_deadline; - - // Check for null inputs. - if (text1 == null || text2 == null) { - throw new Error('Null input. (diff_main)'); - } - - // Check for equality (speedup). - if (text1 == text2) { - if (text1) { - return [[DIFF_EQUAL, text1]]; - } - return []; - } - - if (typeof opt_checklines == 'undefined') { - opt_checklines = true; - } - var checklines = opt_checklines; - - // Trim off common prefix (speedup). - var commonlength = this.diff_commonPrefix(text1, text2); - var commonprefix = text1.substring(0, commonlength); - text1 = text1.substring(commonlength); - text2 = text2.substring(commonlength); - - // Trim off common suffix (speedup). - commonlength = this.diff_commonSuffix(text1, text2); - var commonsuffix = text1.substring(text1.length - commonlength); - text1 = text1.substring(0, text1.length - commonlength); - text2 = text2.substring(0, text2.length - commonlength); - - // Compute the diff on the middle block. - var diffs = this.diff_compute_(text1, text2, checklines, deadline); - - // Restore the prefix and suffix. - if (commonprefix) { - diffs.unshift([DIFF_EQUAL, commonprefix]); - } - if (commonsuffix) { - diffs.push([DIFF_EQUAL, commonsuffix]); - } - this.diff_cleanupMerge(diffs); - return diffs; -}; - - -/** - * Find the differences between two texts. Assumes that the texts do not - * have any common prefix or suffix. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {boolean} checklines Speedup flag. If false, then don't run a - * line-level diff first to identify the changed areas. - * If true, then run a faster, slightly less optimal diff. - * @param {number} deadline Time when the diff should be complete by. - * @return {!Array.} Array of diff tuples. - * @private - */ -diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines, - deadline) { - var diffs; - - if (!text1) { - // Just add some text (speedup). - return [[DIFF_INSERT, text2]]; - } - - if (!text2) { - // Just delete some text (speedup). - return [[DIFF_DELETE, text1]]; - } - - /** @type {?string} */ - var longtext = text1.length > text2.length ? text1 : text2; - /** @type {?string} */ - var shorttext = text1.length > text2.length ? text2 : text1; - var i = longtext.indexOf(shorttext); - if (i != -1) { - // Shorter text is inside the longer text (speedup). - diffs = [[DIFF_INSERT, longtext.substring(0, i)], - [DIFF_EQUAL, shorttext], - [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; - // Swap insertions for deletions if diff is reversed. - if (text1.length > text2.length) { - diffs[0][0] = diffs[2][0] = DIFF_DELETE; - } - return diffs; - } - - if (shorttext.length == 1) { - // Single character string. - // After the previous speedup, the character can't be an equality. - return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; - } - longtext = shorttext = null; // Garbage collect. - - // Check to see if the problem can be split in two. - var hm = this.diff_halfMatch_(text1, text2); - if (hm) { - // A half-match was found, sort out the return data. - var text1_a = hm[0]; - var text1_b = hm[1]; - var text2_a = hm[2]; - var text2_b = hm[3]; - var mid_common = hm[4]; - // Send both pairs off for separate processing. - var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline); - var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline); - // Merge the results. - return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b); - } - - if (checklines && text1.length > 100 && text2.length > 100) { - return this.diff_lineMode_(text1, text2, deadline); - } - - return this.diff_bisect_(text1, text2, deadline); -}; - - -/** - * Do a quick line-level diff on both strings, then rediff the parts for - * greater accuracy. - * This speedup can produce non-minimal diffs. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {number} deadline Time when the diff should be complete by. - * @return {!Array.} Array of diff tuples. - * @private - */ -diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) { - // Scan the text on a line-by-line basis first. - var a = this.diff_linesToChars_(text1, text2); - text1 = a.chars1; - text2 = a.chars2; - var linearray = a.lineArray; - - var diffs = this.diff_main(text1, text2, false, deadline); - - // Convert the diff back to original text. - this.diff_charsToLines_(diffs, linearray); - // Eliminate freak matches (e.g. blank lines) - this.diff_cleanupSemantic(diffs); - - // Rediff any replacement blocks, this time character-by-character. - // Add a dummy entry at the end. - diffs.push([DIFF_EQUAL, '']); - var pointer = 0; - var count_delete = 0; - var count_insert = 0; - var text_delete = ''; - var text_insert = ''; - while (pointer < diffs.length) { - switch (diffs[pointer][0]) { - case DIFF_INSERT: - count_insert++; - text_insert += diffs[pointer][1]; - break; - case DIFF_DELETE: - count_delete++; - text_delete += diffs[pointer][1]; - break; - case DIFF_EQUAL: - // Upon reaching an equality, check for prior redundancies. - if (count_delete >= 1 && count_insert >= 1) { - // Delete the offending records and add the merged ones. - diffs.splice(pointer - count_delete - count_insert, - count_delete + count_insert); - pointer = pointer - count_delete - count_insert; - var a = this.diff_main(text_delete, text_insert, false, deadline); - for (var j = a.length - 1; j >= 0; j--) { - diffs.splice(pointer, 0, a[j]); - } - pointer = pointer + a.length; - } - count_insert = 0; - count_delete = 0; - text_delete = ''; - text_insert = ''; - break; - } - pointer++; - } - diffs.pop(); // Remove the dummy entry at the end. - - return diffs; -}; - - -/** - * Find the 'middle snake' of a diff, split the problem in two - * and return the recursively constructed diff. - * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {number} deadline Time at which to bail if not yet complete. - * @return {!Array.} Array of diff tuples. - * @private - */ -diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) { - // Cache the text lengths to prevent multiple calls. - var text1_length = text1.length; - var text2_length = text2.length; - var max_d = Math.ceil((text1_length + text2_length) / 2); - var v_offset = max_d; - var v_length = 2 * max_d; - var v1 = new Array(v_length); - var v2 = new Array(v_length); - // Setting all elements to -1 is faster in Chrome & Firefox than mixing - // integers and undefined. - for (var x = 0; x < v_length; x++) { - v1[x] = -1; - v2[x] = -1; - } - v1[v_offset + 1] = 0; - v2[v_offset + 1] = 0; - var delta = text1_length - text2_length; - // If the total number of characters is odd, then the front path will collide - // with the reverse path. - var front = (delta % 2 != 0); - // Offsets for start and end of k loop. - // Prevents mapping of space beyond the grid. - var k1start = 0; - var k1end = 0; - var k2start = 0; - var k2end = 0; - for (var d = 0; d < max_d; d++) { - // Bail out if deadline is reached. - if ((new Date()).getTime() > deadline) { - break; - } - - // Walk the front path one step. - for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { - var k1_offset = v_offset + k1; - var x1; - if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) { - x1 = v1[k1_offset + 1]; - } else { - x1 = v1[k1_offset - 1] + 1; - } - var y1 = x1 - k1; - while (x1 < text1_length && y1 < text2_length && - text1.charAt(x1) == text2.charAt(y1)) { - x1++; - y1++; - } - v1[k1_offset] = x1; - if (x1 > text1_length) { - // Ran off the right of the graph. - k1end += 2; - } else if (y1 > text2_length) { - // Ran off the bottom of the graph. - k1start += 2; - } else if (front) { - var k2_offset = v_offset + delta - k1; - if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { - // Mirror x2 onto top-left coordinate system. - var x2 = text1_length - v2[k2_offset]; - if (x1 >= x2) { - // Overlap detected. - return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); - } - } - } - } - - // Walk the reverse path one step. - for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { - var k2_offset = v_offset + k2; - var x2; - if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) { - x2 = v2[k2_offset + 1]; - } else { - x2 = v2[k2_offset - 1] + 1; - } - var y2 = x2 - k2; - while (x2 < text1_length && y2 < text2_length && - text1.charAt(text1_length - x2 - 1) == - text2.charAt(text2_length - y2 - 1)) { - x2++; - y2++; - } - v2[k2_offset] = x2; - if (x2 > text1_length) { - // Ran off the left of the graph. - k2end += 2; - } else if (y2 > text2_length) { - // Ran off the top of the graph. - k2start += 2; - } else if (!front) { - var k1_offset = v_offset + delta - k2; - if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { - var x1 = v1[k1_offset]; - var y1 = v_offset + x1 - k1_offset; - // Mirror x2 onto top-left coordinate system. - x2 = text1_length - x2; - if (x1 >= x2) { - // Overlap detected. - return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); - } - } - } - } - } - // Diff took too long and hit the deadline or - // number of diffs equals number of characters, no commonality at all. - return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; -}; - - -/** - * Given the location of the 'middle snake', split the diff in two parts - * and recurse. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {number} x Index of split point in text1. - * @param {number} y Index of split point in text2. - * @param {number} deadline Time at which to bail if not yet complete. - * @return {!Array.} Array of diff tuples. - * @private - */ -diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y, - deadline) { - var text1a = text1.substring(0, x); - var text2a = text2.substring(0, y); - var text1b = text1.substring(x); - var text2b = text2.substring(y); - - // Compute both diffs serially. - var diffs = this.diff_main(text1a, text2a, false, deadline); - var diffsb = this.diff_main(text1b, text2b, false, deadline); - - return diffs.concat(diffsb); -}; - - -/** - * Split two texts into an array of strings. Reduce the texts to a string of - * hashes where each Unicode character represents one line. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {{chars1: string, chars2: string, lineArray: !Array.}} - * An object containing the encoded text1, the encoded text2 and - * the array of unique strings. - * The zeroth element of the array of unique strings is intentionally blank. - * @private - */ -diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) { - var lineArray = []; // e.g. lineArray[4] == 'Hello\n' - var lineHash = {}; // e.g. lineHash['Hello\n'] == 4 - - // '\x00' is a valid character, but various debuggers don't like it. - // So we'll insert a junk entry to avoid generating a null character. - lineArray[0] = ''; - - /** - * Split a text into an array of strings. Reduce the texts to a string of - * hashes where each Unicode character represents one line. - * Modifies linearray and linehash through being a closure. - * @param {string} text String to encode. - * @return {string} Encoded string. - * @private - */ - function diff_linesToCharsMunge_(text) { - var chars = ''; - // Walk the text, pulling out a substring for each line. - // text.split('\n') would would temporarily double our memory footprint. - // Modifying text would create many large strings to garbage collect. - var lineStart = 0; - var lineEnd = -1; - // Keeping our own length variable is faster than looking it up. - var lineArrayLength = lineArray.length; - while (lineEnd < text.length - 1) { - lineEnd = text.indexOf('\n', lineStart); - if (lineEnd == -1) { - lineEnd = text.length - 1; - } - var line = text.substring(lineStart, lineEnd + 1); - lineStart = lineEnd + 1; - - if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : - (lineHash[line] !== undefined)) { - chars += String.fromCharCode(lineHash[line]); - } else { - chars += String.fromCharCode(lineArrayLength); - lineHash[line] = lineArrayLength; - lineArray[lineArrayLength++] = line; - } - } - return chars; - } - - var chars1 = diff_linesToCharsMunge_(text1); - var chars2 = diff_linesToCharsMunge_(text2); - return {chars1: chars1, chars2: chars2, lineArray: lineArray}; -}; - - -/** - * Rehydrate the text in a diff from a string of line hashes to real lines of - * text. - * @param {!Array.} diffs Array of diff tuples. - * @param {!Array.} lineArray Array of unique strings. - * @private - */ -diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) { - for (var x = 0; x < diffs.length; x++) { - var chars = diffs[x][1]; - var text = []; - for (var y = 0; y < chars.length; y++) { - text[y] = lineArray[chars.charCodeAt(y)]; - } - diffs[x][1] = text.join(''); - } -}; - - -/** - * Determine the common prefix of two strings. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {number} The number of characters common to the start of each - * string. - */ -diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) { - // Quick check for common null cases. - if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { - return 0; - } - // Binary search. - // Performance analysis: http://neil.fraser.name/news/2007/10/09/ - var pointermin = 0; - var pointermax = Math.min(text1.length, text2.length); - var pointermid = pointermax; - var pointerstart = 0; - while (pointermin < pointermid) { - if (text1.substring(pointerstart, pointermid) == - text2.substring(pointerstart, pointermid)) { - pointermin = pointermid; - pointerstart = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - return pointermid; -}; - - -/** - * Determine the common suffix of two strings. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {number} The number of characters common to the end of each string. - */ -diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) { - // Quick check for common null cases. - if (!text1 || !text2 || - text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { - return 0; - } - // Binary search. - // Performance analysis: http://neil.fraser.name/news/2007/10/09/ - var pointermin = 0; - var pointermax = Math.min(text1.length, text2.length); - var pointermid = pointermax; - var pointerend = 0; - while (pointermin < pointermid) { - if (text1.substring(text1.length - pointermid, text1.length - pointerend) == - text2.substring(text2.length - pointermid, text2.length - pointerend)) { - pointermin = pointermid; - pointerend = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - return pointermid; -}; - - -/** - * Determine if the suffix of one string is the prefix of another. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {number} The number of characters common to the end of the first - * string and the start of the second string. - * @private - */ -diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) { - // Cache the text lengths to prevent multiple calls. - var text1_length = text1.length; - var text2_length = text2.length; - // Eliminate the null case. - if (text1_length == 0 || text2_length == 0) { - return 0; - } - // Truncate the longer string. - if (text1_length > text2_length) { - text1 = text1.substring(text1_length - text2_length); - } else if (text1_length < text2_length) { - text2 = text2.substring(0, text1_length); - } - var text_length = Math.min(text1_length, text2_length); - // Quick check for the worst case. - if (text1 == text2) { - return text_length; - } - - // Start by looking for a single character match - // and increase length until no match is found. - // Performance analysis: http://neil.fraser.name/news/2010/11/04/ - var best = 0; - var length = 1; - while (true) { - var pattern = text1.substring(text_length - length); - var found = text2.indexOf(pattern); - if (found == -1) { - return best; - } - length += found; - if (found == 0 || text1.substring(text_length - length) == - text2.substring(0, length)) { - best = length; - length++; - } - } -}; - - -/** - * Do the two texts share a substring which is at least half the length of the - * longer text? - * This speedup can produce non-minimal diffs. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {Array.} Five element Array, containing the prefix of - * text1, the suffix of text1, the prefix of text2, the suffix of - * text2 and the common middle. Or null if there was no match. - * @private - */ -diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) { - if (this.Diff_Timeout <= 0) { - // Don't risk returning a non-optimal diff if we have unlimited time. - return null; - } - var longtext = text1.length > text2.length ? text1 : text2; - var shorttext = text1.length > text2.length ? text2 : text1; - if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { - return null; // Pointless. - } - var dmp = this; // 'this' becomes 'window' in a closure. - - /** - * Does a substring of shorttext exist within longtext such that the substring - * is at least half the length of longtext? - * Closure, but does not reference any external variables. - * @param {string} longtext Longer string. - * @param {string} shorttext Shorter string. - * @param {number} i Start index of quarter length substring within longtext. - * @return {Array.} Five element Array, containing the prefix of - * longtext, the suffix of longtext, the prefix of shorttext, the suffix - * of shorttext and the common middle. Or null if there was no match. - * @private - */ - function diff_halfMatchI_(longtext, shorttext, i) { - // Start with a 1/4 length substring at position i as a seed. - var seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); - var j = -1; - var best_common = ''; - var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; - while ((j = shorttext.indexOf(seed, j + 1)) != -1) { - var prefixLength = dmp.diff_commonPrefix(longtext.substring(i), - shorttext.substring(j)); - var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i), - shorttext.substring(0, j)); - if (best_common.length < suffixLength + prefixLength) { - best_common = shorttext.substring(j - suffixLength, j) + - shorttext.substring(j, j + prefixLength); - best_longtext_a = longtext.substring(0, i - suffixLength); - best_longtext_b = longtext.substring(i + prefixLength); - best_shorttext_a = shorttext.substring(0, j - suffixLength); - best_shorttext_b = shorttext.substring(j + prefixLength); - } - } - if (best_common.length * 2 >= longtext.length) { - return [best_longtext_a, best_longtext_b, - best_shorttext_a, best_shorttext_b, best_common]; - } else { - return null; - } - } - - // First check if the second quarter is the seed for a half-match. - var hm1 = diff_halfMatchI_(longtext, shorttext, - Math.ceil(longtext.length / 4)); - // Check again based on the third quarter. - var hm2 = diff_halfMatchI_(longtext, shorttext, - Math.ceil(longtext.length / 2)); - var hm; - if (!hm1 && !hm2) { - return null; - } else if (!hm2) { - hm = hm1; - } else if (!hm1) { - hm = hm2; - } else { - // Both matched. Select the longest. - hm = hm1[4].length > hm2[4].length ? hm1 : hm2; - } - - // A half-match was found, sort out the return data. - var text1_a, text1_b, text2_a, text2_b; - if (text1.length > text2.length) { - text1_a = hm[0]; - text1_b = hm[1]; - text2_a = hm[2]; - text2_b = hm[3]; - } else { - text2_a = hm[0]; - text2_b = hm[1]; - text1_a = hm[2]; - text1_b = hm[3]; - } - var mid_common = hm[4]; - return [text1_a, text1_b, text2_a, text2_b, mid_common]; -}; - - -/** - * Reduce the number of edits by eliminating semantically trivial equalities. - * @param {!Array.} diffs Array of diff tuples. - */ -diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) { - var changes = false; - var equalities = []; // Stack of indices where equalities are found. - var equalitiesLength = 0; // Keeping our own length var is faster in JS. - /** @type {?string} */ - var lastequality = null; - // Always equal to diffs[equalities[equalitiesLength - 1]][1] - var pointer = 0; // Index of current position. - // Number of characters that changed prior to the equality. - var length_insertions1 = 0; - var length_deletions1 = 0; - // Number of characters that changed after the equality. - var length_insertions2 = 0; - var length_deletions2 = 0; - while (pointer < diffs.length) { - if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. - equalities[equalitiesLength++] = pointer; - length_insertions1 = length_insertions2; - length_deletions1 = length_deletions2; - length_insertions2 = 0; - length_deletions2 = 0; - lastequality = diffs[pointer][1]; - } else { // An insertion or deletion. - if (diffs[pointer][0] == DIFF_INSERT) { - length_insertions2 += diffs[pointer][1].length; - } else { - length_deletions2 += diffs[pointer][1].length; - } - // Eliminate an equality that is smaller or equal to the edits on both - // sides of it. - if (lastequality && (lastequality.length <= - Math.max(length_insertions1, length_deletions1)) && - (lastequality.length <= Math.max(length_insertions2, - length_deletions2))) { - // Duplicate record. - diffs.splice(equalities[equalitiesLength - 1], 0, - [DIFF_DELETE, lastequality]); - // Change second copy to insert. - diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; - // Throw away the equality we just deleted. - equalitiesLength--; - // Throw away the previous equality (it needs to be reevaluated). - equalitiesLength--; - pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; - length_insertions1 = 0; // Reset the counters. - length_deletions1 = 0; - length_insertions2 = 0; - length_deletions2 = 0; - lastequality = null; - changes = true; - } - } - pointer++; - } - - // Normalize the diff. - if (changes) { - this.diff_cleanupMerge(diffs); - } - this.diff_cleanupSemanticLossless(diffs); - - // Find any overlaps between deletions and insertions. - // e.g: abcxxxxxxdef - // -> abcxxxdef - // e.g: xxxabcdefxxx - // -> defxxxabc - // Only extract an overlap if it is as big as the edit ahead or behind it. - pointer = 1; - while (pointer < diffs.length) { - if (diffs[pointer - 1][0] == DIFF_DELETE && - diffs[pointer][0] == DIFF_INSERT) { - var deletion = diffs[pointer - 1][1]; - var insertion = diffs[pointer][1]; - var overlap_length1 = this.diff_commonOverlap_(deletion, insertion); - var overlap_length2 = this.diff_commonOverlap_(insertion, deletion); - if (overlap_length1 >= overlap_length2) { - if (overlap_length1 >= deletion.length / 2 || - overlap_length1 >= insertion.length / 2) { - // Overlap found. Insert an equality and trim the surrounding edits. - diffs.splice(pointer, 0, - [DIFF_EQUAL, insertion.substring(0, overlap_length1)]); - diffs[pointer - 1][1] = - deletion.substring(0, deletion.length - overlap_length1); - diffs[pointer + 1][1] = insertion.substring(overlap_length1); - pointer++; - } - } else { - if (overlap_length2 >= deletion.length / 2 || - overlap_length2 >= insertion.length / 2) { - // Reverse overlap found. - // Insert an equality and swap and trim the surrounding edits. - diffs.splice(pointer, 0, - [DIFF_EQUAL, deletion.substring(0, overlap_length2)]); - diffs[pointer - 1][0] = DIFF_INSERT; - diffs[pointer - 1][1] = - insertion.substring(0, insertion.length - overlap_length2); - diffs[pointer + 1][0] = DIFF_DELETE; - diffs[pointer + 1][1] = - deletion.substring(overlap_length2); - pointer++; - } - } - pointer++; - } - pointer++; - } -}; - - -/** - * Look for single edits surrounded on both sides by equalities - * which can be shifted sideways to align the edit to a word boundary. - * e.g: The cat came. -> The cat came. - * @param {!Array.} diffs Array of diff tuples. - */ -diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) { - /** - * Given two strings, compute a score representing whether the internal - * boundary falls on logical boundaries. - * Scores range from 6 (best) to 0 (worst). - * Closure, but does not reference any external variables. - * @param {string} one First string. - * @param {string} two Second string. - * @return {number} The score. - * @private - */ - function diff_cleanupSemanticScore_(one, two) { - if (!one || !two) { - // Edges are the best. - return 6; - } - - // Each port of this function behaves slightly differently due to - // subtle differences in each language's definition of things like - // 'whitespace'. Since this function's purpose is largely cosmetic, - // the choice has been made to use each language's native features - // rather than force total conformity. - var char1 = one.charAt(one.length - 1); - var char2 = two.charAt(0); - var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_); - var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_); - var whitespace1 = nonAlphaNumeric1 && - char1.match(diff_match_patch.whitespaceRegex_); - var whitespace2 = nonAlphaNumeric2 && - char2.match(diff_match_patch.whitespaceRegex_); - var lineBreak1 = whitespace1 && - char1.match(diff_match_patch.linebreakRegex_); - var lineBreak2 = whitespace2 && - char2.match(diff_match_patch.linebreakRegex_); - var blankLine1 = lineBreak1 && - one.match(diff_match_patch.blanklineEndRegex_); - var blankLine2 = lineBreak2 && - two.match(diff_match_patch.blanklineStartRegex_); - - if (blankLine1 || blankLine2) { - // Five points for blank lines. - return 5; - } else if (lineBreak1 || lineBreak2) { - // Four points for line breaks. - return 4; - } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { - // Three points for end of sentences. - return 3; - } else if (whitespace1 || whitespace2) { - // Two points for whitespace. - return 2; - } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { - // One point for non-alphanumeric. - return 1; - } - return 0; - } - - var pointer = 1; - // Intentionally ignore the first and last element (don't need checking). - while (pointer < diffs.length - 1) { - if (diffs[pointer - 1][0] == DIFF_EQUAL && - diffs[pointer + 1][0] == DIFF_EQUAL) { - // This is a single edit surrounded by equalities. - var equality1 = diffs[pointer - 1][1]; - var edit = diffs[pointer][1]; - var equality2 = diffs[pointer + 1][1]; - - // First, shift the edit as far left as possible. - var commonOffset = this.diff_commonSuffix(equality1, edit); - if (commonOffset) { - var commonString = edit.substring(edit.length - commonOffset); - equality1 = equality1.substring(0, equality1.length - commonOffset); - edit = commonString + edit.substring(0, edit.length - commonOffset); - equality2 = commonString + equality2; - } - - // Second, step character by character right, looking for the best fit. - var bestEquality1 = equality1; - var bestEdit = edit; - var bestEquality2 = equality2; - var bestScore = diff_cleanupSemanticScore_(equality1, edit) + - diff_cleanupSemanticScore_(edit, equality2); - while (edit.charAt(0) === equality2.charAt(0)) { - equality1 += edit.charAt(0); - edit = edit.substring(1) + equality2.charAt(0); - equality2 = equality2.substring(1); - var score = diff_cleanupSemanticScore_(equality1, edit) + - diff_cleanupSemanticScore_(edit, equality2); - // The >= encourages trailing rather than leading whitespace on edits. - if (score >= bestScore) { - bestScore = score; - bestEquality1 = equality1; - bestEdit = edit; - bestEquality2 = equality2; - } - } - - if (diffs[pointer - 1][1] != bestEquality1) { - // We have an improvement, save it back to the diff. - if (bestEquality1) { - diffs[pointer - 1][1] = bestEquality1; - } else { - diffs.splice(pointer - 1, 1); - pointer--; - } - diffs[pointer][1] = bestEdit; - if (bestEquality2) { - diffs[pointer + 1][1] = bestEquality2; - } else { - diffs.splice(pointer + 1, 1); - pointer--; - } - } - } - pointer++; - } -}; - -// Define some regex patterns for matching boundaries. -diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; -diff_match_patch.whitespaceRegex_ = /\s/; -diff_match_patch.linebreakRegex_ = /[\r\n]/; -diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/; -diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/; - -/** - * Reduce the number of edits by eliminating operationally trivial equalities. - * @param {!Array.} diffs Array of diff tuples. - */ -diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) { - var changes = false; - var equalities = []; // Stack of indices where equalities are found. - var equalitiesLength = 0; // Keeping our own length var is faster in JS. - /** @type {?string} */ - var lastequality = null; - // Always equal to diffs[equalities[equalitiesLength - 1]][1] - var pointer = 0; // Index of current position. - // Is there an insertion operation before the last equality. - var pre_ins = false; - // Is there a deletion operation before the last equality. - var pre_del = false; - // Is there an insertion operation after the last equality. - var post_ins = false; - // Is there a deletion operation after the last equality. - var post_del = false; - while (pointer < diffs.length) { - if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. - if (diffs[pointer][1].length < this.Diff_EditCost && - (post_ins || post_del)) { - // Candidate found. - equalities[equalitiesLength++] = pointer; - pre_ins = post_ins; - pre_del = post_del; - lastequality = diffs[pointer][1]; - } else { - // Not a candidate, and can never become one. - equalitiesLength = 0; - lastequality = null; - } - post_ins = post_del = false; - } else { // An insertion or deletion. - if (diffs[pointer][0] == DIFF_DELETE) { - post_del = true; - } else { - post_ins = true; - } - /* - * Five types to be split: - * ABXYCD - * AXCD - * ABXC - * AXCD - * ABXC - */ - if (lastequality && ((pre_ins && pre_del && post_ins && post_del) || - ((lastequality.length < this.Diff_EditCost / 2) && - (pre_ins + pre_del + post_ins + post_del) == 3))) { - // Duplicate record. - diffs.splice(equalities[equalitiesLength - 1], 0, - [DIFF_DELETE, lastequality]); - // Change second copy to insert. - diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; - equalitiesLength--; // Throw away the equality we just deleted; - lastequality = null; - if (pre_ins && pre_del) { - // No changes made which could affect previous entry, keep going. - post_ins = post_del = true; - equalitiesLength = 0; - } else { - equalitiesLength--; // Throw away the previous equality. - pointer = equalitiesLength > 0 ? - equalities[equalitiesLength - 1] : -1; - post_ins = post_del = false; - } - changes = true; - } - } - pointer++; - } - - if (changes) { - this.diff_cleanupMerge(diffs); - } -}; - - -/** - * Reorder and merge like edit sections. Merge equalities. - * Any edit section can move as long as it doesn't cross an equality. - * @param {!Array.} diffs Array of diff tuples. - */ -diff_match_patch.prototype.diff_cleanupMerge = function(diffs) { - diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end. - var pointer = 0; - var count_delete = 0; - var count_insert = 0; - var text_delete = ''; - var text_insert = ''; - var commonlength; - while (pointer < diffs.length) { - switch (diffs[pointer][0]) { - case DIFF_INSERT: - count_insert++; - text_insert += diffs[pointer][1]; - pointer++; - break; - case DIFF_DELETE: - count_delete++; - text_delete += diffs[pointer][1]; - pointer++; - break; - case DIFF_EQUAL: - // Upon reaching an equality, check for prior redundancies. - if (count_delete + count_insert > 1) { - if (count_delete !== 0 && count_insert !== 0) { - // Factor out any common prefixies. - commonlength = this.diff_commonPrefix(text_insert, text_delete); - if (commonlength !== 0) { - if ((pointer - count_delete - count_insert) > 0 && - diffs[pointer - count_delete - count_insert - 1][0] == - DIFF_EQUAL) { - diffs[pointer - count_delete - count_insert - 1][1] += - text_insert.substring(0, commonlength); - } else { - diffs.splice(0, 0, [DIFF_EQUAL, - text_insert.substring(0, commonlength)]); - pointer++; - } - text_insert = text_insert.substring(commonlength); - text_delete = text_delete.substring(commonlength); - } - // Factor out any common suffixies. - commonlength = this.diff_commonSuffix(text_insert, text_delete); - if (commonlength !== 0) { - diffs[pointer][1] = text_insert.substring(text_insert.length - - commonlength) + diffs[pointer][1]; - text_insert = text_insert.substring(0, text_insert.length - - commonlength); - text_delete = text_delete.substring(0, text_delete.length - - commonlength); - } - } - // Delete the offending records and add the merged ones. - if (count_delete === 0) { - diffs.splice(pointer - count_insert, - count_delete + count_insert, [DIFF_INSERT, text_insert]); - } else if (count_insert === 0) { - diffs.splice(pointer - count_delete, - count_delete + count_insert, [DIFF_DELETE, text_delete]); - } else { - diffs.splice(pointer - count_delete - count_insert, - count_delete + count_insert, [DIFF_DELETE, text_delete], - [DIFF_INSERT, text_insert]); - } - pointer = pointer - count_delete - count_insert + - (count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1; - } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { - // Merge this equality with the previous one. - diffs[pointer - 1][1] += diffs[pointer][1]; - diffs.splice(pointer, 1); - } else { - pointer++; - } - count_insert = 0; - count_delete = 0; - text_delete = ''; - text_insert = ''; - break; - } - } - if (diffs[diffs.length - 1][1] === '') { - diffs.pop(); // Remove the dummy entry at the end. - } - - // Second pass: look for single edits surrounded on both sides by equalities - // which can be shifted sideways to eliminate an equality. - // e.g: ABAC -> ABAC - var changes = false; - pointer = 1; - // Intentionally ignore the first and last element (don't need checking). - while (pointer < diffs.length - 1) { - if (diffs[pointer - 1][0] == DIFF_EQUAL && - diffs[pointer + 1][0] == DIFF_EQUAL) { - // This is a single edit surrounded by equalities. - if (diffs[pointer][1].substring(diffs[pointer][1].length - - diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) { - // Shift the edit over the previous equality. - diffs[pointer][1] = diffs[pointer - 1][1] + - diffs[pointer][1].substring(0, diffs[pointer][1].length - - diffs[pointer - 1][1].length); - diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; - diffs.splice(pointer - 1, 1); - changes = true; - } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == - diffs[pointer + 1][1]) { - // Shift the edit over the next equality. - diffs[pointer - 1][1] += diffs[pointer + 1][1]; - diffs[pointer][1] = - diffs[pointer][1].substring(diffs[pointer + 1][1].length) + - diffs[pointer + 1][1]; - diffs.splice(pointer + 1, 1); - changes = true; - } - } - pointer++; - } - // If shifts were made, the diff needs reordering and another shift sweep. - if (changes) { - this.diff_cleanupMerge(diffs); - } -}; - - -/** - * loc is a location in text1, compute and return the equivalent location in - * text2. - * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 - * @param {!Array.} diffs Array of diff tuples. - * @param {number} loc Location within text1. - * @return {number} Location within text2. - */ -diff_match_patch.prototype.diff_xIndex = function(diffs, loc) { - var chars1 = 0; - var chars2 = 0; - var last_chars1 = 0; - var last_chars2 = 0; - var x; - for (x = 0; x < diffs.length; x++) { - if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion. - chars1 += diffs[x][1].length; - } - if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion. - chars2 += diffs[x][1].length; - } - if (chars1 > loc) { // Overshot the location. - break; - } - last_chars1 = chars1; - last_chars2 = chars2; - } - // Was the location was deleted? - if (diffs.length != x && diffs[x][0] === DIFF_DELETE) { - return last_chars2; - } - // Add the remaining character length. - return last_chars2 + (loc - last_chars1); -}; - - -/** - * Convert a diff array into a pretty HTML report. - * @param {!Array.} diffs Array of diff tuples. - * @return {string} HTML representation. - */ -diff_match_patch.prototype.diff_prettyHtml = function(diffs) { - var html = []; - var pattern_amp = /&/g; - var pattern_lt = //g; - var pattern_para = /\n/g; - for (var x = 0; x < diffs.length; x++) { - var op = diffs[x][0]; // Operation (insert, delete, equal) - var data = diffs[x][1]; // Text of change. - var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<') - .replace(pattern_gt, '>').replace(pattern_para, '¶
'); - switch (op) { - case DIFF_INSERT: - html[x] = '' + text + ''; - break; - case DIFF_DELETE: - html[x] = '' + text + ''; - break; - case DIFF_EQUAL: - html[x] = '' + text + ''; - break; - } - } - return html.join(''); -}; - - -/** - * Compute and return the source text (all equalities and deletions). - * @param {!Array.} diffs Array of diff tuples. - * @return {string} Source text. - */ -diff_match_patch.prototype.diff_text1 = function(diffs) { - var text = []; - for (var x = 0; x < diffs.length; x++) { - if (diffs[x][0] !== DIFF_INSERT) { - text[x] = diffs[x][1]; - } - } - return text.join(''); -}; - - -/** - * Compute and return the destination text (all equalities and insertions). - * @param {!Array.} diffs Array of diff tuples. - * @return {string} Destination text. - */ -diff_match_patch.prototype.diff_text2 = function(diffs) { - var text = []; - for (var x = 0; x < diffs.length; x++) { - if (diffs[x][0] !== DIFF_DELETE) { - text[x] = diffs[x][1]; - } - } - return text.join(''); -}; - - -/** - * Compute the Levenshtein distance; the number of inserted, deleted or - * substituted characters. - * @param {!Array.} diffs Array of diff tuples. - * @return {number} Number of changes. - */ -diff_match_patch.prototype.diff_levenshtein = function(diffs) { - var levenshtein = 0; - var insertions = 0; - var deletions = 0; - for (var x = 0; x < diffs.length; x++) { - var op = diffs[x][0]; - var data = diffs[x][1]; - switch (op) { - case DIFF_INSERT: - insertions += data.length; - break; - case DIFF_DELETE: - deletions += data.length; - break; - case DIFF_EQUAL: - // A deletion and an insertion is one substitution. - levenshtein += Math.max(insertions, deletions); - insertions = 0; - deletions = 0; - break; - } - } - levenshtein += Math.max(insertions, deletions); - return levenshtein; -}; - - -/** - * Crush the diff into an encoded string which describes the operations - * required to transform text1 into text2. - * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. - * Operations are tab-separated. Inserted text is escaped using %xx notation. - * @param {!Array.} diffs Array of diff tuples. - * @return {string} Delta text. - */ -diff_match_patch.prototype.diff_toDelta = function(diffs) { - var text = []; - for (var x = 0; x < diffs.length; x++) { - switch (diffs[x][0]) { - case DIFF_INSERT: - text[x] = '+' + encodeURI(diffs[x][1]); - break; - case DIFF_DELETE: - text[x] = '-' + diffs[x][1].length; - break; - case DIFF_EQUAL: - text[x] = '=' + diffs[x][1].length; - break; - } - } - return text.join('\t').replace(/%20/g, ' '); -}; - - -/** - * Given the original text1, and an encoded string which describes the - * operations required to transform text1 into text2, compute the full diff. - * @param {string} text1 Source string for the diff. - * @param {string} delta Delta text. - * @return {!Array.} Array of diff tuples. - * @throws {!Error} If invalid input. - */ -diff_match_patch.prototype.diff_fromDelta = function(text1, delta) { - var diffs = []; - var diffsLength = 0; // Keeping our own length var is faster in JS. - var pointer = 0; // Cursor in text1 - var tokens = delta.split(/\t/g); - for (var x = 0; x < tokens.length; x++) { - // Each token begins with a one character parameter which specifies the - // operation of this token (delete, insert, equality). - var param = tokens[x].substring(1); - switch (tokens[x].charAt(0)) { - case '+': - try { - diffs[diffsLength++] = [DIFF_INSERT, decodeURI(param)]; - } catch (ex) { - // Malformed URI sequence. - throw new Error('Illegal escape in diff_fromDelta: ' + param); - } - break; - case '-': - // Fall through. - case '=': - var n = parseInt(param, 10); - if (isNaN(n) || n < 0) { - throw new Error('Invalid number in diff_fromDelta: ' + param); - } - var text = text1.substring(pointer, pointer += n); - if (tokens[x].charAt(0) == '=') { - diffs[diffsLength++] = [DIFF_EQUAL, text]; - } else { - diffs[diffsLength++] = [DIFF_DELETE, text]; - } - break; - default: - // Blank tokens are ok (from a trailing \t). - // Anything else is an error. - if (tokens[x]) { - throw new Error('Invalid diff operation in diff_fromDelta: ' + - tokens[x]); - } - } - } - if (pointer != text1.length) { - throw new Error('Delta length (' + pointer + - ') does not equal source text length (' + text1.length + ').'); - } - return diffs; -}; - - -// MATCH FUNCTIONS - - -/** - * Locate the best instance of 'pattern' in 'text' near 'loc'. - * @param {string} text The text to search. - * @param {string} pattern The pattern to search for. - * @param {number} loc The location to search around. - * @return {number} Best match index or -1. - */ -diff_match_patch.prototype.match_main = function(text, pattern, loc) { - // Check for null inputs. - if (text == null || pattern == null || loc == null) { - throw new Error('Null input. (match_main)'); - } - - loc = Math.max(0, Math.min(loc, text.length)); - if (text == pattern) { - // Shortcut (potentially not guaranteed by the algorithm) - return 0; - } else if (!text.length) { - // Nothing to match. - return -1; - } else if (text.substring(loc, loc + pattern.length) == pattern) { - // Perfect match at the perfect spot! (Includes case of null pattern) - return loc; - } else { - // Do a fuzzy compare. - return this.match_bitap_(text, pattern, loc); - } -}; - - -/** - * Locate the best instance of 'pattern' in 'text' near 'loc' using the - * Bitap algorithm. - * @param {string} text The text to search. - * @param {string} pattern The pattern to search for. - * @param {number} loc The location to search around. - * @return {number} Best match index or -1. - * @private - */ -diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) { - if (pattern.length > this.Match_MaxBits) { - throw new Error('Pattern too long for this browser.'); - } - - // Initialise the alphabet. - var s = this.match_alphabet_(pattern); - - var dmp = this; // 'this' becomes 'window' in a closure. - - /** - * Compute and return the score for a match with e errors and x location. - * Accesses loc and pattern through being a closure. - * @param {number} e Number of errors in match. - * @param {number} x Location of match. - * @return {number} Overall score for match (0.0 = good, 1.0 = bad). - * @private - */ - function match_bitapScore_(e, x) { - var accuracy = e / pattern.length; - var proximity = Math.abs(loc - x); - if (!dmp.Match_Distance) { - // Dodge divide by zero error. - return proximity ? 1.0 : accuracy; - } - return accuracy + (proximity / dmp.Match_Distance); - } - - // Highest score beyond which we give up. - var score_threshold = this.Match_Threshold; - // Is there a nearby exact match? (speedup) - var best_loc = text.indexOf(pattern, loc); - if (best_loc != -1) { - score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); - // What about in the other direction? (speedup) - best_loc = text.lastIndexOf(pattern, loc + pattern.length); - if (best_loc != -1) { - score_threshold = - Math.min(match_bitapScore_(0, best_loc), score_threshold); - } - } - - // Initialise the bit arrays. - var matchmask = 1 << (pattern.length - 1); - best_loc = -1; - - var bin_min, bin_mid; - var bin_max = pattern.length + text.length; - var last_rd; - for (var d = 0; d < pattern.length; d++) { - // Scan for the best match; each iteration allows for one more error. - // Run a binary search to determine how far from 'loc' we can stray at this - // error level. - bin_min = 0; - bin_mid = bin_max; - while (bin_min < bin_mid) { - if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) { - bin_min = bin_mid; - } else { - bin_max = bin_mid; - } - bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); - } - // Use the result from this iteration as the maximum for the next. - bin_max = bin_mid; - var start = Math.max(1, loc - bin_mid + 1); - var finish = Math.min(loc + bin_mid, text.length) + pattern.length; - - var rd = Array(finish + 2); - rd[finish + 1] = (1 << d) - 1; - for (var j = finish; j >= start; j--) { - // The alphabet (s) is a sparse hash, so the following line generates - // warnings. - var charMatch = s[text.charAt(j - 1)]; - if (d === 0) { // First pass: exact match. - rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; - } else { // Subsequent passes: fuzzy match. - rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | - (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | - last_rd[j + 1]; - } - if (rd[j] & matchmask) { - var score = match_bitapScore_(d, j - 1); - // This match will almost certainly be better than any existing match. - // But check anyway. - if (score <= score_threshold) { - // Told you so. - score_threshold = score; - best_loc = j - 1; - if (best_loc > loc) { - // When passing loc, don't exceed our current distance from loc. - start = Math.max(1, 2 * loc - best_loc); - } else { - // Already passed loc, downhill from here on in. - break; - } - } - } - } - // No hope for a (better) match at greater error levels. - if (match_bitapScore_(d + 1, loc) > score_threshold) { - break; - } - last_rd = rd; - } - return best_loc; -}; - - -/** - * Initialise the alphabet for the Bitap algorithm. - * @param {string} pattern The text to encode. - * @return {!Object} Hash of character locations. - * @private - */ -diff_match_patch.prototype.match_alphabet_ = function(pattern) { - var s = {}; - for (var i = 0; i < pattern.length; i++) { - s[pattern.charAt(i)] = 0; - } - for (var i = 0; i < pattern.length; i++) { - s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1); - } - return s; -}; - - -// PATCH FUNCTIONS - - -/** - * Increase the context until it is unique, - * but don't let the pattern expand beyond Match_MaxBits. - * @param {!diff_match_patch.patch_obj} patch The patch to grow. - * @param {string} text Source text. - * @private - */ -diff_match_patch.prototype.patch_addContext_ = function(patch, text) { - if (text.length == 0) { - return; - } - var pattern = text.substring(patch.start2, patch.start2 + patch.length1); - var padding = 0; - - // Look for the first and last matches of pattern in text. If two different - // matches are found, increase the pattern length. - while (text.indexOf(pattern) != text.lastIndexOf(pattern) && - pattern.length < this.Match_MaxBits - this.Patch_Margin - - this.Patch_Margin) { - padding += this.Patch_Margin; - pattern = text.substring(patch.start2 - padding, - patch.start2 + patch.length1 + padding); - } - // Add one chunk for good luck. - padding += this.Patch_Margin; - - // Add the prefix. - var prefix = text.substring(patch.start2 - padding, patch.start2); - if (prefix) { - patch.diffs.unshift([DIFF_EQUAL, prefix]); - } - // Add the suffix. - var suffix = text.substring(patch.start2 + patch.length1, - patch.start2 + patch.length1 + padding); - if (suffix) { - patch.diffs.push([DIFF_EQUAL, suffix]); - } - - // Roll back the start points. - patch.start1 -= prefix.length; - patch.start2 -= prefix.length; - // Extend the lengths. - patch.length1 += prefix.length + suffix.length; - patch.length2 += prefix.length + suffix.length; -}; - - -/** - * Compute a list of patches to turn text1 into text2. - * Use diffs if provided, otherwise compute it ourselves. - * There are four ways to call this function, depending on what data is - * available to the caller: - * Method 1: - * a = text1, b = text2 - * Method 2: - * a = diffs - * Method 3 (optimal): - * a = text1, b = diffs - * Method 4 (deprecated, use method 3): - * a = text1, b = text2, c = diffs - * - * @param {string|!Array.} a text1 (methods 1,3,4) or - * Array of diff tuples for text1 to text2 (method 2). - * @param {string|!Array.} opt_b text2 (methods 1,4) or - * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). - * @param {string|!Array.} opt_c Array of diff tuples - * for text1 to text2 (method 4) or undefined (methods 1,2,3). - * @return {!Array.} Array of Patch objects. - */ -diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) { - var text1, diffs; - if (typeof a == 'string' && typeof opt_b == 'string' && - typeof opt_c == 'undefined') { - // Method 1: text1, text2 - // Compute diffs from text1 and text2. - text1 = /** @type {string} */(a); - diffs = this.diff_main(text1, /** @type {string} */(opt_b), true); - if (diffs.length > 2) { - this.diff_cleanupSemantic(diffs); - this.diff_cleanupEfficiency(diffs); - } - } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' && - typeof opt_c == 'undefined') { - // Method 2: diffs - // Compute text1 from diffs. - diffs = /** @type {!Array.} */(a); - text1 = this.diff_text1(diffs); - } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' && - typeof opt_c == 'undefined') { - // Method 3: text1, diffs - text1 = /** @type {string} */(a); - diffs = /** @type {!Array.} */(opt_b); - } else if (typeof a == 'string' && typeof opt_b == 'string' && - opt_c && typeof opt_c == 'object') { - // Method 4: text1, text2, diffs - // text2 is not used. - text1 = /** @type {string} */(a); - diffs = /** @type {!Array.} */(opt_c); - } else { - throw new Error('Unknown call format to patch_make.'); - } - - if (diffs.length === 0) { - return []; // Get rid of the null case. - } - var patches = []; - var patch = new diff_match_patch.patch_obj(); - var patchDiffLength = 0; // Keeping our own length var is faster in JS. - var char_count1 = 0; // Number of characters into the text1 string. - var char_count2 = 0; // Number of characters into the text2 string. - // Start with text1 (prepatch_text) and apply the diffs until we arrive at - // text2 (postpatch_text). We recreate the patches one by one to determine - // context info. - var prepatch_text = text1; - var postpatch_text = text1; - for (var x = 0; x < diffs.length; x++) { - var diff_type = diffs[x][0]; - var diff_text = diffs[x][1]; - - if (!patchDiffLength && diff_type !== DIFF_EQUAL) { - // A new patch starts here. - patch.start1 = char_count1; - patch.start2 = char_count2; - } - - switch (diff_type) { - case DIFF_INSERT: - patch.diffs[patchDiffLength++] = diffs[x]; - patch.length2 += diff_text.length; - postpatch_text = postpatch_text.substring(0, char_count2) + diff_text + - postpatch_text.substring(char_count2); - break; - case DIFF_DELETE: - patch.length1 += diff_text.length; - patch.diffs[patchDiffLength++] = diffs[x]; - postpatch_text = postpatch_text.substring(0, char_count2) + - postpatch_text.substring(char_count2 + - diff_text.length); - break; - case DIFF_EQUAL: - if (diff_text.length <= 2 * this.Patch_Margin && - patchDiffLength && diffs.length != x + 1) { - // Small equality inside a patch. - patch.diffs[patchDiffLength++] = diffs[x]; - patch.length1 += diff_text.length; - patch.length2 += diff_text.length; - } else if (diff_text.length >= 2 * this.Patch_Margin) { - // Time for a new patch. - if (patchDiffLength) { - this.patch_addContext_(patch, prepatch_text); - patches.push(patch); - patch = new diff_match_patch.patch_obj(); - patchDiffLength = 0; - // Unlike Unidiff, our patch lists have a rolling context. - // http://code.google.com/p/google-diff-match-patch/wiki/Unidiff - // Update prepatch text & pos to reflect the application of the - // just completed patch. - prepatch_text = postpatch_text; - char_count1 = char_count2; - } - } - break; - } - - // Update the current character count. - if (diff_type !== DIFF_INSERT) { - char_count1 += diff_text.length; - } - if (diff_type !== DIFF_DELETE) { - char_count2 += diff_text.length; - } - } - // Pick up the leftover patch if not empty. - if (patchDiffLength) { - this.patch_addContext_(patch, prepatch_text); - patches.push(patch); - } - - return patches; -}; - - -/** - * Given an array of patches, return another array that is identical. - * @param {!Array.} patches Array of Patch objects. - * @return {!Array.} Array of Patch objects. - */ -diff_match_patch.prototype.patch_deepCopy = function(patches) { - // Making deep copies is hard in JavaScript. - var patchesCopy = []; - for (var x = 0; x < patches.length; x++) { - var patch = patches[x]; - var patchCopy = new diff_match_patch.patch_obj(); - patchCopy.diffs = []; - for (var y = 0; y < patch.diffs.length; y++) { - patchCopy.diffs[y] = patch.diffs[y].slice(); - } - patchCopy.start1 = patch.start1; - patchCopy.start2 = patch.start2; - patchCopy.length1 = patch.length1; - patchCopy.length2 = patch.length2; - patchesCopy[x] = patchCopy; - } - return patchesCopy; -}; - - -/** - * Merge a set of patches onto the text. Return a patched text, as well - * as a list of true/false values indicating which patches were applied. - * @param {!Array.} patches Array of Patch objects. - * @param {string} text Old text. - * @return {!Array.>} Two element Array, containing the - * new text and an array of boolean values. - */ -diff_match_patch.prototype.patch_apply = function(patches, text) { - if (patches.length == 0) { - return [text, []]; - } - - // Deep copy the patches so that no changes are made to originals. - patches = this.patch_deepCopy(patches); - - var nullPadding = this.patch_addPadding(patches); - text = nullPadding + text + nullPadding; - - this.patch_splitMax(patches); - // delta keeps track of the offset between the expected and actual location - // of the previous patch. If there are patches expected at positions 10 and - // 20, but the first patch was found at 12, delta is 2 and the second patch - // has an effective expected position of 22. - var delta = 0; - var results = []; - for (var x = 0; x < patches.length; x++) { - var expected_loc = patches[x].start2 + delta; - var text1 = this.diff_text1(patches[x].diffs); - var start_loc; - var end_loc = -1; - if (text1.length > this.Match_MaxBits) { - // patch_splitMax will only provide an oversized pattern in the case of - // a monster delete. - start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits), - expected_loc); - if (start_loc != -1) { - end_loc = this.match_main(text, - text1.substring(text1.length - this.Match_MaxBits), - expected_loc + text1.length - this.Match_MaxBits); - if (end_loc == -1 || start_loc >= end_loc) { - // Can't find valid trailing context. Drop this patch. - start_loc = -1; - } - } - } else { - start_loc = this.match_main(text, text1, expected_loc); - } - if (start_loc == -1) { - // No match found. :( - results[x] = false; - // Subtract the delta for this failed patch from subsequent patches. - delta -= patches[x].length2 - patches[x].length1; - } else { - // Found a match. :) - results[x] = true; - delta = start_loc - expected_loc; - var text2; - if (end_loc == -1) { - text2 = text.substring(start_loc, start_loc + text1.length); - } else { - text2 = text.substring(start_loc, end_loc + this.Match_MaxBits); - } - if (text1 == text2) { - // Perfect match, just shove the replacement text in. - text = text.substring(0, start_loc) + - this.diff_text2(patches[x].diffs) + - text.substring(start_loc + text1.length); - } else { - // Imperfect match. Run a diff to get a framework of equivalent - // indices. - var diffs = this.diff_main(text1, text2, false); - if (text1.length > this.Match_MaxBits && - this.diff_levenshtein(diffs) / text1.length > - this.Patch_DeleteThreshold) { - // The end points match, but the content is unacceptably bad. - results[x] = false; - } else { - this.diff_cleanupSemanticLossless(diffs); - var index1 = 0; - var index2; - for (var y = 0; y < patches[x].diffs.length; y++) { - var mod = patches[x].diffs[y]; - if (mod[0] !== DIFF_EQUAL) { - index2 = this.diff_xIndex(diffs, index1); - } - if (mod[0] === DIFF_INSERT) { // Insertion - text = text.substring(0, start_loc + index2) + mod[1] + - text.substring(start_loc + index2); - } else if (mod[0] === DIFF_DELETE) { // Deletion - text = text.substring(0, start_loc + index2) + - text.substring(start_loc + this.diff_xIndex(diffs, - index1 + mod[1].length)); - } - if (mod[0] !== DIFF_DELETE) { - index1 += mod[1].length; - } - } - } - } - } - } - // Strip the padding off. - text = text.substring(nullPadding.length, text.length - nullPadding.length); - return [text, results]; -}; - - -/** - * Add some padding on text start and end so that edges can match something. - * Intended to be called only from within patch_apply. - * @param {!Array.} patches Array of Patch objects. - * @return {string} The padding string added to each side. - */ -diff_match_patch.prototype.patch_addPadding = function(patches) { - var paddingLength = this.Patch_Margin; - var nullPadding = ''; - for (var x = 1; x <= paddingLength; x++) { - nullPadding += String.fromCharCode(x); - } - - // Bump all the patches forward. - for (var x = 0; x < patches.length; x++) { - patches[x].start1 += paddingLength; - patches[x].start2 += paddingLength; - } - - // Add some padding on start of first diff. - var patch = patches[0]; - var diffs = patch.diffs; - if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) { - // Add nullPadding equality. - diffs.unshift([DIFF_EQUAL, nullPadding]); - patch.start1 -= paddingLength; // Should be 0. - patch.start2 -= paddingLength; // Should be 0. - patch.length1 += paddingLength; - patch.length2 += paddingLength; - } else if (paddingLength > diffs[0][1].length) { - // Grow first equality. - var extraLength = paddingLength - diffs[0][1].length; - diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1]; - patch.start1 -= extraLength; - patch.start2 -= extraLength; - patch.length1 += extraLength; - patch.length2 += extraLength; - } - - // Add some padding on end of last diff. - patch = patches[patches.length - 1]; - diffs = patch.diffs; - if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) { - // Add nullPadding equality. - diffs.push([DIFF_EQUAL, nullPadding]); - patch.length1 += paddingLength; - patch.length2 += paddingLength; - } else if (paddingLength > diffs[diffs.length - 1][1].length) { - // Grow last equality. - var extraLength = paddingLength - diffs[diffs.length - 1][1].length; - diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength); - patch.length1 += extraLength; - patch.length2 += extraLength; - } - - return nullPadding; -}; - - -/** - * Look through the patches and break up any which are longer than the maximum - * limit of the match algorithm. - * Intended to be called only from within patch_apply. - * @param {!Array.} patches Array of Patch objects. - */ -diff_match_patch.prototype.patch_splitMax = function(patches) { - var patch_size = this.Match_MaxBits; - for (var x = 0; x < patches.length; x++) { - if (patches[x].length1 <= patch_size) { - continue; - } - var bigpatch = patches[x]; - // Remove the big old patch. - patches.splice(x--, 1); - var start1 = bigpatch.start1; - var start2 = bigpatch.start2; - var precontext = ''; - while (bigpatch.diffs.length !== 0) { - // Create one of several smaller patches. - var patch = new diff_match_patch.patch_obj(); - var empty = true; - patch.start1 = start1 - precontext.length; - patch.start2 = start2 - precontext.length; - if (precontext !== '') { - patch.length1 = patch.length2 = precontext.length; - patch.diffs.push([DIFF_EQUAL, precontext]); - } - while (bigpatch.diffs.length !== 0 && - patch.length1 < patch_size - this.Patch_Margin) { - var diff_type = bigpatch.diffs[0][0]; - var diff_text = bigpatch.diffs[0][1]; - if (diff_type === DIFF_INSERT) { - // Insertions are harmless. - patch.length2 += diff_text.length; - start2 += diff_text.length; - patch.diffs.push(bigpatch.diffs.shift()); - empty = false; - } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 && - patch.diffs[0][0] == DIFF_EQUAL && - diff_text.length > 2 * patch_size) { - // This is a large deletion. Let it pass in one chunk. - patch.length1 += diff_text.length; - start1 += diff_text.length; - empty = false; - patch.diffs.push([diff_type, diff_text]); - bigpatch.diffs.shift(); - } else { - // Deletion or equality. Only take as much as we can stomach. - diff_text = diff_text.substring(0, - patch_size - patch.length1 - this.Patch_Margin); - patch.length1 += diff_text.length; - start1 += diff_text.length; - if (diff_type === DIFF_EQUAL) { - patch.length2 += diff_text.length; - start2 += diff_text.length; - } else { - empty = false; - } - patch.diffs.push([diff_type, diff_text]); - if (diff_text == bigpatch.diffs[0][1]) { - bigpatch.diffs.shift(); - } else { - bigpatch.diffs[0][1] = - bigpatch.diffs[0][1].substring(diff_text.length); - } - } - } - // Compute the head context for the next patch. - precontext = this.diff_text2(patch.diffs); - precontext = - precontext.substring(precontext.length - this.Patch_Margin); - // Append the end context for this patch. - var postcontext = this.diff_text1(bigpatch.diffs) - .substring(0, this.Patch_Margin); - if (postcontext !== '') { - patch.length1 += postcontext.length; - patch.length2 += postcontext.length; - if (patch.diffs.length !== 0 && - patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) { - patch.diffs[patch.diffs.length - 1][1] += postcontext; - } else { - patch.diffs.push([DIFF_EQUAL, postcontext]); - } - } - if (!empty) { - patches.splice(++x, 0, patch); - } - } - } -}; - - -/** - * Take a list of patches and return a textual representation. - * @param {!Array.} patches Array of Patch objects. - * @return {string} Text representation of patches. - */ -diff_match_patch.prototype.patch_toText = function(patches) { - var text = []; - for (var x = 0; x < patches.length; x++) { - text[x] = patches[x]; - } - return text.join(''); -}; - - -/** - * Parse a textual representation of patches and return a list of Patch objects. - * @param {string} textline Text representation of patches. - * @return {!Array.} Array of Patch objects. - * @throws {!Error} If invalid input. - */ -diff_match_patch.prototype.patch_fromText = function(textline) { - var patches = []; - if (!textline) { - return patches; - } - var text = textline.split('\n'); - var textPointer = 0; - var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; - while (textPointer < text.length) { - var m = text[textPointer].match(patchHeader); - if (!m) { - throw new Error('Invalid patch string: ' + text[textPointer]); - } - var patch = new diff_match_patch.patch_obj(); - patches.push(patch); - patch.start1 = parseInt(m[1], 10); - if (m[2] === '') { - patch.start1--; - patch.length1 = 1; - } else if (m[2] == '0') { - patch.length1 = 0; - } else { - patch.start1--; - patch.length1 = parseInt(m[2], 10); - } - - patch.start2 = parseInt(m[3], 10); - if (m[4] === '') { - patch.start2--; - patch.length2 = 1; - } else if (m[4] == '0') { - patch.length2 = 0; - } else { - patch.start2--; - patch.length2 = parseInt(m[4], 10); - } - textPointer++; - - while (textPointer < text.length) { - var sign = text[textPointer].charAt(0); - try { - var line = decodeURI(text[textPointer].substring(1)); - } catch (ex) { - // Malformed URI sequence. - throw new Error('Illegal escape in patch_fromText: ' + line); - } - if (sign == '-') { - // Deletion. - patch.diffs.push([DIFF_DELETE, line]); - } else if (sign == '+') { - // Insertion. - patch.diffs.push([DIFF_INSERT, line]); - } else if (sign == ' ') { - // Minor equality. - patch.diffs.push([DIFF_EQUAL, line]); - } else if (sign == '@') { - // Start of next patch. - break; - } else if (sign === '') { - // Blank line? Whatever. - } else { - // WTF? - throw new Error('Invalid patch mode "' + sign + '" in: ' + line); - } - textPointer++; - } - } - return patches; -}; - - -/** - * Class representing one patch operation. - * @constructor - */ -diff_match_patch.patch_obj = function() { - /** @type {!Array.} */ - this.diffs = []; - /** @type {?number} */ - this.start1 = null; - /** @type {?number} */ - this.start2 = null; - /** @type {number} */ - this.length1 = 0; - /** @type {number} */ - this.length2 = 0; -}; - - -/** - * Emmulate GNU diff's format. - * Header: @@ -382,8 +481,9 @@ - * Indicies are printed as 1-based, not 0-based. - * @return {string} The GNU diff string. - */ -diff_match_patch.patch_obj.prototype.toString = function() { - var coords1, coords2; - if (this.length1 === 0) { - coords1 = this.start1 + ',0'; - } else if (this.length1 == 1) { - coords1 = this.start1 + 1; - } else { - coords1 = (this.start1 + 1) + ',' + this.length1; - } - if (this.length2 === 0) { - coords2 = this.start2 + ',0'; - } else if (this.length2 == 1) { - coords2 = this.start2 + 1; - } else { - coords2 = (this.start2 + 1) + ',' + this.length2; - } - var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n']; - var op; - // Escape the body of the patch with %xx notation. - for (var x = 0; x < this.diffs.length; x++) { - switch (this.diffs[x][0]) { - case DIFF_INSERT: - op = '+'; - break; - case DIFF_DELETE: - op = '-'; - break; - case DIFF_EQUAL: - op = ' '; - break; - } - text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n'; - } - return text.join('').replace(/%20/g, ' '); -}; - - -// Export these global variables so that they survive Google's JS compiler. -// In a browser, 'this' will be 'window'. -// Users of node.js should 'require' the uncompressed version since Google's -// JS compiler may break the following exports for non-browser environments. -this['diff_match_patch'] = diff_match_patch; -this['DIFF_DELETE'] = DIFF_DELETE; -this['DIFF_INSERT'] = DIFF_INSERT; -this['DIFF_EQUAL'] = DIFF_EQUAL; diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/jquery-1.7.2.min.js b/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/jquery-1.7.2.min.js deleted file mode 100644 index 5627896..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/jquery-1.7.2.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v1.7.2 jquery.com | jquery.org/license */ -(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"":"")+""),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;e=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="
"+""+"
",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="
t
",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="
",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( -a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&j.push({elem:this,matches:d.slice(e)});for(k=0;k0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
","
"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f -.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(;d1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]===""&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/jquery.activity-indicator.js b/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/jquery.activity-indicator.js deleted file mode 100644 index 0d65f77..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/diff/lib/jquery.activity-indicator.js +++ /dev/null @@ -1,222 +0,0 @@ -/*! - * NETEYE Activity Indicator jQuery Plugin - * - * Copyright (c) 2010 NETEYE GmbH - * Licensed under the MIT license - * - * Author: Felix Gnass [fgnass at neteye dot de] - * Version: 1.0.0 - */ - -/** - * Plugin that renders a customisable activity indicator (spinner) using SVG or VML. - */ -(function($) { - - $.fn.activity = function(opts) { - this.each(function() { - var $this = $(this); - var el = $this.data('activity'); - if (el) { - clearInterval(el.data('interval')); - el.remove(); - $this.removeData('activity'); - } - if (opts !== false) { - opts = $.extend({color: $this.css('color')}, $.fn.activity.defaults, opts); - - el = render($this, opts).css('position', 'absolute').prependTo(opts.outside ? 'body' : $this); - var h = $this.outerHeight() - el.height(); - var w = $this.outerWidth() - el.width(); - var margin = { - top: opts.valign == 'top' ? opts.padding : opts.valign == 'bottom' ? h - opts.padding : Math.floor(h / 2), - left: opts.align == 'left' ? opts.padding : opts.align == 'right' ? w - opts.padding : Math.floor(w / 2) - }; - var offset = $this.offset(); - if (opts.outside) { - el.css({top: offset.top + 'px', left: offset.left + 'px'}); - } - else { - margin.top -= el.offset().top - offset.top; - margin.left -= el.offset().left - offset.left; - } - el.css({marginTop: margin.top + 'px', marginLeft: margin.left + 'px'}); - animate(el, opts.segments, Math.round(10 / opts.speed) / 10); - $this.data('activity', el); - } - }); - return this; - }; - - $.fn.activity.defaults = { - segments: 12, - space: 3, - length: 7, - width: 4, - speed: 1.2, - align: 'center', - valign: 'center', - padding: 4 - }; - - $.fn.activity.getOpacity = function(opts, i) { - var steps = opts.steps || opts.segments-1; - var end = opts.opacity !== undefined ? opts.opacity : 1/steps; - return 1 - Math.min(i, steps) * (1 - end) / steps; - }; - - /** - * Default rendering strategy. If neither SVG nor VML is available, a div with class-name 'busy' - * is inserted, that can be styled with CSS to display an animated gif as fallback. - */ - var render = function() { - return $('
').addClass('busy'); - }; - - /** - * The default animation strategy does nothing as we expect an animated gif as fallback. - */ - var animate = function() { - }; - - /** - * Utility function to create elements in the SVG namespace. - */ - function svg(tag, attr) { - var el = document.createElementNS("http://www.w3.org/2000/svg", tag || 'svg'); - if (attr) { - $.each(attr, function(k, v) { - el.setAttributeNS(null, k, v); - }); - } - return $(el); - } - - if (document.createElementNS && document.createElementNS( "http://www.w3.org/2000/svg", "svg").createSVGRect) { - - // ======================================================================================= - // SVG Rendering - // ======================================================================================= - - /** - * Rendering strategy that creates a SVG tree. - */ - render = function(target, d) { - var innerRadius = d.width*2 + d.space; - var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1); - - var el = svg().width(r*2).height(r*2); - - var g = svg('g', { - 'stroke-width': d.width, - 'stroke-linecap': 'round', - stroke: d.color - }).appendTo(svg('g', {transform: 'translate('+ r +','+ r +')'}).appendTo(el)); - - for (var i = 0; i < d.segments; i++) { - g.append(svg('line', { - x1: 0, - y1: innerRadius, - x2: 0, - y2: innerRadius + d.length, - transform: 'rotate(' + (360 / d.segments * i) + ', 0, 0)', - opacity: $.fn.activity.getOpacity(d, i) - })); - } - return $('
').append(el).width(2*r).height(2*r); - }; - - // Check if Webkit CSS animations are available, as they work much better on the iPad - // than setTimeout() based animations. - - if (document.createElement('div').style.WebkitAnimationName !== undefined) { - - var animations = {}; - - /** - * Animation strategy that uses dynamically created CSS animation rules. - */ - animate = function(el, steps, duration) { - if (!animations[steps]) { - var name = 'spin' + steps; - var rule = '@-webkit-keyframes '+ name +' {'; - for (var i=0; i < steps; i++) { - var p1 = Math.round(100000 / steps * i) / 1000; - var p2 = Math.round(100000 / steps * (i+1) - 1) / 1000; - var value = '% { -webkit-transform:rotate(' + Math.round(360 / steps * i) + 'deg); }\n'; - rule += p1 + value + p2 + value; - } - rule += '100% { -webkit-transform:rotate(100deg); }\n}'; - document.styleSheets[0].insertRule(rule); - animations[steps] = name; - } - el.css('-webkit-animation', animations[steps] + ' ' + duration +'s linear infinite'); - }; - } - else { - - /** - * Animation strategy that transforms a SVG element using setInterval(). - */ - animate = function(el, steps, duration) { - var rotation = 0; - var g = el.find('g g').get(0); - el.data('interval', setInterval(function() { - g.setAttributeNS(null, 'transform', 'rotate(' + (++rotation % steps * (360 / steps)) + ')'); - }, duration * 1000 / steps)); - }; - } - - } - else { - - // ======================================================================================= - // VML Rendering - // ======================================================================================= - - var s = $('').css('behavior', 'url(#default#VML)').appendTo('body'); - - if (s.get(0).adj) { - - // VML support detected. Insert CSS rules for group, shape and stroke. - var sheet = document.createStyleSheet(); - $.each(['group', 'shape', 'stroke'], function() { - sheet.addRule(this, "behavior:url(#default#VML);"); - }); - - /** - * Rendering strategy that creates a VML tree. - */ - render = function(target, d) { - - var innerRadius = d.width*2 + d.space; - var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1); - var s = r*2; - var o = -Math.ceil(s/2); - - var el = $('', {coordsize: s + ' ' + s, coordorigin: o + ' ' + o}).css({top: o, left: o, width: s, height: s}); - for (var i = 0; i < d.segments; i++) { - el.append($('', {path: 'm ' + innerRadius + ',0 l ' + (innerRadius + d.length) + ',0'}).css({ - width: s, - height: s, - rotation: (360 / d.segments * i) + 'deg' - }).append($('', {color: d.color, weight: d.width + 'px', endcap: 'round', opacity: $.fn.activity.getOpacity(d, i)}))); - } - return $('', {coordsize: s + ' ' + s}).css({width: s, height: s, overflow: 'hidden'}).append(el); - }; - - /** - * Animation strategy that modifies the VML rotation property using setInterval(). - */ - animate = function(el, steps, duration) { - var rotation = 0; - var g = el.get(0); - el.data('interval', setInterval(function() { - g.style.rotation = ++rotation % steps * (360 / steps); - }, duration * 1000 / steps)); - }; - } - $(s).remove(); - } - -})(jQuery); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/codemirror.css b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/codemirror.css deleted file mode 100644 index cfe2eb2..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/codemirror.css +++ /dev/null @@ -1,126 +0,0 @@ -.CodeMirror { - line-height: 1em; - font-family: monospace; -} - -.CodeMirror-scroll { - overflow: auto; - height: 300px; - /* This is needed to prevent an IE[67] bug where the scrolled content - is visible outside of the scrolling box. */ - position: relative; - outline: none; -} - -.CodeMirror-gutter { - position: absolute; left: 0; top: 0; - z-index: 10; - background-color: #f7f7f7; - border-right: 1px solid #eee; - min-width: 2em; - height: 100%; -} -.CodeMirror-gutter-text { - color: #aaa; - text-align: right; - padding: .4em .2em .4em .4em; - white-space: pre !important; -} -.CodeMirror-lines { - padding: .4em; - white-space: pre; -} - -.CodeMirror pre { - -moz-border-radius: 0; - -webkit-border-radius: 0; - -o-border-radius: 0; - border-radius: 0; - border-width: 0; margin: 0; padding: 0; background: transparent; - font-family: inherit; - font-size: inherit; - padding: 0; margin: 0; - white-space: pre; - word-wrap: normal; - line-height: inherit; - color: inherit; -} - -.CodeMirror-wrap pre { - word-wrap: break-word; - white-space: pre-wrap; - word-break: normal; -} -.CodeMirror-wrap .CodeMirror-scroll { - overflow-x: hidden; -} - -.CodeMirror textarea { - outline: none !important; -} - -.CodeMirror pre.CodeMirror-cursor { - z-index: 10; - position: absolute; - visibility: hidden; - border-left: 1px solid black; - border-right: none; - width: 0; -} -.cm-keymap-fat-cursor pre.CodeMirror-cursor { - width: auto; - border: 0; - background: transparent; - background: rgba(0, 200, 0, .4); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#6600c800, endColorstr=#4c00c800); -} -/* Kludge to turn off filter in ie9+, which also accepts rgba */ -.cm-keymap-fat-cursor pre.CodeMirror-cursor:not(#nonsense_id) { - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); -} -.CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {} -.CodeMirror-focused pre.CodeMirror-cursor { - visibility: visible; -} - -div.CodeMirror-selected { background: #d9d9d9; } -.CodeMirror-focused div.CodeMirror-selected { background: #d7d4f0; } - -.CodeMirror-searching { - background: #ffa; - background: rgba(255, 255, 0, .4); -} - -/* Default theme */ - -.cm-s-default span.cm-keyword {color: #708;} -.cm-s-default span.cm-atom {color: #219;} -.cm-s-default span.cm-number {color: #164;} -.cm-s-default span.cm-def {color: #00f;} -.cm-s-default span.cm-variable {color: black;} -.cm-s-default span.cm-variable-2 {color: #05a;} -.cm-s-default span.cm-variable-3 {color: #085;} -.cm-s-default span.cm-property {color: black;} -.cm-s-default span.cm-operator {color: black;} -.cm-s-default span.cm-comment {color: #a50;} -.cm-s-default span.cm-string {color: #a11;} -.cm-s-default span.cm-string-2 {color: #f50;} -.cm-s-default span.cm-meta {color: #555;} -.cm-s-default span.cm-error {color: #f00;} -.cm-s-default span.cm-qualifier {color: #555;} -.cm-s-default span.cm-builtin {color: #30a;} -.cm-s-default span.cm-bracket {color: #cc7;} -.cm-s-default span.cm-tag {color: #170;} -.cm-s-default span.cm-attribute {color: #00c;} -.cm-s-default span.cm-header {color: blue;} -.cm-s-default span.cm-quote {color: #090;} -.cm-s-default span.cm-hr {color: #999;} -.cm-s-default span.cm-link {color: #00c;} - -span.cm-header, span.cm-strong {font-weight: bold;} -span.cm-em {font-style: italic;} -span.cm-emstrong {font-style: italic; font-weight: bold;} -span.cm-link {text-decoration: underline;} - -div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} -div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/codemirror.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/codemirror.js deleted file mode 100644 index be4cb30..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/codemirror.js +++ /dev/null @@ -1,3076 +0,0 @@ -// CodeMirror version 2.25 -// -// All functions that need access to the editor's state live inside -// the CodeMirror function. Below that, at the bottom of the file, -// some utilities are defined. - -// CodeMirror is the only global var we claim -var CodeMirror = (function() { - // This is the function that produces an editor instance. Its - // closure is used to store the editor state. - function CodeMirror(place, givenOptions) { - // Determine effective options based on given values and defaults. - var options = {}, defaults = CodeMirror.defaults; - for (var opt in defaults) - if (defaults.hasOwnProperty(opt)) - options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt]; - - // The element in which the editor lives. - var wrapper = document.createElement("div"); - wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : ""); - // This mess creates the base DOM structure for the editor. - wrapper.innerHTML = - '
' + // Wraps and hides input textarea - '
' + - '
' + - '
' + // Set to the height of the text, causes scrolling - '
' + // Moved around its parent to cover visible view - '
' + - // Provides positioning relative to (visible) text origin - '
' + - '
' + - '
 
' + // Absolutely positioned blinky cursor - '
' + // DIVs containing the selection and the actual code - '
'; - if (place.appendChild) place.appendChild(wrapper); else place(wrapper); - // I've never seen more elegant code in my life. - var inputDiv = wrapper.firstChild, input = inputDiv.firstChild, - scroller = wrapper.lastChild, code = scroller.firstChild, - mover = code.firstChild, gutter = mover.firstChild, gutterText = gutter.firstChild, - lineSpace = gutter.nextSibling.firstChild, measure = lineSpace.firstChild, - cursor = measure.nextSibling, selectionDiv = cursor.nextSibling, - lineDiv = selectionDiv.nextSibling; - themeChanged(); keyMapChanged(); - // Needed to hide big blue blinking cursor on Mobile Safari - if (ios) input.style.width = "0px"; - if (!webkit) lineSpace.draggable = true; - lineSpace.style.outline = "none"; - if (options.tabindex != null) input.tabIndex = options.tabindex; - if (options.autofocus) focusInput(); - if (!options.gutter && !options.lineNumbers) gutter.style.display = "none"; - // Needed to handle Tab key in KHTML - if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute"; - - // Check for problem with IE innerHTML not working when we have a - // P (or similar) parent node. - try { stringWidth("x"); } - catch (e) { - if (e.message.match(/runtime/i)) - e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)"); - throw e; - } - - // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval. - var poll = new Delayed(), highlight = new Delayed(), blinker; - - // mode holds a mode API object. doc is the tree of Line objects, - // work an array of lines that should be parsed, and history the - // undo history (instance of History constructor). - var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), work, focused; - loadMode(); - // The selection. These are always maintained to point at valid - // positions. Inverted is used to remember that the user is - // selecting bottom-to-top. - var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false}; - // Selection-related flags. shiftSelecting obviously tracks - // whether the user is holding shift. - var shiftSelecting, lastClick, lastDoubleClick, lastScrollPos = 0, draggingText, - overwrite = false, suppressEdits = false; - // Variables used by startOperation/endOperation to track what - // happened during the operation. - var updateInput, userSelChange, changes, textChanged, selectionChanged, leaveInputAlone, - gutterDirty, callbacks, maxLengthChanged; - // Current visible range (may be bigger than the view window). - var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0; - // bracketHighlighted is used to remember that a bracket has been - // marked. - var bracketHighlighted; - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - var maxLine = "", maxWidth; - var tabCache = {}; - - // Initialize the content. - operation(function(){setValue(options.value || ""); updateInput = false;})(); - var history = new History(); - - // Register our event handlers. - connect(scroller, "mousedown", operation(onMouseDown)); - connect(scroller, "dblclick", operation(onDoubleClick)); - connect(lineSpace, "selectstart", e_preventDefault); - // Gecko browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for Gecko. - if (!gecko) connect(scroller, "contextmenu", onContextMenu); - connect(scroller, "scroll", function() { - lastScrollPos = scroller.scrollTop; - updateDisplay([]); - if (options.fixedGutter) gutter.style.left = scroller.scrollLeft + "px"; - if (options.onScroll) options.onScroll(instance); - }); - connect(window, "resize", function() {updateDisplay(true);}); - connect(input, "keyup", operation(onKeyUp)); - connect(input, "input", fastPoll); - connect(input, "keydown", operation(onKeyDown)); - connect(input, "keypress", operation(onKeyPress)); - connect(input, "focus", onFocus); - connect(input, "blur", onBlur); - - if (options.dragDrop) { - connect(lineSpace, "dragstart", onDragStart); - function drag_(e) { - if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; - e_stop(e); - } - connect(scroller, "dragenter", drag_); - connect(scroller, "dragover", drag_); - connect(scroller, "drop", operation(onDrop)); - } - connect(scroller, "paste", function(){focusInput(); fastPoll();}); - connect(input, "paste", fastPoll); - connect(input, "cut", operation(function(){ - if (!options.readOnly) replaceSelection(""); - })); - - // Needed to handle Tab key in KHTML - if (khtml) connect(code, "mouseup", function() { - if (document.activeElement == input) input.blur(); - focusInput(); - }); - - // IE throws unspecified error in certain cases, when - // trying to access activeElement before onload - var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { } - if (hasFocus || options.autofocus) setTimeout(onFocus, 20); - else onBlur(); - - function isLine(l) {return l >= 0 && l < doc.size;} - // The instance object that we'll return. Mostly calls out to - // local functions in the CodeMirror function. Some do some extra - // range checking and/or clipping. operation is used to wrap the - // call so that changes it makes are tracked, and the display is - // updated afterwards. - var instance = wrapper.CodeMirror = { - getValue: getValue, - setValue: operation(setValue), - getSelection: getSelection, - replaceSelection: operation(replaceSelection), - focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();}, - setOption: function(option, value) { - var oldVal = options[option]; - options[option] = value; - if (option == "mode" || option == "indentUnit") loadMode(); - else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();} - else if (option == "readOnly" && !value) {resetInput(true);} - else if (option == "theme") themeChanged(); - else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)(); - else if (option == "tabSize") updateDisplay(true); - else if (option == "keyMap") keyMapChanged(); - if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme") { - gutterChanged(); - updateDisplay(true); - } - }, - getOption: function(option) {return options[option];}, - undo: operation(undo), - redo: operation(redo), - indentLine: operation(function(n, dir) { - if (typeof dir != "string") { - if (dir == null) dir = options.smartIndent ? "smart" : "prev"; - else dir = dir ? "add" : "subtract"; - } - if (isLine(n)) indentLine(n, dir); - }), - indentSelection: operation(indentSelected), - historySize: function() {return {undo: history.done.length, redo: history.undone.length};}, - clearHistory: function() {history = new History();}, - matchBrackets: operation(function(){matchBrackets(true);}), - getTokenAt: operation(function(pos) { - pos = clipPos(pos); - return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), pos.ch); - }), - getStateAfter: function(line) { - line = clipLine(line == null ? doc.size - 1: line); - return getStateBefore(line + 1); - }, - cursorCoords: function(start, mode) { - if (start == null) start = sel.inverted; - return this.charCoords(start ? sel.from : sel.to, mode); - }, - charCoords: function(pos, mode) { - pos = clipPos(pos); - if (mode == "local") return localCoords(pos, false); - if (mode == "div") return localCoords(pos, true); - return pageCoords(pos); - }, - coordsChar: function(coords) { - var off = eltOffset(lineSpace); - return coordsChar(coords.x - off.left, coords.y - off.top); - }, - markText: operation(markText), - setBookmark: setBookmark, - findMarksAt: findMarksAt, - setMarker: operation(addGutterMarker), - clearMarker: operation(removeGutterMarker), - setLineClass: operation(setLineClass), - hideLine: operation(function(h) {return setLineHidden(h, true);}), - showLine: operation(function(h) {return setLineHidden(h, false);}), - onDeleteLine: function(line, f) { - if (typeof line == "number") { - if (!isLine(line)) return null; - line = getLine(line); - } - (line.handlers || (line.handlers = [])).push(f); - return line; - }, - lineInfo: lineInfo, - addWidget: function(pos, node, scroll, vert, horiz) { - pos = localCoords(clipPos(pos)); - var top = pos.yBot, left = pos.x; - node.style.position = "absolute"; - code.appendChild(node); - if (vert == "over") top = pos.y; - else if (vert == "near") { - var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()), - hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft(); - if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight) - top = pos.y - node.offsetHeight; - if (left + node.offsetWidth > hspace) - left = hspace - node.offsetWidth; - } - node.style.top = (top + paddingTop()) + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = code.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") left = 0; - else if (horiz == "middle") left = (code.clientWidth - node.offsetWidth) / 2; - node.style.left = (left + paddingLeft()) + "px"; - } - if (scroll) - scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight); - }, - - lineCount: function() {return doc.size;}, - clipPos: clipPos, - getCursor: function(start) { - if (start == null) start = sel.inverted; - return copyPos(start ? sel.from : sel.to); - }, - somethingSelected: function() {return !posEq(sel.from, sel.to);}, - setCursor: operation(function(line, ch, user) { - if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user); - else setCursor(line, ch, user); - }), - setSelection: operation(function(from, to, user) { - (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from)); - }), - getLine: function(line) {if (isLine(line)) return getLine(line).text;}, - getLineHandle: function(line) {if (isLine(line)) return getLine(line);}, - setLine: operation(function(line, text) { - if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length}); - }), - removeLine: operation(function(line) { - if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0})); - }), - replaceRange: operation(replaceRange), - getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));}, - - triggerOnKeyDown: operation(onKeyDown), - execCommand: function(cmd) {return commands[cmd](instance);}, - // Stuff used by commands, probably not much use to outside code. - moveH: operation(moveH), - deleteH: operation(deleteH), - moveV: operation(moveV), - toggleOverwrite: function() { - if(overwrite){ - overwrite = false; - cursor.className = cursor.className.replace(" CodeMirror-overwrite", ""); - } else { - overwrite = true; - cursor.className += " CodeMirror-overwrite"; - } - }, - - posFromIndex: function(off) { - var lineNo = 0, ch; - doc.iter(0, doc.size, function(line) { - var sz = line.text.length + 1; - if (sz > off) { ch = off; return true; } - off -= sz; - ++lineNo; - }); - return clipPos({line: lineNo, ch: ch}); - }, - indexFromPos: function (coords) { - if (coords.line < 0 || coords.ch < 0) return 0; - var index = coords.ch; - doc.iter(0, coords.line, function (line) { - index += line.text.length + 1; - }); - return index; - }, - scrollTo: function(x, y) { - if (x != null) scroller.scrollLeft = x; - if (y != null) scroller.scrollTop = y; - updateDisplay([]); - }, - - operation: function(f){return operation(f)();}, - compoundChange: function(f){return compoundChange(f);}, - refresh: function(){ - updateDisplay(true); - if (scroller.scrollHeight > lastScrollPos) - scroller.scrollTop = lastScrollPos; - }, - getInputField: function(){return input;}, - getWrapperElement: function(){return wrapper;}, - getScrollerElement: function(){return scroller;}, - getGutterElement: function(){return gutter;} - }; - - function getLine(n) { return getLineAt(doc, n); } - function updateLineHeight(line, height) { - gutterDirty = true; - var diff = height - line.height; - for (var n = line; n; n = n.parent) n.height += diff; - } - - function setValue(code) { - var top = {line: 0, ch: 0}; - updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length}, - splitLines(code), top, top); - updateInput = true; - } - function getValue() { - var text = []; - doc.iter(0, doc.size, function(line) { text.push(line.text); }); - return text.join("\n"); - } - - function onMouseDown(e) { - setShift(e_prop(e, "shiftKey")); - // Check whether this is a click in a widget - for (var n = e_target(e); n != wrapper; n = n.parentNode) - if (n.parentNode == code && n != mover) return; - - // See if this is a click in the gutter - for (var n = e_target(e); n != wrapper; n = n.parentNode) - if (n.parentNode == gutterText) { - if (options.onGutterClick) - options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e); - return e_preventDefault(e); - } - - var start = posFromMouse(e); - - switch (e_button(e)) { - case 3: - if (gecko && !mac) onContextMenu(e); - return; - case 2: - if (start) setCursor(start.line, start.ch, true); - setTimeout(focusInput, 20); - return; - } - // For button 1, if it was clicked inside the editor - // (posFromMouse returning non-null), we have to adjust the - // selection. - if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;} - - if (!focused) onFocus(); - - var now = +new Date; - if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { - e_preventDefault(e); - setTimeout(focusInput, 20); - return selectLine(start.line); - } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { - lastDoubleClick = {time: now, pos: start}; - e_preventDefault(e); - return selectWordAt(start); - } else { lastClick = {time: now, pos: start}; } - - var last = start, going; - if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) && - !posLess(start, sel.from) && !posLess(sel.to, start)) { - // Let the drag handler handle this. - if (webkit) lineSpace.draggable = true; - function dragEnd(e2) { - if (webkit) lineSpace.draggable = false; - draggingText = false; - up(); drop(); - if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { - e_preventDefault(e2); - setCursor(start.line, start.ch, true); - focusInput(); - } - } - var up = connect(document, "mouseup", operation(dragEnd), true); - var drop = connect(scroller, "drop", operation(dragEnd), true); - draggingText = true; - // IE's approach to draggable - if (lineSpace.dragDrop) lineSpace.dragDrop(); - return; - } - e_preventDefault(e); - setCursor(start.line, start.ch, true); - - function extend(e) { - var cur = posFromMouse(e, true); - if (cur && !posEq(cur, last)) { - if (!focused) onFocus(); - last = cur; - setSelectionUser(start, cur); - updateInput = false; - var visible = visibleLines(); - if (cur.line >= visible.to || cur.line < visible.from) - going = setTimeout(operation(function(){extend(e);}), 150); - } - } - - function done(e) { - clearTimeout(going); - var cur = posFromMouse(e); - if (cur) setSelectionUser(start, cur); - e_preventDefault(e); - focusInput(); - updateInput = true; - move(); up(); - } - var move = connect(document, "mousemove", operation(function(e) { - clearTimeout(going); - e_preventDefault(e); - if (!ie && !e_button(e)) done(e); - else extend(e); - }), true); - var up = connect(document, "mouseup", operation(done), true); - } - function onDoubleClick(e) { - for (var n = e_target(e); n != wrapper; n = n.parentNode) - if (n.parentNode == gutterText) return e_preventDefault(e); - var start = posFromMouse(e); - if (!start) return; - lastDoubleClick = {time: +new Date, pos: start}; - e_preventDefault(e); - selectWordAt(start); - } - function onDrop(e) { - if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; - e.preventDefault(); - var pos = posFromMouse(e, true), files = e.dataTransfer.files; - if (!pos || options.readOnly) return; - if (files && files.length && window.FileReader && window.File) { - function loadFile(file, i) { - var reader = new FileReader; - reader.onload = function() { - text[i] = reader.result; - if (++read == n) { - pos = clipPos(pos); - operation(function() { - var end = replaceRange(text.join(""), pos, pos); - setSelectionUser(pos, end); - })(); - } - }; - reader.readAsText(file); - } - var n = files.length, text = Array(n), read = 0; - for (var i = 0; i < n; ++i) loadFile(files[i], i); - } - else { - try { - var text = e.dataTransfer.getData("Text"); - if (text) { - compoundChange(function() { - var curFrom = sel.from, curTo = sel.to; - setSelectionUser(pos, pos); - if (draggingText) replaceRange("", curFrom, curTo); - replaceSelection(text); - focusInput(); - }); - } - } - catch(e){} - } - } - function onDragStart(e) { - var txt = getSelection(); - e.dataTransfer.setData("Text", txt); - - // Use dummy image instead of default browsers image. - if (gecko || chrome) { - var img = document.createElement('img'); - img.scr = 'data:image/gif;base64,R0lGODdhAgACAIAAAAAAAP///ywAAAAAAgACAAACAoRRADs='; //1x1 image - e.dataTransfer.setDragImage(img, 0, 0); - } - } - - function doHandleBinding(bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) return false; - } - var prevShift = shiftSelecting; - try { - if (options.readOnly) suppressEdits = true; - if (dropShift) shiftSelecting = null; - bound(instance); - } catch(e) { - if (e != Pass) throw e; - return false; - } finally { - shiftSelecting = prevShift; - suppressEdits = false; - } - return true; - } - function handleKeyBinding(e) { - // Handle auto keymap transitions - var startMap = getKeyMap(options.keyMap), next = startMap.auto; - clearTimeout(maybeTransition); - if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { - if (getKeyMap(options.keyMap) == startMap) { - options.keyMap = (next.call ? next.call(null, instance) : next); - } - }, 50); - - var name = keyNames[e_prop(e, "keyCode")], handled = false; - if (name == null || e.altGraphKey) return false; - if (e_prop(e, "altKey")) name = "Alt-" + name; - if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name; - if (e_prop(e, "metaKey")) name = "Cmd-" + name; - - var stopped = false; - function stop() { stopped = true; } - - if (e_prop(e, "shiftKey")) { - handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap, - function(b) {return doHandleBinding(b, true);}, stop) - || lookupKey(name, options.extraKeys, options.keyMap, function(b) { - if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b); - }, stop); - } else { - handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding, stop); - } - if (stopped) handled = false; - if (handled) { - e_preventDefault(e); - restartBlink(); - if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } - } - return handled; - } - function handleCharBinding(e, ch) { - var handled = lookupKey("'" + ch + "'", options.extraKeys, - options.keyMap, function(b) { return doHandleBinding(b, true); }); - if (handled) { - e_preventDefault(e); - restartBlink(); - } - return handled; - } - - var lastStoppedKey = null, maybeTransition; - function onKeyDown(e) { - if (!focused) onFocus(); - if (ie && e.keyCode == 27) { e.returnValue = false; } - if (pollingFast) { if (readInput()) pollingFast = false; } - if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; - var code = e_prop(e, "keyCode"); - // IE does strange things with escape. - setShift(code == 16 || e_prop(e, "shiftKey")); - // First give onKeyEvent option a chance to handle this. - var handled = handleKeyBinding(e); - if (window.opera) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey")) - replaceSelection(""); - } - } - function onKeyPress(e) { - if (pollingFast) readInput(); - if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; - var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode"); - if (window.opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} - if (((window.opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return; - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) { - if (mode.electricChars.indexOf(ch) > -1) - setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75); - } - if (handleCharBinding(e, ch)) return; - fastPoll(); - } - function onKeyUp(e) { - if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; - if (e_prop(e, "keyCode") == 16) shiftSelecting = null; - } - - function onFocus() { - if (options.readOnly == "nocursor") return; - if (!focused) { - if (options.onFocus) options.onFocus(instance); - focused = true; - if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1) - wrapper.className += " CodeMirror-focused"; - if (!leaveInputAlone) resetInput(true); - } - slowPoll(); - restartBlink(); - } - function onBlur() { - if (focused) { - if (options.onBlur) options.onBlur(instance); - focused = false; - if (bracketHighlighted) - operation(function(){ - if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; } - })(); - wrapper.className = wrapper.className.replace(" CodeMirror-focused", ""); - } - clearInterval(blinker); - setTimeout(function() {if (!focused) shiftSelecting = null;}, 150); - } - - // Replace the range from from to to by the strings in newText. - // Afterwards, set the selection to selFrom, selTo. - function updateLines(from, to, newText, selFrom, selTo) { - if (suppressEdits) return; - if (history) { - var old = []; - doc.iter(from.line, to.line + 1, function(line) { old.push(line.text); }); - history.addChange(from.line, newText.length, old); - while (history.done.length > options.undoDepth) history.done.shift(); - } - updateLinesNoUndo(from, to, newText, selFrom, selTo); - } - function unredoHelper(from, to) { - if (!from.length) return; - var set = from.pop(), out = []; - for (var i = set.length - 1; i >= 0; i -= 1) { - var change = set[i]; - var replaced = [], end = change.start + change.added; - doc.iter(change.start, end, function(line) { replaced.push(line.text); }); - out.push({start: change.start, added: change.old.length, old: replaced}); - var pos = clipPos({line: change.start + change.old.length - 1, - ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])}); - updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, change.old, pos, pos); - } - updateInput = true; - to.push(out); - } - function undo() {unredoHelper(history.done, history.undone);} - function redo() {unredoHelper(history.undone, history.done);} - - function updateLinesNoUndo(from, to, newText, selFrom, selTo) { - if (suppressEdits) return; - var recomputeMaxLength = false, maxLineLength = maxLine.length; - if (!options.lineWrapping) - doc.iter(from.line, to.line + 1, function(line) { - if (!line.hidden && line.text.length == maxLineLength) {recomputeMaxLength = true; return true;} - }); - if (from.line != to.line || newText.length > 1) gutterDirty = true; - - var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line); - // First adjust the line structure, taking some care to leave highlighting intact. - if (from.ch == 0 && to.ch == 0 && newText[newText.length - 1] == "") { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - var added = [], prevLine = null; - if (from.line) { - prevLine = getLine(from.line - 1); - prevLine.fixMarkEnds(lastLine); - } else lastLine.fixMarkStarts(); - for (var i = 0, e = newText.length - 1; i < e; ++i) - added.push(Line.inheritMarks(newText[i], prevLine)); - if (nlines) doc.remove(from.line, nlines, callbacks); - if (added.length) doc.insert(from.line, added); - } else if (firstLine == lastLine) { - if (newText.length == 1) - firstLine.replace(from.ch, to.ch, newText[0]); - else { - lastLine = firstLine.split(to.ch, newText[newText.length-1]); - firstLine.replace(from.ch, null, newText[0]); - firstLine.fixMarkEnds(lastLine); - var added = []; - for (var i = 1, e = newText.length - 1; i < e; ++i) - added.push(Line.inheritMarks(newText[i], firstLine)); - added.push(lastLine); - doc.insert(from.line + 1, added); - } - } else if (newText.length == 1) { - firstLine.replace(from.ch, null, newText[0]); - lastLine.replace(null, to.ch, ""); - firstLine.append(lastLine); - doc.remove(from.line + 1, nlines, callbacks); - } else { - var added = []; - firstLine.replace(from.ch, null, newText[0]); - lastLine.replace(null, to.ch, newText[newText.length-1]); - firstLine.fixMarkEnds(lastLine); - for (var i = 1, e = newText.length - 1; i < e; ++i) - added.push(Line.inheritMarks(newText[i], firstLine)); - if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks); - doc.insert(from.line + 1, added); - } - if (options.lineWrapping) { - var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3); - doc.iter(from.line, from.line + newText.length, function(line) { - if (line.hidden) return; - var guess = Math.ceil(line.text.length / perLine) || 1; - if (guess != line.height) updateLineHeight(line, guess); - }); - } else { - doc.iter(from.line, from.line + newText.length, function(line) { - var l = line.text; - if (!line.hidden && l.length > maxLineLength) { - maxLine = l; maxLineLength = l.length; maxWidth = null; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) maxLengthChanged = true; - } - - // Add these lines to the work array, so that they will be - // highlighted. Adjust work lines if lines were added/removed. - var newWork = [], lendiff = newText.length - nlines - 1; - for (var i = 0, l = work.length; i < l; ++i) { - var task = work[i]; - if (task < from.line) newWork.push(task); - else if (task > to.line) newWork.push(task + lendiff); - } - var hlEnd = from.line + Math.min(newText.length, 500); - highlightLines(from.line, hlEnd); - newWork.push(hlEnd); - work = newWork; - startWorker(100); - // Remember that these lines changed, for updating the display - changes.push({from: from.line, to: to.line + 1, diff: lendiff}); - var changeObj = {from: from, to: to, text: newText}; - if (textChanged) { - for (var cur = textChanged; cur.next; cur = cur.next) {} - cur.next = changeObj; - } else textChanged = changeObj; - - // Update the selection - function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;} - setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line)); - - // Make sure the scroll-size div has the correct height. - if (scroller.clientHeight) - code.style.height = (doc.height * textHeight() + 2 * paddingTop()) + "px"; - } - - function computeMaxLength() { - var maxLineLength = 0; - maxLine = ""; maxWidth = null; - doc.iter(0, doc.size, function(line) { - var l = line.text; - if (!line.hidden && l.length > maxLineLength) { - maxLineLength = l.length; maxLine = l; - } - }); - maxLengthChanged = false; - } - - function replaceRange(code, from, to) { - from = clipPos(from); - if (!to) to = from; else to = clipPos(to); - code = splitLines(code); - function adjustPos(pos) { - if (posLess(pos, from)) return pos; - if (!posLess(to, pos)) return end; - var line = pos.line + code.length - (to.line - from.line) - 1; - var ch = pos.ch; - if (pos.line == to.line) - ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0)); - return {line: line, ch: ch}; - } - var end; - replaceRange1(code, from, to, function(end1) { - end = end1; - return {from: adjustPos(sel.from), to: adjustPos(sel.to)}; - }); - return end; - } - function replaceSelection(code, collapse) { - replaceRange1(splitLines(code), sel.from, sel.to, function(end) { - if (collapse == "end") return {from: end, to: end}; - else if (collapse == "start") return {from: sel.from, to: sel.from}; - else return {from: sel.from, to: end}; - }); - } - function replaceRange1(code, from, to, computeSel) { - var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length; - var newSel = computeSel({line: from.line + code.length - 1, ch: endch}); - updateLines(from, to, code, newSel.from, newSel.to); - } - - function getRange(from, to) { - var l1 = from.line, l2 = to.line; - if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch); - var code = [getLine(l1).text.slice(from.ch)]; - doc.iter(l1 + 1, l2, function(line) { code.push(line.text); }); - code.push(getLine(l2).text.slice(0, to.ch)); - return code.join("\n"); - } - function getSelection() { - return getRange(sel.from, sel.to); - } - - var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll - function slowPoll() { - if (pollingFast) return; - poll.set(options.pollInterval, function() { - startOperation(); - readInput(); - if (focused) slowPoll(); - endOperation(); - }); - } - function fastPoll() { - var missed = false; - pollingFast = true; - function p() { - startOperation(); - var changed = readInput(); - if (!changed && !missed) {missed = true; poll.set(60, p);} - else {pollingFast = false; slowPoll();} - endOperation(); - } - poll.set(20, p); - } - - // Previnput is a hack to work with IME. If we reset the textarea - // on every change, that breaks IME. So we look for changes - // compared to the previous content instead. (Modern browsers have - // events that indicate IME taking place, but these are not widely - // supported or compatible enough yet to rely on.) - var prevInput = ""; - function readInput() { - if (leaveInputAlone || !focused || hasSelection(input) || options.readOnly) return false; - var text = input.value; - if (text == prevInput) return false; - shiftSelecting = null; - var same = 0, l = Math.min(prevInput.length, text.length); - while (same < l && prevInput[same] == text[same]) ++same; - if (same < prevInput.length) - sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)}; - else if (overwrite && posEq(sel.from, sel.to)) - sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))}; - replaceSelection(text.slice(same), "end"); - if (text.length > 1000) { input.value = prevInput = ""; } - else prevInput = text; - return true; - } - function resetInput(user) { - if (!posEq(sel.from, sel.to)) { - prevInput = ""; - input.value = getSelection(); - selectInput(input); - } else if (user) prevInput = input.value = ""; - } - - function focusInput() { - if (options.readOnly != "nocursor") input.focus(); - } - - function scrollEditorIntoView() { - if (!cursor.getBoundingClientRect) return; - var rect = cursor.getBoundingClientRect(); - // IE returns bogus coordinates when the instance sits inside of an iframe and the cursor is hidden - if (ie && rect.top == rect.bottom) return; - var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); - if (rect.top < 0 || rect.bottom > winH) cursor.scrollIntoView(); - } - function scrollCursorIntoView() { - var cursor = localCoords(sel.inverted ? sel.from : sel.to); - var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x; - return scrollIntoView(x, cursor.y, x, cursor.yBot); - } - function scrollIntoView(x1, y1, x2, y2) { - var pl = paddingLeft(), pt = paddingTop(); - y1 += pt; y2 += pt; x1 += pl; x2 += pl; - var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true; - if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1); scrolled = true;} - else if (y2 > screentop + screen) {scroller.scrollTop = y2 - screen; scrolled = true;} - - var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft; - var gutterw = options.fixedGutter ? gutter.clientWidth : 0; - var atLeft = x1 < gutterw + pl + 10; - if (x1 < screenleft + gutterw || atLeft) { - if (atLeft) x1 = 0; - scroller.scrollLeft = Math.max(0, x1 - 10 - gutterw); - scrolled = true; - } - else if (x2 > screenw + screenleft - 3) { - scroller.scrollLeft = x2 + 10 - screenw; - scrolled = true; - if (x2 > code.clientWidth) result = false; - } - if (scrolled && options.onScroll) options.onScroll(instance); - return result; - } - - function visibleLines() { - var lh = textHeight(), top = scroller.scrollTop - paddingTop(); - var fromHeight = Math.max(0, Math.floor(top / lh)); - var toHeight = Math.ceil((top + scroller.clientHeight) / lh); - return {from: lineAtHeight(doc, fromHeight), - to: lineAtHeight(doc, toHeight)}; - } - // Uses a set of changes plus the current scroll position to - // determine which DOM updates have to be made, and makes the - // updates. - function updateDisplay(changes, suppressCallback) { - if (!scroller.clientWidth) { - showingFrom = showingTo = displayOffset = 0; - return; - } - // Compute the new visible window - var visible = visibleLines(); - // Bail out if the visible area is already rendered and nothing changed. - if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) return; - var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100); - if (showingFrom < from && from - showingFrom < 20) from = showingFrom; - if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo); - - // Create a range of theoretically intact lines, and punch holes - // in that using the change info. - var intact = changes === true ? [] : - computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes); - // Clip off the parts that won't be visible - var intactLines = 0; - for (var i = 0; i < intact.length; ++i) { - var range = intact[i]; - if (range.from < from) {range.domStart += (from - range.from); range.from = from;} - if (range.to > to) range.to = to; - if (range.from >= range.to) intact.splice(i--, 1); - else intactLines += range.to - range.from; - } - if (intactLines == to - from && from == showingFrom && to == showingTo) return; - intact.sort(function(a, b) {return a.domStart - b.domStart;}); - - var th = textHeight(), gutterDisplay = gutter.style.display; - lineDiv.style.display = "none"; - patchDisplay(from, to, intact); - lineDiv.style.display = gutter.style.display = ""; - - // Position the mover div to align with the lines it's supposed - // to be showing (which will cover the visible display) - var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th; - // This is just a bogus formula that detects when the editor is - // resized or the font size changes. - if (different) lastSizeC = scroller.clientHeight + th; - showingFrom = from; showingTo = to; - displayOffset = heightAtLine(doc, from); - mover.style.top = (displayOffset * th) + "px"; - if (scroller.clientHeight) - code.style.height = (doc.height * th + 2 * paddingTop()) + "px"; - - // Since this is all rather error prone, it is honoured with the - // only assertion in the whole file. - if (lineDiv.childNodes.length != showingTo - showingFrom) - throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) + - " nodes=" + lineDiv.childNodes.length); - - function checkHeights() { - maxWidth = scroller.clientWidth; - var curNode = lineDiv.firstChild, heightChanged = false; - doc.iter(showingFrom, showingTo, function(line) { - if (!line.hidden) { - var height = Math.round(curNode.offsetHeight / th) || 1; - if (line.height != height) { - updateLineHeight(line, height); - gutterDirty = heightChanged = true; - } - } - curNode = curNode.nextSibling; - }); - if (heightChanged) - code.style.height = (doc.height * th + 2 * paddingTop()) + "px"; - return heightChanged; - } - - if (options.lineWrapping) { - checkHeights(); - } else { - if (maxWidth == null) maxWidth = stringWidth(maxLine); - if (maxWidth > scroller.clientWidth) { - lineSpace.style.width = maxWidth + "px"; - // Needed to prevent odd wrapping/hiding of widgets placed in here. - code.style.width = ""; - code.style.width = scroller.scrollWidth + "px"; - } else { - lineSpace.style.width = code.style.width = ""; - } - } - - gutter.style.display = gutterDisplay; - if (different || gutterDirty) { - // If the gutter grew in size, re-check heights. If those changed, re-draw gutter. - updateGutter() && options.lineWrapping && checkHeights() && updateGutter(); - } - updateSelection(); - if (!suppressCallback && options.onUpdate) options.onUpdate(instance); - return true; - } - - function computeIntact(intact, changes) { - for (var i = 0, l = changes.length || 0; i < l; ++i) { - var change = changes[i], intact2 = [], diff = change.diff || 0; - for (var j = 0, l2 = intact.length; j < l2; ++j) { - var range = intact[j]; - if (change.to <= range.from && change.diff) - intact2.push({from: range.from + diff, to: range.to + diff, - domStart: range.domStart}); - else if (change.to <= range.from || change.from >= range.to) - intact2.push(range); - else { - if (change.from > range.from) - intact2.push({from: range.from, to: change.from, domStart: range.domStart}); - if (change.to < range.to) - intact2.push({from: change.to + diff, to: range.to + diff, - domStart: range.domStart + (change.to - range.from)}); - } - } - intact = intact2; - } - return intact; - } - - function patchDisplay(from, to, intact) { - // The first pass removes the DOM nodes that aren't intact. - if (!intact.length) lineDiv.innerHTML = ""; - else { - function killNode(node) { - var tmp = node.nextSibling; - node.parentNode.removeChild(node); - return tmp; - } - var domPos = 0, curNode = lineDiv.firstChild, n; - for (var i = 0; i < intact.length; ++i) { - var cur = intact[i]; - while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;} - for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;} - } - while (curNode) curNode = killNode(curNode); - } - // This pass fills in the lines that actually changed. - var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from; - var scratch = document.createElement("div"); - doc.iter(from, to, function(line) { - if (nextIntact && nextIntact.to == j) nextIntact = intact.shift(); - if (!nextIntact || nextIntact.from > j) { - if (line.hidden) var html = scratch.innerHTML = "
";
-          else {
-            var html = ''
-              + line.getHTML(makeTab) + '';
-            // Kludge to make sure the styled element lies behind the selection (by z-index)
-            if (line.bgClassName)
-              html = '
 
' + html + "
"; - } - scratch.innerHTML = html; - lineDiv.insertBefore(scratch.firstChild, curNode); - } else { - curNode = curNode.nextSibling; - } - ++j; - }); - } - - function updateGutter() { - if (!options.gutter && !options.lineNumbers) return; - var hText = mover.offsetHeight, hEditor = scroller.clientHeight; - gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px"; - var html = [], i = showingFrom, normalNode; - doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) { - if (line.hidden) { - html.push("
");
-        } else {
-          var marker = line.gutterMarker;
-          var text = options.lineNumbers ? i + options.firstLineNumber : null;
-          if (marker && marker.text)
-            text = marker.text.replace("%N%", text != null ? text : "");
-          else if (text == null)
-            text = "\u00a0";
-          html.push((marker && marker.style ? '
' : "
"), text);
-          for (var j = 1; j < line.height; ++j) html.push("
 "); - html.push("
"); - if (!marker) normalNode = i; - } - ++i; - }); - gutter.style.display = "none"; - gutterText.innerHTML = html.join(""); - // Make sure scrolling doesn't cause number gutter size to pop - if (normalNode != null) { - var node = gutterText.childNodes[normalNode - showingFrom]; - var minwidth = String(doc.size).length, val = eltText(node), pad = ""; - while (val.length + pad.length < minwidth) pad += "\u00a0"; - if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild); - } - gutter.style.display = ""; - var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2; - lineSpace.style.marginLeft = gutter.offsetWidth + "px"; - gutterDirty = false; - return resized; - } - function updateSelection() { - var collapsed = posEq(sel.from, sel.to); - var fromPos = localCoords(sel.from, true); - var toPos = collapsed ? fromPos : localCoords(sel.to, true); - var headPos = sel.inverted ? fromPos : toPos, th = textHeight(); - var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv); - inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px"; - inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px"; - if (collapsed) { - cursor.style.top = headPos.y + "px"; - cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px"; - cursor.style.display = ""; - selectionDiv.style.display = "none"; - } else { - var sameLine = fromPos.y == toPos.y, html = ""; - var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth; - var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight; - function add(left, top, right, height) { - var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px" - : "right: " + right + "px"; - html += '
'; - } - if (sel.from.ch && fromPos.y >= 0) { - var right = sameLine ? clientWidth - toPos.x : 0; - add(fromPos.x, fromPos.y, right, th); - } - var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0)); - var middleHeight = Math.min(toPos.y, clientHeight) - middleStart; - if (middleHeight > 0.2 * th) - add(0, middleStart, 0, middleHeight); - if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th) - add(0, toPos.y, clientWidth - toPos.x, th); - selectionDiv.innerHTML = html; - cursor.style.display = "none"; - selectionDiv.style.display = ""; - } - } - - function setShift(val) { - if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from); - else shiftSelecting = null; - } - function setSelectionUser(from, to) { - var sh = shiftSelecting && clipPos(shiftSelecting); - if (sh) { - if (posLess(sh, from)) from = sh; - else if (posLess(to, sh)) to = sh; - } - setSelection(from, to); - userSelChange = true; - } - // Update the selection. Last two args are only used by - // updateLines, since they have to be expressed in the line - // numbers before the update. - function setSelection(from, to, oldFrom, oldTo) { - goalColumn = null; - if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;} - if (posEq(sel.from, from) && posEq(sel.to, to)) return; - if (posLess(to, from)) {var tmp = to; to = from; from = tmp;} - - // Skip over hidden lines. - if (from.line != oldFrom) { - var from1 = skipHidden(from, oldFrom, sel.from.ch); - // If there is no non-hidden line left, force visibility on current line - if (!from1) setLineHidden(from.line, false); - else from = from1; - } - if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch); - - if (posEq(from, to)) sel.inverted = false; - else if (posEq(from, sel.to)) sel.inverted = false; - else if (posEq(to, sel.from)) sel.inverted = true; - - if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) { - var head = sel.inverted ? from : to; - if (head.line != sel.from.line && sel.from.line < doc.size) { - var oldLine = getLine(sel.from.line); - if (/^\s+$/.test(oldLine.text)) - setTimeout(operation(function() { - if (oldLine.parent && /^\s+$/.test(oldLine.text)) { - var no = lineNo(oldLine); - replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length}); - } - }, 10)); - } - } - - sel.from = from; sel.to = to; - selectionChanged = true; - } - function skipHidden(pos, oldLine, oldCh) { - function getNonHidden(dir) { - var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1; - while (lNo != end) { - var line = getLine(lNo); - if (!line.hidden) { - var ch = pos.ch; - if (toEnd || ch > oldCh || ch > line.text.length) ch = line.text.length; - return {line: lNo, ch: ch}; - } - lNo += dir; - } - } - var line = getLine(pos.line); - var toEnd = pos.ch == line.text.length && pos.ch != oldCh; - if (!line.hidden) return pos; - if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1); - else return getNonHidden(-1) || getNonHidden(1); - } - function setCursor(line, ch, user) { - var pos = clipPos({line: line, ch: ch || 0}); - (user ? setSelectionUser : setSelection)(pos, pos); - } - - function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));} - function clipPos(pos) { - if (pos.line < 0) return {line: 0, ch: 0}; - if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length}; - var ch = pos.ch, linelen = getLine(pos.line).text.length; - if (ch == null || ch > linelen) return {line: pos.line, ch: linelen}; - else if (ch < 0) return {line: pos.line, ch: 0}; - else return pos; - } - - function findPosH(dir, unit) { - var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch; - var lineObj = getLine(line); - function findNextLine() { - for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) { - var lo = getLine(l); - if (!lo.hidden) { line = l; lineObj = lo; return true; } - } - } - function moveOnce(boundToLine) { - if (ch == (dir < 0 ? 0 : lineObj.text.length)) { - if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0; - else return false; - } else ch += dir; - return true; - } - if (unit == "char") moveOnce(); - else if (unit == "column") moveOnce(true); - else if (unit == "word") { - var sawWord = false; - for (;;) { - if (dir < 0) if (!moveOnce()) break; - if (isWordChar(lineObj.text.charAt(ch))) sawWord = true; - else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;} - if (dir > 0) if (!moveOnce()) break; - } - } - return {line: line, ch: ch}; - } - function moveH(dir, unit) { - var pos = dir < 0 ? sel.from : sel.to; - if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit); - setCursor(pos.line, pos.ch, true); - } - function deleteH(dir, unit) { - if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to); - else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to); - else replaceRange("", sel.from, findPosH(dir, unit)); - userSelChange = true; - } - var goalColumn = null; - function moveV(dir, unit) { - var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true); - if (goalColumn != null) pos.x = goalColumn; - if (unit == "page") dist = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight); - else if (unit == "line") dist = textHeight(); - var target = coordsChar(pos.x, pos.y + dist * dir + 2); - if (unit == "page") scroller.scrollTop += localCoords(target, true).y - pos.y; - setCursor(target.line, target.ch, true); - goalColumn = pos.x; - } - - function selectWordAt(pos) { - var line = getLine(pos.line).text; - var start = pos.ch, end = pos.ch; - while (start > 0 && isWordChar(line.charAt(start - 1))) --start; - while (end < line.length && isWordChar(line.charAt(end))) ++end; - setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end}); - } - function selectLine(line) { - setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0})); - } - function indentSelected(mode) { - if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode); - var e = sel.to.line - (sel.to.ch ? 0 : 1); - for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode); - } - - function indentLine(n, how) { - if (!how) how = "add"; - if (how == "smart") { - if (!mode.indent) how = "prev"; - else var state = getStateBefore(n); - } - - var line = getLine(n), curSpace = line.indentation(options.tabSize), - curSpaceString = line.text.match(/^\s*/)[0], indentation; - if (how == "prev") { - if (n) indentation = getLine(n-1).indentation(options.tabSize); - else indentation = 0; - } - else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text); - else if (how == "add") indentation = curSpace + options.indentUnit; - else if (how == "subtract") indentation = curSpace - options.indentUnit; - indentation = Math.max(0, indentation); - var diff = indentation - curSpace; - - if (!diff) { - if (sel.from.line != n && sel.to.line != n) return; - var indentString = curSpaceString; - } - else { - var indentString = "", pos = 0; - if (options.indentWithTabs) - for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";} - while (pos < indentation) {++pos; indentString += " ";} - } - - replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}); - } - - function loadMode() { - mode = CodeMirror.getMode(options, options.mode); - doc.iter(0, doc.size, function(line) { line.stateAfter = null; }); - work = [0]; - startWorker(); - } - function gutterChanged() { - var visible = options.gutter || options.lineNumbers; - gutter.style.display = visible ? "" : "none"; - if (visible) gutterDirty = true; - else lineDiv.parentNode.style.marginLeft = 0; - } - function wrappingChanged(from, to) { - if (options.lineWrapping) { - wrapper.className += " CodeMirror-wrap"; - var perLine = scroller.clientWidth / charWidth() - 3; - doc.iter(0, doc.size, function(line) { - if (line.hidden) return; - var guess = Math.ceil(line.text.length / perLine) || 1; - if (guess != 1) updateLineHeight(line, guess); - }); - lineSpace.style.width = code.style.width = ""; - } else { - wrapper.className = wrapper.className.replace(" CodeMirror-wrap", ""); - maxWidth = null; maxLine = ""; - doc.iter(0, doc.size, function(line) { - if (line.height != 1 && !line.hidden) updateLineHeight(line, 1); - if (line.text.length > maxLine.length) maxLine = line.text; - }); - } - changes.push({from: 0, to: doc.size}); - } - function makeTab(col) { - var w = options.tabSize - col % options.tabSize, cached = tabCache[w]; - if (cached) return cached; - for (var str = '', i = 0; i < w; ++i) str += " "; - return (tabCache[w] = {html: str + "", width: w}); - } - function themeChanged() { - scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") + - options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - } - function keyMapChanged() { - var style = keyMap[options.keyMap].style; - wrapper.className = wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + - (style ? " cm-keymap-" + style : ""); - } - - function TextMarker() { this.set = []; } - TextMarker.prototype.clear = operation(function() { - var min = Infinity, max = -Infinity; - for (var i = 0, e = this.set.length; i < e; ++i) { - var line = this.set[i], mk = line.marked; - if (!mk || !line.parent) continue; - var lineN = lineNo(line); - min = Math.min(min, lineN); max = Math.max(max, lineN); - for (var j = 0; j < mk.length; ++j) - if (mk[j].marker == this) mk.splice(j--, 1); - } - if (min != Infinity) - changes.push({from: min, to: max + 1}); - }); - TextMarker.prototype.find = function() { - var from, to; - for (var i = 0, e = this.set.length; i < e; ++i) { - var line = this.set[i], mk = line.marked; - for (var j = 0; j < mk.length; ++j) { - var mark = mk[j]; - if (mark.marker == this) { - if (mark.from != null || mark.to != null) { - var found = lineNo(line); - if (found != null) { - if (mark.from != null) from = {line: found, ch: mark.from}; - if (mark.to != null) to = {line: found, ch: mark.to}; - } - } - } - } - } - return {from: from, to: to}; - }; - - function markText(from, to, className) { - from = clipPos(from); to = clipPos(to); - var tm = new TextMarker(); - if (!posLess(from, to)) return tm; - function add(line, from, to, className) { - getLine(line).addMark(new MarkedText(from, to, className, tm)); - } - if (from.line == to.line) add(from.line, from.ch, to.ch, className); - else { - add(from.line, from.ch, null, className); - for (var i = from.line + 1, e = to.line; i < e; ++i) - add(i, null, null, className); - add(to.line, null, to.ch, className); - } - changes.push({from: from.line, to: to.line + 1}); - return tm; - } - - function setBookmark(pos) { - pos = clipPos(pos); - var bm = new Bookmark(pos.ch); - getLine(pos.line).addMark(bm); - return bm; - } - - function findMarksAt(pos) { - pos = clipPos(pos); - var markers = [], marked = getLine(pos.line).marked; - if (!marked) return markers; - for (var i = 0, e = marked.length; i < e; ++i) { - var m = marked[i]; - if ((m.from == null || m.from <= pos.ch) && - (m.to == null || m.to >= pos.ch)) - markers.push(m.marker || m); - } - return markers; - } - - function addGutterMarker(line, text, className) { - if (typeof line == "number") line = getLine(clipLine(line)); - line.gutterMarker = {text: text, style: className}; - gutterDirty = true; - return line; - } - function removeGutterMarker(line) { - if (typeof line == "number") line = getLine(clipLine(line)); - line.gutterMarker = null; - gutterDirty = true; - } - - function changeLine(handle, op) { - var no = handle, line = handle; - if (typeof handle == "number") line = getLine(clipLine(handle)); - else no = lineNo(handle); - if (no == null) return null; - if (op(line, no)) changes.push({from: no, to: no + 1}); - else return null; - return line; - } - function setLineClass(handle, className, bgClassName) { - return changeLine(handle, function(line) { - if (line.className != className || line.bgClassName != bgClassName) { - line.className = className; - line.bgClassName = bgClassName; - return true; - } - }); - } - function setLineHidden(handle, hidden) { - return changeLine(handle, function(line, no) { - if (line.hidden != hidden) { - line.hidden = hidden; - if (!options.lineWrapping) { - var l = line.text; - if (hidden && l.length == maxLine.length) { - maxLengthChanged = true; - } - else if (!hidden && l.length > maxLine.length) { - maxLine = l; maxWidth = null; - maxLengthChanged = false; - } - } - updateLineHeight(line, hidden ? 0 : 1); - var fline = sel.from.line, tline = sel.to.line; - if (hidden && (fline == no || tline == no)) { - var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from; - var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to; - // Can't hide the last visible line, we'd have no place to put the cursor - if (!to) return; - setSelection(from, to); - } - return (gutterDirty = true); - } - }); - } - - function lineInfo(line) { - if (typeof line == "number") { - if (!isLine(line)) return null; - var n = line; - line = getLine(line); - if (!line) return null; - } - else { - var n = lineNo(line); - if (n == null) return null; - } - var marker = line.gutterMarker; - return {line: n, handle: line, text: line.text, markerText: marker && marker.text, - markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName}; - } - - function stringWidth(str) { - measure.innerHTML = "
x
"; - measure.firstChild.firstChild.firstChild.nodeValue = str; - return measure.firstChild.firstChild.offsetWidth || 10; - } - // These are used to go from pixel positions to character - // positions, taking varying character widths into account. - function charFromX(line, x) { - if (x <= 0) return 0; - var lineObj = getLine(line), text = lineObj.text; - function getX(len) { - return measureLine(lineObj, len).left; - } - var from = 0, fromX = 0, to = text.length, toX; - // Guess a suitable upper bound for our search. - var estimated = Math.min(to, Math.ceil(x / charWidth())); - for (;;) { - var estX = getX(estimated); - if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); - else {toX = estX; to = estimated; break;} - } - if (x > toX) return to; - // Try to guess a suitable lower bound as well. - estimated = Math.floor(to * 0.8); estX = getX(estimated); - if (estX < x) {from = estimated; fromX = estX;} - // Do a binary search between these bounds. - for (;;) { - if (to - from <= 1) return (toX - x > x - fromX) ? from : to; - var middle = Math.ceil((from + to) / 2), middleX = getX(middle); - if (middleX > x) {to = middle; toX = middleX;} - else {from = middle; fromX = middleX;} - } - } - - var tempId = "CodeMirror-temp-" + Math.floor(Math.random() * 0xffffff).toString(16); - function measureLine(line, ch) { - if (ch == 0) return {top: 0, left: 0}; - var wbr = options.lineWrapping && ch < line.text.length && - spanAffectsWrapping.test(line.text.slice(ch - 1, ch + 1)); - measure.innerHTML = "
" + line.getHTML(makeTab, ch, tempId, wbr) + "
"; - var elt = document.getElementById(tempId); - var top = elt.offsetTop, left = elt.offsetLeft; - // Older IEs report zero offsets for spans directly after a wrap - if (ie && top == 0 && left == 0) { - var backup = document.createElement("span"); - backup.innerHTML = "x"; - elt.parentNode.insertBefore(backup, elt.nextSibling); - top = backup.offsetTop; - } - return {top: top, left: left}; - } - function localCoords(pos, inLineWrap) { - var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0)); - if (pos.ch == 0) x = 0; - else { - var sp = measureLine(getLine(pos.line), pos.ch); - x = sp.left; - if (options.lineWrapping) y += Math.max(0, sp.top); - } - return {x: x, y: y, yBot: y + lh}; - } - // Coords must be lineSpace-local - function coordsChar(x, y) { - if (y < 0) y = 0; - var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th); - var lineNo = lineAtHeight(doc, heightPos); - if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length}; - var lineObj = getLine(lineNo), text = lineObj.text; - var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0; - if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0}; - function getX(len) { - var sp = measureLine(lineObj, len); - if (tw) { - var off = Math.round(sp.top / th); - return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth); - } - return sp.left; - } - var from = 0, fromX = 0, to = text.length, toX; - // Guess a suitable upper bound for our search. - var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw)); - for (;;) { - var estX = getX(estimated); - if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); - else {toX = estX; to = estimated; break;} - } - if (x > toX) return {line: lineNo, ch: to}; - // Try to guess a suitable lower bound as well. - estimated = Math.floor(to * 0.8); estX = getX(estimated); - if (estX < x) {from = estimated; fromX = estX;} - // Do a binary search between these bounds. - for (;;) { - if (to - from <= 1) return {line: lineNo, ch: (toX - x > x - fromX) ? from : to}; - var middle = Math.ceil((from + to) / 2), middleX = getX(middle); - if (middleX > x) {to = middle; toX = middleX;} - else {from = middle; fromX = middleX;} - } - } - function pageCoords(pos) { - var local = localCoords(pos, true), off = eltOffset(lineSpace); - return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot}; - } - - var cachedHeight, cachedHeightFor, measureText; - function textHeight() { - if (measureText == null) { - measureText = "
";
-        for (var i = 0; i < 49; ++i) measureText += "x
"; - measureText += "x
"; - } - var offsetHeight = lineDiv.clientHeight; - if (offsetHeight == cachedHeightFor) return cachedHeight; - cachedHeightFor = offsetHeight; - measure.innerHTML = measureText; - cachedHeight = measure.firstChild.offsetHeight / 50 || 1; - measure.innerHTML = ""; - return cachedHeight; - } - var cachedWidth, cachedWidthFor = 0; - function charWidth() { - if (scroller.clientWidth == cachedWidthFor) return cachedWidth; - cachedWidthFor = scroller.clientWidth; - return (cachedWidth = stringWidth("x")); - } - function paddingTop() {return lineSpace.offsetTop;} - function paddingLeft() {return lineSpace.offsetLeft;} - - function posFromMouse(e, liberal) { - var offW = eltOffset(scroller, true), x, y; - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { x = e.clientX; y = e.clientY; } catch (e) { return null; } - // This is a mess of a heuristic to try and determine whether a - // scroll-bar was clicked or not, and to return null if one was - // (and !liberal). - if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight)) - return null; - var offL = eltOffset(lineSpace, true); - return coordsChar(x - offL.left, y - offL.top); - } - function onContextMenu(e) { - var pos = posFromMouse(e), scrollPos = scroller.scrollTop; - if (!pos || window.opera) return; // Opera is difficult. - if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) - operation(setCursor)(pos.line, pos.ch); - - var oldCSS = input.style.cssText; - inputDiv.style.position = "absolute"; - input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + - "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " + - "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - leaveInputAlone = true; - var val = input.value = getSelection(); - focusInput(); - selectInput(input); - function rehide() { - var newVal = splitLines(input.value).join("\n"); - if (newVal != val) operation(replaceSelection)(newVal, "end"); - inputDiv.style.position = "relative"; - input.style.cssText = oldCSS; - if (ie_lt9) scroller.scrollTop = scrollPos; - leaveInputAlone = false; - resetInput(true); - slowPoll(); - } - - if (gecko) { - e_stop(e); - var mouseup = connect(window, "mouseup", function() { - mouseup(); - setTimeout(rehide, 20); - }, true); - } else { - setTimeout(rehide, 50); - } - } - - // Cursor-blinking - function restartBlink() { - clearInterval(blinker); - var on = true; - cursor.style.visibility = ""; - blinker = setInterval(function() { - cursor.style.visibility = (on = !on) ? "" : "hidden"; - }, 650); - } - - var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; - function matchBrackets(autoclear) { - var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1; - var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; - if (!match) return; - var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles; - for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2) - if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;} - - var stack = [line.text.charAt(pos)], re = /[(){}[\]]/; - function scan(line, from, to) { - if (!line.text) return; - var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur; - for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) { - var text = st[i]; - if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;} - for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) { - if (pos >= from && pos < to && re.test(cur = text.charAt(j))) { - var match = matching[cur]; - if (match.charAt(1) == ">" == forward) stack.push(cur); - else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false}; - else if (!stack.length) return {pos: pos, match: true}; - } - } - } - } - for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) { - var line = getLine(i), first = i == head.line; - var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length); - if (found) break; - } - if (!found) found = {pos: null, match: false}; - var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; - var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style), - two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style); - var clear = operation(function(){one.clear(); two && two.clear();}); - if (autoclear) setTimeout(clear, 800); - else bracketHighlighted = clear; - } - - // Finds the line to start with when starting a parse. Tries to - // find a line with a stateAfter, so that it can start with a - // valid state. If that fails, it returns the line with the - // smallest indentation, which tends to need the least context to - // parse correctly. - function findStartLine(n) { - var minindent, minline; - for (var search = n, lim = n - 40; search > lim; --search) { - if (search == 0) return 0; - var line = getLine(search-1); - if (line.stateAfter) return search; - var indented = line.indentation(options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline; - } - function getStateBefore(n) { - var start = findStartLine(n), state = start && getLine(start-1).stateAfter; - if (!state) state = startState(mode); - else state = copyState(mode, state); - doc.iter(start, n, function(line) { - line.highlight(mode, state, options.tabSize); - line.stateAfter = copyState(mode, state); - }); - if (start < n) changes.push({from: start, to: n}); - if (n < doc.size && !getLine(n).stateAfter) work.push(n); - return state; - } - function highlightLines(start, end) { - var state = getStateBefore(start); - doc.iter(start, end, function(line) { - line.highlight(mode, state, options.tabSize); - line.stateAfter = copyState(mode, state); - }); - } - function highlightWorker() { - var end = +new Date + options.workTime; - var foundWork = work.length; - while (work.length) { - if (!getLine(showingFrom).stateAfter) var task = showingFrom; - else var task = work.pop(); - if (task >= doc.size) continue; - var start = findStartLine(task), state = start && getLine(start-1).stateAfter; - if (state) state = copyState(mode, state); - else state = startState(mode); - - var unchanged = 0, compare = mode.compareStates, realChange = false, - i = start, bail = false; - doc.iter(i, doc.size, function(line) { - var hadState = line.stateAfter; - if (+new Date > end) { - work.push(i); - startWorker(options.workDelay); - if (realChange) changes.push({from: task, to: i + 1}); - return (bail = true); - } - var changed = line.highlight(mode, state, options.tabSize); - if (changed) realChange = true; - line.stateAfter = copyState(mode, state); - var done = null; - if (compare) { - var same = hadState && compare(hadState, state); - if (same != Pass) done = !!same; - } - if (done == null) { - if (changed !== false || !hadState) unchanged = 0; - else if (++unchanged > 3 && (!mode.indent || mode.indent(hadState, "") == mode.indent(state, ""))) - done = true; - } - if (done) return true; - ++i; - }); - if (bail) return; - if (realChange) changes.push({from: task, to: i + 1}); - } - if (foundWork && options.onHighlightComplete) - options.onHighlightComplete(instance); - } - function startWorker(time) { - if (!work.length) return; - highlight.set(time, operation(highlightWorker)); - } - - // Operations are used to wrap changes in such a way that each - // change won't have to update the cursor and display (which would - // be awkward, slow, and error-prone), but instead updates are - // batched and then all combined and executed at once. - function startOperation() { - updateInput = userSelChange = textChanged = null; - changes = []; selectionChanged = false; callbacks = []; - } - function endOperation() { - var reScroll = false, updated; - if (maxLengthChanged) computeMaxLength(); - if (selectionChanged) reScroll = !scrollCursorIntoView(); - if (changes.length) updated = updateDisplay(changes, true); - else { - if (selectionChanged) updateSelection(); - if (gutterDirty) updateGutter(); - } - if (reScroll) scrollCursorIntoView(); - if (selectionChanged) {scrollEditorIntoView(); restartBlink();} - - if (focused && !leaveInputAlone && - (updateInput === true || (updateInput !== false && selectionChanged))) - resetInput(userSelChange); - - if (selectionChanged && options.matchBrackets) - setTimeout(operation(function() { - if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;} - if (posEq(sel.from, sel.to)) matchBrackets(false); - }), 20); - var tc = textChanged, cbs = callbacks; // these can be reset by callbacks - if (selectionChanged && options.onCursorActivity) - options.onCursorActivity(instance); - if (tc && options.onChange && instance) - options.onChange(instance, tc); - for (var i = 0; i < cbs.length; ++i) cbs[i](instance); - if (updated && options.onUpdate) options.onUpdate(instance); - } - var nestedOperation = 0; - function operation(f) { - return function() { - if (!nestedOperation++) startOperation(); - try {var result = f.apply(this, arguments);} - finally {if (!--nestedOperation) endOperation();} - return result; - }; - } - - function compoundChange(f) { - history.startCompound(); - try { return f(); } finally { history.endCompound(); } - } - - for (var ext in extensions) - if (extensions.propertyIsEnumerable(ext) && - !instance.propertyIsEnumerable(ext)) - instance[ext] = extensions[ext]; - return instance; - } // (end of function CodeMirror) - - // The default configuration options. - CodeMirror.defaults = { - value: "", - mode: null, - theme: "default", - indentUnit: 2, - indentWithTabs: false, - smartIndent: true, - tabSize: 4, - keyMap: "default", - extraKeys: null, - electricChars: true, - autoClearEmptyLines: false, - onKeyEvent: null, - onDragEvent: null, - lineWrapping: false, - lineNumbers: false, - gutter: false, - fixedGutter: false, - firstLineNumber: 1, - readOnly: false, - dragDrop: true, - onChange: null, - onCursorActivity: null, - onGutterClick: null, - onHighlightComplete: null, - onUpdate: null, - onFocus: null, onBlur: null, onScroll: null, - matchBrackets: false, - workTime: 100, - workDelay: 200, - pollInterval: 100, - undoDepth: 40, - tabindex: null, - autofocus: null - }; - - var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); - var mac = ios || /Mac/.test(navigator.platform); - var win = /Win/.test(navigator.platform); - - // Known modes, by name and by MIME - var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; - CodeMirror.defineMode = function(name, mode) { - if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; - if (arguments.length > 2) { - mode.dependencies = []; - for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); - } - modes[name] = mode; - }; - CodeMirror.defineMIME = function(mime, spec) { - mimeModes[mime] = spec; - }; - CodeMirror.resolveMode = function(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) - spec = mimeModes[spec]; - else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) - return CodeMirror.resolveMode("application/xml"); - if (typeof spec == "string") return {name: spec}; - else return spec || {name: "null"}; - }; - CodeMirror.getMode = function(options, spec) { - var spec = CodeMirror.resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) return CodeMirror.getMode(options, "text/plain"); - return mfactory(options, spec); - }; - CodeMirror.listModes = function() { - var list = []; - for (var m in modes) - if (modes.propertyIsEnumerable(m)) list.push(m); - return list; - }; - CodeMirror.listMIMEs = function() { - var list = []; - for (var m in mimeModes) - if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]}); - return list; - }; - - var extensions = CodeMirror.extensions = {}; - CodeMirror.defineExtension = function(name, func) { - extensions[name] = func; - }; - - var commands = CodeMirror.commands = { - selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});}, - killLine: function(cm) { - var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); - if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0}); - else cm.replaceRange("", from, sel ? to : {line: from.line}); - }, - deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});}, - undo: function(cm) {cm.undo();}, - redo: function(cm) {cm.redo();}, - goDocStart: function(cm) {cm.setCursor(0, 0, true);}, - goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);}, - goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);}, - goLineStartSmart: function(cm) { - var cur = cm.getCursor(); - var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/)); - cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true); - }, - goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);}, - goLineUp: function(cm) {cm.moveV(-1, "line");}, - goLineDown: function(cm) {cm.moveV(1, "line");}, - goPageUp: function(cm) {cm.moveV(-1, "page");}, - goPageDown: function(cm) {cm.moveV(1, "page");}, - goCharLeft: function(cm) {cm.moveH(-1, "char");}, - goCharRight: function(cm) {cm.moveH(1, "char");}, - goColumnLeft: function(cm) {cm.moveH(-1, "column");}, - goColumnRight: function(cm) {cm.moveH(1, "column");}, - goWordLeft: function(cm) {cm.moveH(-1, "word");}, - goWordRight: function(cm) {cm.moveH(1, "word");}, - delCharLeft: function(cm) {cm.deleteH(-1, "char");}, - delCharRight: function(cm) {cm.deleteH(1, "char");}, - delWordLeft: function(cm) {cm.deleteH(-1, "word");}, - delWordRight: function(cm) {cm.deleteH(1, "word");}, - indentAuto: function(cm) {cm.indentSelection("smart");}, - indentMore: function(cm) {cm.indentSelection("add");}, - indentLess: function(cm) {cm.indentSelection("subtract");}, - insertTab: function(cm) {cm.replaceSelection("\t", "end");}, - defaultTab: function(cm) { - if (cm.somethingSelected()) cm.indentSelection("add"); - else cm.replaceSelection("\t", "end"); - }, - transposeChars: function(cm) { - var cur = cm.getCursor(), line = cm.getLine(cur.line); - if (cur.ch > 0 && cur.ch < line.length - 1) - cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), - {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1}); - }, - newlineAndIndent: function(cm) { - cm.replaceSelection("\n", "end"); - cm.indentLine(cm.getCursor().line); - }, - toggleOverwrite: function(cm) {cm.toggleOverwrite();} - }; - - var keyMap = CodeMirror.keyMap = {}; - keyMap.basic = { - "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", - "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", - "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "defaultTab", "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" - }; - // Note that the save and find-related commands aren't defined by - // default. Unknown commands are simply ignored. - keyMap.pcDefault = { - "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", - "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find", - "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", - fallthrough: "basic" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", - "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft", - "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft", - "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find", - "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", "Cmd-]": "indentMore", - fallthrough: ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - keyMap.emacsy = { - "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", - "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft", - "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" - }; - - function getKeyMap(val) { - if (typeof val == "string") return keyMap[val]; - else return val; - } - function lookupKey(name, extraMap, map, handle, stop) { - function lookup(map) { - map = getKeyMap(map); - var found = map[name]; - if (found != null && handle(found)) return true; - if (map.nofallthrough) { - if (stop) stop(); - return true; - } - var fallthrough = map.fallthrough; - if (fallthrough == null) return false; - if (Object.prototype.toString.call(fallthrough) != "[object Array]") - return lookup(fallthrough); - for (var i = 0, e = fallthrough.length; i < e; ++i) { - if (lookup(fallthrough[i])) return true; - } - return false; - } - if (extraMap && lookup(extraMap)) return true; - return lookup(map); - } - function isModifierKey(event) { - var name = keyNames[e_prop(event, "keyCode")]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - } - - CodeMirror.fromTextArea = function(textarea, options) { - if (!options) options = {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabindex) - options.tabindex = textarea.tabindex; - if (options.autofocus == null && textarea.getAttribute("autofocus") != null) - options.autofocus = true; - - function save() {textarea.value = instance.getValue();} - if (textarea.form) { - // Deplorable hack to make the submit method do the right thing. - var rmSubmit = connect(textarea.form, "submit", save, true); - if (typeof textarea.form.submit == "function") { - var realSubmit = textarea.form.submit; - function wrappedSubmit() { - save(); - textarea.form.submit = realSubmit; - textarea.form.submit(); - textarea.form.submit = wrappedSubmit; - } - textarea.form.submit = wrappedSubmit; - } - } - - textarea.style.display = "none"; - var instance = CodeMirror(function(node) { - textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - instance.save = save; - instance.getTextArea = function() { return textarea; }; - instance.toTextArea = function() { - save(); - textarea.parentNode.removeChild(instance.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - rmSubmit(); - if (typeof textarea.form.submit == "function") - textarea.form.submit = realSubmit; - } - }; - return instance; - }; - - // Utility functions for working with state. Exported because modes - // sometimes need to do this. - function copyState(mode, state) { - if (state === true) return state; - if (mode.copyState) return mode.copyState(state); - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) val = val.concat([]); - nstate[n] = val; - } - return nstate; - } - CodeMirror.copyState = copyState; - function startState(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - } - CodeMirror.startState = startState; - - // The character stream used by a mode's parser. - function StringStream(string, tabSize) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - } - StringStream.prototype = { - eol: function() {return this.pos >= this.string.length;}, - sol: function() {return this.pos == 0;}, - peek: function() {return this.string.charAt(this.pos);}, - next: function() { - if (this.pos < this.string.length) - return this.string.charAt(this.pos++); - }, - eat: function(match) { - var ch = this.string.charAt(this.pos); - if (typeof match == "string") var ok = ch == match; - else var ok = ch && (match.test ? match.test(ch) : match(ch)); - if (ok) {++this.pos; return ch;} - }, - eatWhile: function(match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start; - }, - eatSpace: function() { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; - return this.pos > start; - }, - skipToEnd: function() {this.pos = this.string.length;}, - skipTo: function(ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true;} - }, - backUp: function(n) {this.pos -= n;}, - column: function() {return countColumn(this.string, this.start, this.tabSize);}, - indentation: function() {return countColumn(this.string, null, this.tabSize);}, - match: function(pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - function cased(str) {return caseInsensitive ? str.toLowerCase() : str;} - if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { - if (consume !== false) this.pos += pattern.length; - return true; - } - } - else { - var match = this.string.slice(this.pos).match(pattern); - if (match && consume !== false) this.pos += match[0].length; - return match; - } - }, - current: function(){return this.string.slice(this.start, this.pos);} - }; - CodeMirror.StringStream = StringStream; - - function MarkedText(from, to, className, marker) { - this.from = from; this.to = to; this.style = className; this.marker = marker; - } - MarkedText.prototype = { - attach: function(line) { this.marker.set.push(line); }, - detach: function(line) { - var ix = indexOf(this.marker.set, line); - if (ix > -1) this.marker.set.splice(ix, 1); - }, - split: function(pos, lenBefore) { - if (this.to <= pos && this.to != null) return null; - var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore; - var to = this.to == null ? null : this.to - pos + lenBefore; - return new MarkedText(from, to, this.style, this.marker); - }, - dup: function() { return new MarkedText(null, null, this.style, this.marker); }, - clipTo: function(fromOpen, from, toOpen, to, diff) { - if (fromOpen && to > this.from && (to < this.to || this.to == null)) - this.from = null; - else if (this.from != null && this.from >= from) - this.from = Math.max(to, this.from) + diff; - if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null)) - this.to = null; - else if (this.to != null && this.to > from) - this.to = to < this.to ? this.to + diff : from; - }, - isDead: function() { return this.from != null && this.to != null && this.from >= this.to; }, - sameSet: function(x) { return this.marker == x.marker; } - }; - - function Bookmark(pos) { - this.from = pos; this.to = pos; this.line = null; - } - Bookmark.prototype = { - attach: function(line) { this.line = line; }, - detach: function(line) { if (this.line == line) this.line = null; }, - split: function(pos, lenBefore) { - if (pos < this.from) { - this.from = this.to = (this.from - pos) + lenBefore; - return this; - } - }, - isDead: function() { return this.from > this.to; }, - clipTo: function(fromOpen, from, toOpen, to, diff) { - if ((fromOpen || from < this.from) && (toOpen || to > this.to)) { - this.from = 0; this.to = -1; - } else if (this.from > from) { - this.from = this.to = Math.max(to, this.from) + diff; - } - }, - sameSet: function(x) { return false; }, - find: function() { - if (!this.line || !this.line.parent) return null; - return {line: lineNo(this.line), ch: this.from}; - }, - clear: function() { - if (this.line) { - var found = indexOf(this.line.marked, this); - if (found != -1) this.line.marked.splice(found, 1); - this.line = null; - } - } - }; - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - function Line(text, styles) { - this.styles = styles || [text, null]; - this.text = text; - this.height = 1; - this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null; - this.stateAfter = this.parent = this.hidden = null; - } - Line.inheritMarks = function(text, orig) { - var ln = new Line(text), mk = orig && orig.marked; - if (mk) { - for (var i = 0; i < mk.length; ++i) { - if (mk[i].to == null && mk[i].style) { - var newmk = ln.marked || (ln.marked = []), mark = mk[i]; - var nmark = mark.dup(); newmk.push(nmark); nmark.attach(ln); - } - } - } - return ln; - } - Line.prototype = { - // Replace a piece of a line, keeping the styles around it intact. - replace: function(from, to_, text) { - var st = [], mk = this.marked, to = to_ == null ? this.text.length : to_; - copyStyles(0, from, this.styles, st); - if (text) st.push(text, null); - copyStyles(to, this.text.length, this.styles, st); - this.styles = st; - this.text = this.text.slice(0, from) + text + this.text.slice(to); - this.stateAfter = null; - if (mk) { - var diff = text.length - (to - from); - for (var i = 0; i < mk.length; ++i) { - var mark = mk[i]; - mark.clipTo(from == null, from || 0, to_ == null, to, diff); - if (mark.isDead()) {mark.detach(this); mk.splice(i--, 1);} - } - } - }, - // Split a part off a line, keeping styles and markers intact. - split: function(pos, textBefore) { - var st = [textBefore, null], mk = this.marked; - copyStyles(pos, this.text.length, this.styles, st); - var taken = new Line(textBefore + this.text.slice(pos), st); - if (mk) { - for (var i = 0; i < mk.length; ++i) { - var mark = mk[i]; - var newmark = mark.split(pos, textBefore.length); - if (newmark) { - if (!taken.marked) taken.marked = []; - taken.marked.push(newmark); newmark.attach(taken); - if (newmark == mark) mk.splice(i--, 1); - } - } - } - return taken; - }, - append: function(line) { - var mylen = this.text.length, mk = line.marked, mymk = this.marked; - this.text += line.text; - copyStyles(0, line.text.length, line.styles, this.styles); - if (mymk) { - for (var i = 0; i < mymk.length; ++i) - if (mymk[i].to == null) mymk[i].to = mylen; - } - if (mk && mk.length) { - if (!mymk) this.marked = mymk = []; - outer: for (var i = 0; i < mk.length; ++i) { - var mark = mk[i]; - if (!mark.from) { - for (var j = 0; j < mymk.length; ++j) { - var mymark = mymk[j]; - if (mymark.to == mylen && mymark.sameSet(mark)) { - mymark.to = mark.to == null ? null : mark.to + mylen; - if (mymark.isDead()) { - mymark.detach(this); - mk.splice(i--, 1); - } - continue outer; - } - } - } - mymk.push(mark); - mark.attach(this); - mark.from += mylen; - if (mark.to != null) mark.to += mylen; - } - } - }, - fixMarkEnds: function(other) { - var mk = this.marked, omk = other.marked; - if (!mk) return; - for (var i = 0; i < mk.length; ++i) { - var mark = mk[i], close = mark.to == null; - if (close && omk) { - for (var j = 0; j < omk.length; ++j) - if (omk[j].sameSet(mark)) {close = false; break;} - } - if (close) mark.to = this.text.length; - } - }, - fixMarkStarts: function() { - var mk = this.marked; - if (!mk) return; - for (var i = 0; i < mk.length; ++i) - if (mk[i].from == null) mk[i].from = 0; - }, - addMark: function(mark) { - mark.attach(this); - if (this.marked == null) this.marked = []; - this.marked.push(mark); - this.marked.sort(function(a, b){return (a.from || 0) - (b.from || 0);}); - }, - // Run the given mode's parser over a line, update the styles - // array, which contains alternating fragments of text and CSS - // classes. - highlight: function(mode, state, tabSize) { - var stream = new StringStream(this.text, tabSize), st = this.styles, pos = 0; - var changed = false, curWord = st[0], prevWord; - if (this.text == "" && mode.blankLine) mode.blankLine(state); - while (!stream.eol()) { - var style = mode.token(stream, state); - var substr = this.text.slice(stream.start, stream.pos); - stream.start = stream.pos; - if (pos && st[pos-1] == style) - st[pos-2] += substr; - else if (substr) { - if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true; - st[pos++] = substr; st[pos++] = style; - prevWord = curWord; curWord = st[pos]; - } - // Give up when line is ridiculously long - if (stream.pos > 5000) { - st[pos++] = this.text.slice(stream.pos); st[pos++] = null; - break; - } - } - if (st.length != pos) {st.length = pos; changed = true;} - if (pos && st[pos-2] != prevWord) changed = true; - // Short lines with simple highlights return null, and are - // counted as changed by the driver because they are likely to - // highlight the same way in various contexts. - return changed || (st.length < 5 && this.text.length < 10 ? null : false); - }, - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function(mode, state, ch) { - var txt = this.text, stream = new StringStream(txt); - while (stream.pos < ch && !stream.eol()) { - stream.start = stream.pos; - var style = mode.token(stream, state); - } - return {start: stream.start, - end: stream.pos, - string: stream.current(), - className: style || null, - state: state}; - }, - indentation: function(tabSize) {return countColumn(this.text, null, tabSize);}, - // Produces an HTML fragment for the line, taking selection, - // marking, and highlighting into account. - getHTML: function(makeTab, wrapAt, wrapId, wrapWBR) { - var html = [], first = true, col = 0; - function span_(text, style) { - if (!text) return; - // Work around a bug where, in some compat modes, IE ignores leading spaces - if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1); - first = false; - if (text.indexOf("\t") == -1) { - col += text.length; - var escaped = htmlEscape(text); - } else { - var escaped = ""; - for (var pos = 0;;) { - var idx = text.indexOf("\t", pos); - if (idx == -1) { - escaped += htmlEscape(text.slice(pos)); - col += text.length - pos; - break; - } else { - col += idx - pos; - var tab = makeTab(col); - escaped += htmlEscape(text.slice(pos, idx)) + tab.html; - col += tab.width; - pos = idx + 1; - } - } - } - if (style) html.push('', escaped, ""); - else html.push(escaped); - } - var span = span_; - if (wrapAt != null) { - var outPos = 0, open = ""; - span = function(text, style) { - var l = text.length; - if (wrapAt >= outPos && wrapAt < outPos + l) { - if (wrapAt > outPos) { - span_(text.slice(0, wrapAt - outPos), style); - // See comment at the definition of spanAffectsWrapping - if (wrapWBR) html.push(""); - } - html.push(open); - var cut = wrapAt - outPos; - span_(window.opera ? text.slice(cut, cut + 1) : text.slice(cut), style); - html.push(""); - if (window.opera) span_(text.slice(cut + 1), style); - wrapAt--; - outPos += l; - } else { - outPos += l; - span_(text, style); - // Output empty wrapper when at end of line - if (outPos == wrapAt && outPos == len) html.push(open + " "); - // Stop outputting HTML when gone sufficiently far beyond measure - else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){}; - } - } - } - - var st = this.styles, allText = this.text, marked = this.marked; - var len = allText.length; - function styleToClass(style) { - if (!style) return null; - return "cm-" + style.replace(/ +/g, " cm-"); - } - - if (!allText && wrapAt == null) { - span(" "); - } else if (!marked || !marked.length) { - for (var i = 0, ch = 0; ch < len; i+=2) { - var str = st[i], style = st[i+1], l = str.length; - if (ch + l > len) str = str.slice(0, len - ch); - ch += l; - span(str, styleToClass(style)); - } - } else { - var pos = 0, i = 0, text = "", style, sg = 0; - var nextChange = marked[0].from || 0, marks = [], markpos = 0; - function advanceMarks() { - var m; - while (markpos < marked.length && - ((m = marked[markpos]).from == pos || m.from == null)) { - if (m.style != null) marks.push(m); - ++markpos; - } - nextChange = markpos < marked.length ? marked[markpos].from : Infinity; - for (var i = 0; i < marks.length; ++i) { - var to = marks[i].to || Infinity; - if (to == pos) marks.splice(i--, 1); - else nextChange = Math.min(to, nextChange); - } - } - var m = 0; - while (pos < len) { - if (nextChange == pos) advanceMarks(); - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - var appliedStyle = style; - for (var j = 0; j < marks.length; ++j) - appliedStyle = (appliedStyle ? appliedStyle + " " : "") + marks[j].style; - span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle); - if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} - pos = end; - } - text = st[i++]; style = styleToClass(st[i++]); - } - } - } - return html.join(""); - }, - cleanUp: function() { - this.parent = null; - if (this.marked) - for (var i = 0, e = this.marked.length; i < e; ++i) this.marked[i].detach(this); - } - }; - // Utility used by replace and split above - function copyStyles(from, to, source, dest) { - for (var i = 0, pos = 0, state = 0; pos < to; i+=2) { - var part = source[i], end = pos + part.length; - if (state == 0) { - if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]); - if (end >= from) state = 1; - } - else if (state == 1) { - if (end > to) dest.push(part.slice(0, to - pos), source[i+1]); - else dest.push(part, source[i+1]); - } - pos = end; - } - } - - // Data structure that holds the sequence of lines. - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - for (var i = 0, e = lines.length, height = 0; i < e; ++i) { - lines[i].parent = this; - height += lines[i].height; - } - this.height = height; - } - LeafChunk.prototype = { - chunkSize: function() { return this.lines.length; }, - remove: function(at, n, callbacks) { - for (var i = at, e = at + n; i < e; ++i) { - var line = this.lines[i]; - this.height -= line.height; - line.cleanUp(); - if (line.handlers) - for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]); - } - this.lines.splice(at, n); - }, - collapse: function(lines) { - lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); - }, - insertHeight: function(at, lines, height) { - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; - }, - iterN: function(at, n, op) { - for (var e = at + n; at < e; ++at) - if (op(this.lines[at])) return true; - } - }; - function BranchChunk(children) { - this.children = children; - var size = 0, height = 0; - for (var i = 0, e = children.length; i < e; ++i) { - var ch = children[i]; - size += ch.chunkSize(); height += ch.height; - ch.parent = this; - } - this.size = size; - this.height = height; - this.parent = null; - } - BranchChunk.prototype = { - chunkSize: function() { return this.size; }, - remove: function(at, n, callbacks) { - this.size -= n; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), oldHeight = child.height; - child.remove(at, rm, callbacks); - this.height -= oldHeight - child.height; - if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } - if ((n -= rm) == 0) break; - at = 0; - } else at -= sz; - } - if (this.size - n < 25) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - collapse: function(lines) { - for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); - }, - insert: function(at, lines) { - var height = 0; - for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; - this.insertHeight(at, lines, height); - }, - insertHeight: function(at, lines, height) { - this.size += lines.length; - this.height += height; - for (var i = 0, e = this.children.length; i < e; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at <= sz) { - child.insertHeight(at, lines, height); - if (child.lines && child.lines.length > 50) { - while (child.lines.length > 50) { - var spilled = child.lines.splice(child.lines.length - 25, 25); - var newleaf = new LeafChunk(spilled); - child.height -= newleaf.height; - this.children.splice(i + 1, 0, newleaf); - newleaf.parent = this; - } - this.maybeSpill(); - } - break; - } - at -= sz; - } - }, - maybeSpill: function() { - if (this.children.length <= 10) return; - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { // Become the parent node - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10); - me.parent.maybeSpill(); - }, - iter: function(from, to, op) { this.iterN(from, to - from, op); }, - iterN: function(at, n, op) { - for (var i = 0, e = this.children.length; i < e; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) return true; - if ((n -= used) == 0) break; - at = 0; - } else at -= sz; - } - } - }; - - function getLineAt(chunk, n) { - while (!chunk.lines) { - for (var i = 0;; ++i) { - var child = chunk.children[i], sz = child.chunkSize(); - if (n < sz) { chunk = child; break; } - n -= sz; - } - } - return chunk.lines[n]; - } - function lineNo(line) { - if (line.parent == null) return null; - var cur = line.parent, no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i = 0, e = chunk.children.length; ; ++i) { - if (chunk.children[i] == cur) break; - no += chunk.children[i].chunkSize(); - } - } - return no; - } - function lineAtHeight(chunk, h) { - var n = 0; - outer: do { - for (var i = 0, e = chunk.children.length; i < e; ++i) { - var child = chunk.children[i], ch = child.height; - if (h < ch) { chunk = child; continue outer; } - h -= ch; - n += child.chunkSize(); - } - return n; - } while (!chunk.lines); - for (var i = 0, e = chunk.lines.length; i < e; ++i) { - var line = chunk.lines[i], lh = line.height; - if (h < lh) break; - h -= lh; - } - return n + i; - } - function heightAtLine(chunk, n) { - var h = 0; - outer: do { - for (var i = 0, e = chunk.children.length; i < e; ++i) { - var child = chunk.children[i], sz = child.chunkSize(); - if (n < sz) { chunk = child; continue outer; } - n -= sz; - h += child.height; - } - return h; - } while (!chunk.lines); - for (var i = 0; i < n; ++i) h += chunk.lines[i].height; - return h; - } - - // The history object 'chunks' changes that are made close together - // and at almost the same time into bigger undoable units. - function History() { - this.time = 0; - this.done = []; this.undone = []; - this.compound = 0; - this.closed = false; - } - History.prototype = { - addChange: function(start, added, old) { - this.undone.length = 0; - var time = +new Date, cur = this.done[this.done.length - 1], last = cur && cur[cur.length - 1]; - var dtime = time - this.time; - - if (this.compound && cur && !this.closed) { - cur.push({start: start, added: added, old: old}); - } else if (dtime > 400 || !last || this.closed || - last.start > start + old.length || last.start + last.added < start) { - this.done.push([{start: start, added: added, old: old}]); - this.closed = false; - } else { - var startBefore = Math.max(0, last.start - start), - endAfter = Math.max(0, (start + old.length) - (last.start + last.added)); - for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]); - for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]); - if (startBefore) last.start = start; - last.added += added - (old.length - startBefore - endAfter); - } - this.time = time; - }, - startCompound: function() { - if (!this.compound++) this.closed = true; - }, - endCompound: function() { - if (!--this.compound) this.closed = true; - } - }; - - function stopMethod() {e_stop(this);} - // Ensure an event has a stop method. - function addStop(event) { - if (!event.stop) event.stop = stopMethod; - return event; - } - - function e_preventDefault(e) { - if (e.preventDefault) e.preventDefault(); - else e.returnValue = false; - } - function e_stopPropagation(e) { - if (e.stopPropagation) e.stopPropagation(); - else e.cancelBubble = true; - } - function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} - CodeMirror.e_stop = e_stop; - CodeMirror.e_preventDefault = e_preventDefault; - CodeMirror.e_stopPropagation = e_stopPropagation; - - function e_target(e) {return e.target || e.srcElement;} - function e_button(e) { - if (e.which) return e.which; - else if (e.button & 1) return 1; - else if (e.button & 2) return 3; - else if (e.button & 4) return 2; - } - - // Allow 3rd-party code to override event properties by adding an override - // object to an event object. - function e_prop(e, prop) { - var overridden = e.override && e.override.hasOwnProperty(prop); - return overridden ? e.override[prop] : e[prop]; - } - - // Event handler registration. If disconnect is true, it'll return a - // function that unregisters the handler. - function connect(node, type, handler, disconnect) { - if (typeof node.addEventListener == "function") { - node.addEventListener(type, handler, false); - if (disconnect) return function() {node.removeEventListener(type, handler, false);}; - } - else { - var wrapHandler = function(event) {handler(event || window.event);}; - node.attachEvent("on" + type, wrapHandler); - if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);}; - } - } - CodeMirror.connect = connect; - - function Delayed() {this.id = null;} - Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; - - var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; - - var gecko = /gecko\/\d{7}/i.test(navigator.userAgent); - var ie = /MSIE \d/.test(navigator.userAgent); - var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); - var quirksMode = ie && document.documentMode == 5; - var webkit = /WebKit\//.test(navigator.userAgent); - var chrome = /Chrome\//.test(navigator.userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var khtml = /KHTML\//.test(navigator.userAgent); - - // Detect drag-and-drop - var dragAndDrop = function() { - // There is *some* kind of drag-and-drop support in IE6-8, but I - // couldn't get it to work yet. - if (ie_lt9) return false; - var div = document.createElement('div'); - return "draggable" in div || "dragDrop" in div; - }(); - - // Feature-detect whether newlines in textareas are converted to \r\n - var lineSep = function () { - var te = document.createElement("textarea"); - te.value = "foo\nbar"; - if (te.value.indexOf("\r") > -1) return "\r\n"; - return "\n"; - }(); - - // For a reason I have yet to figure out, some browsers disallow - // word wrapping between certain characters *only* if a new inline - // element is started between them. This makes it hard to reliably - // measure the position of things, since that requires inserting an - // extra span. This terribly fragile set of regexps matches the - // character combinations that suffer from this phenomenon on the - // various browsers. - var spanAffectsWrapping = /^$/; // Won't match any two-character string - if (gecko) spanAffectsWrapping = /$'/; - else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/; - else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/; - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - function countColumn(string, end, tabSize) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) end = string.length; - } - for (var i = 0, n = 0; i < end; ++i) { - if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); - else ++n; - } - return n; - } - - function computedStyle(elt) { - if (elt.currentStyle) return elt.currentStyle; - return window.getComputedStyle(elt, null); - } - - // Find the position of an element by following the offsetParent chain. - // If screen==true, it returns screen (rather than page) coordinates. - function eltOffset(node, screen) { - var bod = node.ownerDocument.body; - var x = 0, y = 0, skipBody = false; - for (var n = node; n; n = n.offsetParent) { - var ol = n.offsetLeft, ot = n.offsetTop; - // Firefox reports weird inverted offsets when the body has a border. - if (n == bod) { x += Math.abs(ol); y += Math.abs(ot); } - else { x += ol, y += ot; } - if (screen && computedStyle(n).position == "fixed") - skipBody = true; - } - var e = screen && !skipBody ? null : bod; - for (var n = node.parentNode; n != e; n = n.parentNode) - if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;} - return {left: x, top: y}; - } - // Use the faster and saner getBoundingClientRect method when possible. - if (document.documentElement.getBoundingClientRect != null) eltOffset = function(node, screen) { - // Take the parts of bounding client rect that we are interested in so we are able to edit if need be, - // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page) - try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; } - catch(e) { box = {top: 0, left: 0}; } - if (!screen) { - // Get the toplevel scroll, working around browser differences. - if (window.pageYOffset == null) { - var t = document.documentElement || document.body.parentNode; - if (t.scrollTop == null) t = document.body; - box.top += t.scrollTop; box.left += t.scrollLeft; - } else { - box.top += window.pageYOffset; box.left += window.pageXOffset; - } - } - return box; - }; - - // Get a node's text content. - function eltText(node) { - return node.textContent || node.innerText || node.nodeValue || ""; - } - function selectInput(node) { - if (ios) { // Mobile Safari apparently has a bug where select() is broken. - node.selectionStart = 0; - node.selectionEnd = node.value.length; - } else node.select(); - } - - // Operations on {line, ch} objects. - function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} - function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} - function copyPos(x) {return {line: x.line, ch: x.ch};} - - var escapeElement = document.createElement("pre"); - function htmlEscape(str) { - escapeElement.textContent = str; - return escapeElement.innerHTML; - } - // Recent (late 2011) Opera betas insert bogus newlines at the start - // of the textContent, so we strip those. - if (htmlEscape("a") == "\na") - htmlEscape = function(str) { - escapeElement.textContent = str; - return escapeElement.innerHTML.slice(1); - }; - // Some IEs don't preserve tabs through innerHTML - else if (htmlEscape("\t") != "\t") - htmlEscape = function(str) { - escapeElement.innerHTML = ""; - escapeElement.appendChild(document.createTextNode(str)); - return escapeElement.innerHTML; - }; - CodeMirror.htmlEscape = htmlEscape; - - // Used to position the cursor after an undo/redo by finding the - // last edited character. - function editEnd(from, to) { - if (!to) return 0; - if (!from) return to.length; - for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j) - if (from.charAt(i) != to.charAt(j)) break; - return j + 1; - } - - function indexOf(collection, elt) { - if (collection.indexOf) return collection.indexOf(elt); - for (var i = 0, e = collection.length; i < e; ++i) - if (collection[i] == elt) return i; - return -1; - } - function isWordChar(ch) { - return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase(); - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { - var pos = 0, nl, result = []; - while ((nl = string.indexOf("\n", pos)) > -1) { - result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl)); - pos = nl + 1; - } - result.push(string.slice(pos)); - return result; - } : function(string){return string.split(/\r?\n/);}; - CodeMirror.splitLines = splitLines; - - var hasSelection = window.getSelection ? function(te) { - try { return te.selectionStart != te.selectionEnd; } - catch(e) { return false; } - } : function(te) { - try {var range = te.ownerDocument.selection.createRange();} - catch(e) {} - if (!range || range.parentElement() != te) return false; - return range.compareEndPoints("StartToEnd", range) != 0; - }; - - CodeMirror.defineMode("null", function() { - return {token: function(stream) {stream.skipToEnd();}}; - }); - CodeMirror.defineMIME("text/plain", "null"); - - var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", - 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", - 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", - 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 127: "Delete", 186: ";", 187: "=", 188: ",", - 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp", - 63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right", - 63233: "Down", 63302: "Insert", 63272: "Delete"}; - CodeMirror.keyNames = keyNames; - (function() { - // Number keys - for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); - // Alphabetic keys - for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); - // Function keys - for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; - })(); - - return CodeMirror; -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/closetag.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/closetag.js deleted file mode 100644 index 819d259..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/closetag.js +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Tag-closer extension for CodeMirror. - * - * This extension adds a "closeTag" utility function that can be used with key bindings to - * insert a matching end tag after the ">" character of a start tag has been typed. It can - * also complete " - * Contributed under the same license terms as CodeMirror. - */ -(function() { - /** Option that allows tag closing behavior to be toggled. Default is true. */ - CodeMirror.defaults['closeTagEnabled'] = true; - - /** Array of tag names to add indentation after the start tag for. Default is the list of block-level html tags. */ - CodeMirror.defaults['closeTagIndent'] = ['applet', 'blockquote', 'body', 'button', 'div', 'dl', 'fieldset', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'html', 'iframe', 'layer', 'legend', 'object', 'ol', 'p', 'select', 'table', 'ul']; - - /** - * Call during key processing to close tags. Handles the key event if the tag is closed, otherwise throws CodeMirror.Pass. - * - cm: The editor instance. - * - ch: The character being processed. - * - indent: Optional. Omit or pass true to use the default indentation tag list defined in the 'closeTagIndent' option. - * Pass false to disable indentation. Pass an array to override the default list of tag names. - */ - CodeMirror.defineExtension("closeTag", function(cm, ch, indent) { - if (!cm.getOption('closeTagEnabled')) { - throw CodeMirror.Pass; - } - - var mode = cm.getOption('mode'); - - if (mode == 'text/html') { - - /* - * Relevant structure of token: - * - * htmlmixed - * className - * state - * htmlState - * type - * context - * tagName - * mode - * - * xml - * className - * state - * tagName - * type - */ - - var pos = cm.getCursor(); - var tok = cm.getTokenAt(pos); - var state = tok.state; - - if (state.mode && state.mode != 'html') { - throw CodeMirror.Pass; // With htmlmixed, we only care about the html sub-mode. - } - - if (ch == '>') { - var type = state.htmlState ? state.htmlState.type : state.type; // htmlmixed : xml - - if (tok.className == 'tag' && type == 'closeTag') { - throw CodeMirror.Pass; // Don't process the '>' at the end of an end-tag. - } - - cm.replaceSelection('>'); // Mode state won't update until we finish the tag. - pos = {line: pos.line, ch: pos.ch + 1}; - cm.setCursor(pos); - - tok = cm.getTokenAt(cm.getCursor()); - state = tok.state; - type = state.htmlState ? state.htmlState.type : state.type; // htmlmixed : xml - - if (tok.className == 'tag' && type != 'selfcloseTag') { - var tagName = state.htmlState ? state.htmlState.context.tagName : state.tagName; // htmlmixed : xml - if (tagName.length > 0) { - insertEndTag(cm, indent, pos, tagName); - } - return; - } - - // Undo the '>' insert and allow cm to handle the key instead. - cm.setSelection({line: pos.line, ch: pos.ch - 1}, pos); - cm.replaceSelection(""); - - } else if (ch == '/') { - if (tok.className == 'tag' && tok.string == '<') { - var tagName = state.htmlState ? (state.htmlState.context ? state.htmlState.context.tagName : '') : state.context.tagName; // htmlmixed : xml # extra htmlmized check is for ' 0) { - completeEndTag(cm, pos, tagName); - return; - } - } - } - - } - - throw CodeMirror.Pass; // Bubble if not handled - }); - - function insertEndTag(cm, indent, pos, tagName) { - if (shouldIndent(cm, indent, tagName)) { - cm.replaceSelection('\n\n', 'end'); - cm.indentLine(pos.line + 1); - cm.indentLine(pos.line + 2); - cm.setCursor({line: pos.line + 1, ch: cm.getLine(pos.line + 1).length}); - } else { - cm.replaceSelection(''); - cm.setCursor(pos); - } - } - - function shouldIndent(cm, indent, tagName) { - if (typeof indent == 'undefined' || indent == null || indent == true) { - indent = cm.getOption('closeTagIndent'); - } - if (!indent) { - indent = []; - } - return indexOf(indent, tagName.toLowerCase()) != -1; - } - - // C&P from codemirror.js...would be nice if this were visible to utilities. - function indexOf(collection, elt) { - if (collection.indexOf) return collection.indexOf(elt); - for (var i = 0, e = collection.length; i < e; ++i) - if (collection[i] == elt) return i; - return -1; - } - - function completeEndTag(cm, pos, tagName) { - cm.replaceSelection('/' + tagName + '>'); - cm.setCursor({line: pos.line, ch: pos.ch + tagName.length + 2 }); - } - -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/dialog.css b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/dialog.css deleted file mode 100644 index 4cb467e..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/dialog.css +++ /dev/null @@ -1,23 +0,0 @@ -.CodeMirror-dialog { - position: relative; -} - -.CodeMirror-dialog > div { - position: absolute; - top: 0; left: 0; right: 0; - background: white; - border-bottom: 1px solid #eee; - z-index: 15; - padding: .1em .8em; - overflow: hidden; - color: #333; -} - -.CodeMirror-dialog input { - border: none; - outline: none; - background: transparent; - width: 20em; - color: inherit; - font-family: monospace; -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/dialog.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/dialog.js deleted file mode 100644 index 95ba263..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/dialog.js +++ /dev/null @@ -1,63 +0,0 @@ -// Open simple dialogs on top of an editor. Relies on dialog.css. - -(function() { - function dialogDiv(cm, template) { - var wrap = cm.getWrapperElement(); - var dialog = wrap.insertBefore(document.createElement("div"), wrap.firstChild); - dialog.className = "CodeMirror-dialog"; - dialog.innerHTML = '
' + template + '
'; - return dialog; - } - - CodeMirror.defineExtension("openDialog", function(template, callback) { - var dialog = dialogDiv(this, template); - var closed = false, me = this; - function close() { - if (closed) return; - closed = true; - dialog.parentNode.removeChild(dialog); - } - var inp = dialog.getElementsByTagName("input")[0]; - if (inp) { - CodeMirror.connect(inp, "keydown", function(e) { - if (e.keyCode == 13 || e.keyCode == 27) { - CodeMirror.e_stop(e); - close(); - me.focus(); - if (e.keyCode == 13) callback(inp.value); - } - }); - inp.focus(); - CodeMirror.connect(inp, "blur", close); - } - return close; - }); - - CodeMirror.defineExtension("openConfirm", function(template, callbacks) { - var dialog = dialogDiv(this, template); - var buttons = dialog.getElementsByTagName("button"); - var closed = false, me = this, blurring = 1; - function close() { - if (closed) return; - closed = true; - dialog.parentNode.removeChild(dialog); - me.focus(); - } - buttons[0].focus(); - for (var i = 0; i < buttons.length; ++i) { - var b = buttons[i]; - (function(callback) { - CodeMirror.connect(b, "click", function(e) { - CodeMirror.e_preventDefault(e); - close(); - if (callback) callback(me); - }); - })(callbacks[i]); - CodeMirror.connect(b, "blur", function() { - --blurring; - setTimeout(function() { if (blurring <= 0) close(); }, 200); - }); - CodeMirror.connect(b, "focus", function() { ++blurring; }); - } - }); -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/foldcode.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/foldcode.js deleted file mode 100644 index 56e6144..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/foldcode.js +++ /dev/null @@ -1,191 +0,0 @@ -// the tagRangeFinder function is -// Copyright (C) 2011 by Daniel Glazman -// released under the MIT license (../../LICENSE) like the rest of CodeMirror -CodeMirror.tagRangeFinder = function(cm, line, hideEnd) { - var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; - var nameChar = nameStartChar + "\-\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; - var xmlNAMERegExp = new RegExp("^[" + nameStartChar + "][" + nameChar + "]*"); - - var lineText = cm.getLine(line); - var found = false; - var tag = null; - var pos = 0; - while (!found) { - pos = lineText.indexOf("<", pos); - if (-1 == pos) // no tag on line - return; - if (pos + 1 < lineText.length && lineText[pos + 1] == "/") { // closing tag - pos++; - continue; - } - // ok we weem to have a start tag - if (!lineText.substr(pos + 1).match(xmlNAMERegExp)) { // not a tag name... - pos++; - continue; - } - var gtPos = lineText.indexOf(">", pos + 1); - if (-1 == gtPos) { // end of start tag not in line - var l = line + 1; - var foundGt = false; - var lastLine = cm.lineCount(); - while (l < lastLine && !foundGt) { - var lt = cm.getLine(l); - var gt = lt.indexOf(">"); - if (-1 != gt) { // found a > - foundGt = true; - var slash = lt.lastIndexOf("/", gt); - if (-1 != slash && slash < gt) { - var str = lineText.substr(slash, gt - slash + 1); - if (!str.match( /\/\s*\>/ )) { // yep, that's the end of empty tag - if (hideEnd === true) l++; - return l; - } - } - } - l++; - } - found = true; - } - else { - var slashPos = lineText.lastIndexOf("/", gtPos); - if (-1 == slashPos) { // cannot be empty tag - found = true; - // don't continue - } - else { // empty tag? - // check if really empty tag - var str = lineText.substr(slashPos, gtPos - slashPos + 1); - if (!str.match( /\/\s*\>/ )) { // finally not empty - found = true; - // don't continue - } - } - } - if (found) { - var subLine = lineText.substr(pos + 1); - tag = subLine.match(xmlNAMERegExp); - if (tag) { - // we have an element name, wooohooo ! - tag = tag[0]; - // do we have the close tag on same line ??? - if (-1 != lineText.indexOf("", pos)) // yep - { - found = false; - } - // we don't, so we have a candidate... - } - else - found = false; - } - if (!found) - pos++; - } - - if (found) { - var startTag = "(\\<\\/" + tag + "\\>)|(\\<" + tag + "\\>)|(\\<" + tag + "\\s)|(\\<" + tag + "$)"; - var startTagRegExp = new RegExp(startTag, "g"); - var endTag = ""; - var depth = 1; - var l = line + 1; - var lastLine = cm.lineCount(); - while (l < lastLine) { - lineText = cm.getLine(l); - var match = lineText.match(startTagRegExp); - if (match) { - for (var i = 0; i < match.length; i++) { - if (match[i] == endTag) - depth--; - else - depth++; - if (!depth) { - if (hideEnd === true) l++; - return l; - } - } - } - l++; - } - return; - } -}; - -CodeMirror.braceRangeFinder = function(cm, line, hideEnd) { - var lineText = cm.getLine(line); - var startChar = lineText.lastIndexOf("{"); - if (startChar < 0 || lineText.lastIndexOf("}") > startChar) return; - var tokenType = cm.getTokenAt({line: line, ch: startChar}).className; - var count = 1, lastLine = cm.lineCount(), end; - outer: for (var i = line + 1; i < lastLine; ++i) { - var text = cm.getLine(i), pos = 0; - for (;;) { - var nextOpen = text.indexOf("{", pos), nextClose = text.indexOf("}", pos); - if (nextOpen < 0) nextOpen = text.length; - if (nextClose < 0) nextClose = text.length; - pos = Math.min(nextOpen, nextClose); - if (pos == text.length) break; - if (cm.getTokenAt({line: i, ch: pos + 1}).className == tokenType) { - if (pos == nextOpen) ++count; - else if (!--count) { end = i; break outer; } - } - ++pos; - } - } - if (end == null || end == line + 1) return; - if (hideEnd === true) end++; - return end; -}; - -CodeMirror.indentRangeFinder = function(cm, line) { - var tabSize = cm.getOption("tabSize"); - var myIndent = cm.getLineHandle(line).indentation(tabSize), last; - for (var i = line + 1, end = cm.lineCount(); i < end; ++i) { - var handle = cm.getLineHandle(i); - if (!/^\s*$/.test(handle.text)) { - if (handle.indentation(tabSize) <= myIndent) break; - last = i; - } - } - if (!last) return null; - return last + 1; -}; - -CodeMirror.newFoldFunction = function(rangeFinder, markText, hideEnd) { - var folded = []; - if (markText == null) markText = '
%N%'; - - function isFolded(cm, n) { - for (var i = 0; i < folded.length; ++i) { - var start = cm.lineInfo(folded[i].start); - if (!start) folded.splice(i--, 1); - else if (start.line == n) return {pos: i, region: folded[i]}; - } - } - - function expand(cm, region) { - cm.clearMarker(region.start); - for (var i = 0; i < region.hidden.length; ++i) - cm.showLine(region.hidden[i]); - } - - return function(cm, line) { - cm.operation(function() { - var known = isFolded(cm, line); - if (known) { - folded.splice(known.pos, 1); - expand(cm, known.region); - } else { - var end = rangeFinder(cm, line, hideEnd); - if (end == null) return; - var hidden = []; - for (var i = line + 1; i < end; ++i) { - var handle = cm.hideLine(i); - if (handle) hidden.push(handle); - } - var first = cm.setMarker(line, markText); - var region = {start: first, hidden: hidden}; - cm.onDeleteLine(first, function() { expand(cm, region); }); - folded.push(region); - } - }); - }; -}; diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/formatting.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/formatting.js deleted file mode 100644 index e189119..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/formatting.js +++ /dev/null @@ -1,294 +0,0 @@ -// ============== Formatting extensions ============================ -// A common storage for all mode-specific formatting features -if (!CodeMirror.modeExtensions) CodeMirror.modeExtensions = {}; - -// Returns the extension of the editor's current mode -CodeMirror.defineExtension("getModeExt", function () { - var mname = CodeMirror.resolveMode(this.getOption("mode")).name; - var ext = CodeMirror.modeExtensions[mname]; - if (!ext) throw new Error("No extensions found for mode " + mname); - return ext; -}); - -// If the current mode is 'htmlmixed', returns the extension of a mode located at -// the specified position (can be htmlmixed, css or javascript). Otherwise, simply -// returns the extension of the editor's current mode. -CodeMirror.defineExtension("getModeExtAtPos", function (pos) { - var token = this.getTokenAt(pos); - if (token && token.state && token.state.mode) - return CodeMirror.modeExtensions[token.state.mode == "html" ? "htmlmixed" : token.state.mode]; - else - return this.getModeExt(); -}); - -// Comment/uncomment the specified range -CodeMirror.defineExtension("commentRange", function (isComment, from, to) { - var curMode = this.getModeExtAtPos(this.getCursor()); - if (isComment) { // Comment range - var commentedText = this.getRange(from, to); - this.replaceRange(curMode.commentStart + this.getRange(from, to) + curMode.commentEnd - , from, to); - if (from.line == to.line && from.ch == to.ch) { // An empty comment inserted - put cursor inside - this.setCursor(from.line, from.ch + curMode.commentStart.length); - } - } - else { // Uncomment range - var selText = this.getRange(from, to); - var startIndex = selText.indexOf(curMode.commentStart); - var endIndex = selText.lastIndexOf(curMode.commentEnd); - if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) { - // Take string till comment start - selText = selText.substr(0, startIndex) - // From comment start till comment end - + selText.substring(startIndex + curMode.commentStart.length, endIndex) - // From comment end till string end - + selText.substr(endIndex + curMode.commentEnd.length); - } - this.replaceRange(selText, from, to); - } -}); - -// Applies automatic mode-aware indentation to the specified range -CodeMirror.defineExtension("autoIndentRange", function (from, to) { - var cmInstance = this; - this.operation(function () { - for (var i = from.line; i <= to.line; i++) { - cmInstance.indentLine(i, "smart"); - } - }); -}); - -// Applies automatic formatting to the specified range -CodeMirror.defineExtension("autoFormatRange", function (from, to) { - var absStart = this.indexFromPos(from); - var absEnd = this.indexFromPos(to); - // Insert additional line breaks where necessary according to the - // mode's syntax - var res = this.getModeExt().autoFormatLineBreaks(this.getValue(), absStart, absEnd); - var cmInstance = this; - - // Replace and auto-indent the range - this.operation(function () { - cmInstance.replaceRange(res, from, to); - var startLine = cmInstance.posFromIndex(absStart).line; - var endLine = cmInstance.posFromIndex(absStart + res.length).line; - for (var i = startLine; i <= endLine; i++) { - cmInstance.indentLine(i, "smart"); - } - }); -}); - -// Define extensions for a few modes - -CodeMirror.modeExtensions["css"] = { - commentStart: "/*", - commentEnd: "*/", - wordWrapChars: [";", "\\{", "\\}"], - autoFormatLineBreaks: function (text) { - return text.replace(new RegExp("(;|\\{|\\})([^\r\n])", "g"), "$1\n$2"); - } -}; - -CodeMirror.modeExtensions["javascript"] = { - commentStart: "/*", - commentEnd: "*/", - wordWrapChars: [";", "\\{", "\\}"], - - getNonBreakableBlocks: function (text) { - var nonBreakableRegexes = [ - new RegExp("for\\s*?\\(([\\s\\S]*?)\\)"), - new RegExp("'([\\s\\S]*?)('|$)"), - new RegExp("\"([\\s\\S]*?)(\"|$)"), - new RegExp("//.*([\r\n]|$)") - ]; - var nonBreakableBlocks = new Array(); - for (var i = 0; i < nonBreakableRegexes.length; i++) { - var curPos = 0; - while (curPos < text.length) { - var m = text.substr(curPos).match(nonBreakableRegexes[i]); - if (m != null) { - nonBreakableBlocks.push({ - start: curPos + m.index, - end: curPos + m.index + m[0].length - }); - curPos += m.index + Math.max(1, m[0].length); - } - else { // No more matches - break; - } - } - } - nonBreakableBlocks.sort(function (a, b) { - return a.start - b.start; - }); - - return nonBreakableBlocks; - }, - - autoFormatLineBreaks: function (text) { - var curPos = 0; - var reLinesSplitter = new RegExp("(;|\\{|\\})([^\r\n])", "g"); - var nonBreakableBlocks = this.getNonBreakableBlocks(text); - if (nonBreakableBlocks != null) { - var res = ""; - for (var i = 0; i < nonBreakableBlocks.length; i++) { - if (nonBreakableBlocks[i].start > curPos) { // Break lines till the block - res += text.substring(curPos, nonBreakableBlocks[i].start).replace(reLinesSplitter, "$1\n$2"); - curPos = nonBreakableBlocks[i].start; - } - if (nonBreakableBlocks[i].start <= curPos - && nonBreakableBlocks[i].end >= curPos) { // Skip non-breakable block - res += text.substring(curPos, nonBreakableBlocks[i].end); - curPos = nonBreakableBlocks[i].end; - } - } - if (curPos < text.length - 1) { - res += text.substr(curPos).replace(reLinesSplitter, "$1\n$2"); - } - return res; - } - else { - return text.replace(reLinesSplitter, "$1\n$2"); - } - } -}; - -CodeMirror.modeExtensions["xml"] = { - commentStart: "", - wordWrapChars: [">"], - - autoFormatLineBreaks: function (text) { - var lines = text.split("\n"); - var reProcessedPortion = new RegExp("(^\\s*?<|^[^<]*?)(.+)(>\\s*?$|[^>]*?$)"); - var reOpenBrackets = new RegExp("<", "g"); - var reCloseBrackets = new RegExp("(>)([^\r\n])", "g"); - for (var i = 0; i < lines.length; i++) { - var mToProcess = lines[i].match(reProcessedPortion); - if (mToProcess != null && mToProcess.length > 3) { // The line starts with whitespaces and ends with whitespaces - lines[i] = mToProcess[1] - + mToProcess[2].replace(reOpenBrackets, "\n$&").replace(reCloseBrackets, "$1\n$2") - + mToProcess[3]; - continue; - } - } - - return lines.join("\n"); - } -}; - -CodeMirror.modeExtensions["htmlmixed"] = { - commentStart: "", - wordWrapChars: [">", ";", "\\{", "\\}"], - - getModeInfos: function (text, absPos) { - var modeInfos = new Array(); - modeInfos[0] = - { - pos: 0, - modeExt: CodeMirror.modeExtensions["xml"], - modeName: "xml" - }; - - var modeMatchers = new Array(); - modeMatchers[0] = - { - regex: new RegExp("]*>([\\s\\S]*?)(]*>|$)", "i"), - modeExt: CodeMirror.modeExtensions["css"], - modeName: "css" - }; - modeMatchers[1] = - { - regex: new RegExp("]*>([\\s\\S]*?)(]*>|$)", "i"), - modeExt: CodeMirror.modeExtensions["javascript"], - modeName: "javascript" - }; - - var lastCharPos = (typeof (absPos) !== "undefined" ? absPos : text.length - 1); - // Detect modes for the entire text - for (var i = 0; i < modeMatchers.length; i++) { - var curPos = 0; - while (curPos <= lastCharPos) { - var m = text.substr(curPos).match(modeMatchers[i].regex); - if (m != null) { - if (m.length > 1 && m[1].length > 0) { - // Push block begin pos - var blockBegin = curPos + m.index + m[0].indexOf(m[1]); - modeInfos.push( - { - pos: blockBegin, - modeExt: modeMatchers[i].modeExt, - modeName: modeMatchers[i].modeName - }); - // Push block end pos - modeInfos.push( - { - pos: blockBegin + m[1].length, - modeExt: modeInfos[0].modeExt, - modeName: modeInfos[0].modeName - }); - curPos += m.index + m[0].length; - continue; - } - else { - curPos += m.index + Math.max(m[0].length, 1); - } - } - else { // No more matches - break; - } - } - } - // Sort mode infos - modeInfos.sort(function sortModeInfo(a, b) { - return a.pos - b.pos; - }); - - return modeInfos; - }, - - autoFormatLineBreaks: function (text, startPos, endPos) { - var modeInfos = this.getModeInfos(text); - var reBlockStartsWithNewline = new RegExp("^\\s*?\n"); - var reBlockEndsWithNewline = new RegExp("\n\\s*?$"); - var res = ""; - // Use modes info to break lines correspondingly - if (modeInfos.length > 1) { // Deal with multi-mode text - for (var i = 1; i <= modeInfos.length; i++) { - var selStart = modeInfos[i - 1].pos; - var selEnd = (i < modeInfos.length ? modeInfos[i].pos : endPos); - - if (selStart >= endPos) { // The block starts later than the needed fragment - break; - } - if (selStart < startPos) { - if (selEnd <= startPos) { // The block starts earlier than the needed fragment - continue; - } - selStart = startPos; - } - if (selEnd > endPos) { - selEnd = endPos; - } - var textPortion = text.substring(selStart, selEnd); - if (modeInfos[i - 1].modeName != "xml") { // Starting a CSS or JavaScript block - if (!reBlockStartsWithNewline.test(textPortion) - && selStart > 0) { // The block does not start with a line break - textPortion = "\n" + textPortion; - } - if (!reBlockEndsWithNewline.test(textPortion) - && selEnd < text.length - 1) { // The block does not end with a line break - textPortion += "\n"; - } - } - res += modeInfos[i - 1].modeExt.autoFormatLineBreaks(textPortion); - } - } - else { // Single-mode text - res = modeInfos[0].modeExt.autoFormatLineBreaks(text.substring(startPos, endPos)); - } - - return res; - } -}; diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/javascript-hint.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/javascript-hint.js deleted file mode 100644 index 2117e5a..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/javascript-hint.js +++ /dev/null @@ -1,134 +0,0 @@ -(function () { - function forEach(arr, f) { - for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); - } - - function arrayContains(arr, item) { - if (!Array.prototype.indexOf) { - var i = arr.length; - while (i--) { - if (arr[i] === item) { - return true; - } - } - return false; - } - return arr.indexOf(item) != -1; - } - - function scriptHint(editor, keywords, getToken) { - // Find the token at the cursor - var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token; - // If it's not a 'word-style' token, ignore the token. - if (!/^[\w$_]*$/.test(token.string)) { - token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state, - className: token.string == "." ? "property" : null}; - } - // If it is a property, find out what it is a property of. - while (tprop.className == "property") { - tprop = getToken(editor, {line: cur.line, ch: tprop.start}); - if (tprop.string != ".") return; - tprop = getToken(editor, {line: cur.line, ch: tprop.start}); - if (tprop.string == ')') { - var level = 1; - do { - tprop = getToken(editor, {line: cur.line, ch: tprop.start}); - switch (tprop.string) { - case ')': level++; break; - case '(': level--; break; - default: break; - } - } while (level > 0) - tprop = getToken(editor, {line: cur.line, ch: tprop.start}); - if (tprop.className == 'variable') - tprop.className = 'function'; - else return; // no clue - } - if (!context) var context = []; - context.push(tprop); - } - return {list: getCompletions(token, context, keywords), - from: {line: cur.line, ch: token.start}, - to: {line: cur.line, ch: token.end}}; - } - - CodeMirror.javascriptHint = function(editor) { - return scriptHint(editor, javascriptKeywords, - function (e, cur) {return e.getTokenAt(cur);}); - } - - function getCoffeeScriptToken(editor, cur) { - // This getToken, it is for coffeescript, imitates the behavior of - // getTokenAt method in javascript.js, that is, returning "property" - // type and treat "." as indepenent token. - var token = editor.getTokenAt(cur); - if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') { - token.end = token.start; - token.string = '.'; - token.className = "property"; - } - else if (/^\.[\w$_]*$/.test(token.string)) { - token.className = "property"; - token.start++; - token.string = token.string.replace(/\./, ''); - } - return token; - } - - CodeMirror.coffeescriptHint = function(editor) { - return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken); - } - - var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " + - "toUpperCase toLowerCase split concat match replace search").split(" "); - var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " + - "lastIndexOf every some filter forEach map reduce reduceRight ").split(" "); - var funcProps = "prototype apply call bind".split(" "); - var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " + - "if in instanceof new null return switch throw true try typeof var void while with").split(" "); - var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " + - "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" "); - - function getCompletions(token, context, keywords) { - var found = [], start = token.string; - function maybeAdd(str) { - if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str); - } - function gatherCompletions(obj) { - if (typeof obj == "string") forEach(stringProps, maybeAdd); - else if (obj instanceof Array) forEach(arrayProps, maybeAdd); - else if (obj instanceof Function) forEach(funcProps, maybeAdd); - for (var name in obj) maybeAdd(name); - } - - if (context) { - // If this is a property, see if it belongs to some object we can - // find in the current environment. - var obj = context.pop(), base; - if (obj.className == "variable") - base = window[obj.string]; - else if (obj.className == "string") - base = ""; - else if (obj.className == "atom") - base = 1; - else if (obj.className == "function") { - if (window.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') && - (typeof window.jQuery == 'function')) - base = window.jQuery(); - else if (window._ != null && (obj.string == '_') && (typeof window._ == 'function')) - base = window._(); - } - while (base != null && context.length) - base = base[context.pop().string]; - if (base != null) gatherCompletions(base); - } - else { - // If not, just look in the window object and any local scope - // (reading into JS mode internals to get at the local variables) - for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); - gatherCompletions(window); - forEach(keywords, maybeAdd); - } - return found; - } -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/loadmode.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/loadmode.js deleted file mode 100644 index 48d5a7a..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/loadmode.js +++ /dev/null @@ -1,51 +0,0 @@ -(function() { - if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js"; - - var loading = {}; - function splitCallback(cont, n) { - var countDown = n; - return function() { if (--countDown == 0) cont(); } - } - function ensureDeps(mode, cont) { - var deps = CodeMirror.modes[mode].dependencies; - if (!deps) return cont(); - var missing = []; - for (var i = 0; i < deps.length; ++i) { - if (!CodeMirror.modes.hasOwnProperty(deps[i])) - missing.push(deps[i]); - } - if (!missing.length) return cont(); - var split = splitCallback(cont, missing.length); - for (var i = 0; i < missing.length; ++i) - CodeMirror.requireMode(missing[i], split); - } - - CodeMirror.requireMode = function(mode, cont) { - if (typeof mode != "string") mode = mode.name; - if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont); - if (loading.hasOwnProperty(mode)) return loading[mode].push(cont); - - var script = document.createElement("script"); - script.src = CodeMirror.modeURL.replace(/%N/g, mode); - var others = document.getElementsByTagName("script")[0]; - others.parentNode.insertBefore(script, others); - var list = loading[mode] = [cont]; - var count = 0, poll = setInterval(function() { - if (++count > 100) return clearInterval(poll); - if (CodeMirror.modes.hasOwnProperty(mode)) { - clearInterval(poll); - loading[mode] = null; - ensureDeps(mode, function() { - for (var i = 0; i < list.length; ++i) list[i](); - }); - } - }, 200); - }; - - CodeMirror.autoLoadMode = function(instance, mode) { - if (!CodeMirror.modes.hasOwnProperty(mode)) - CodeMirror.requireMode(mode, function() { - instance.setOption("mode", instance.getOption("mode")); - }); - }; -}()); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/match-highlighter.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/match-highlighter.js deleted file mode 100644 index 59098ff..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/match-highlighter.js +++ /dev/null @@ -1,44 +0,0 @@ -// Define match-highlighter commands. Depends on searchcursor.js -// Use by attaching the following function call to the onCursorActivity event: - //myCodeMirror.matchHighlight(minChars); -// And including a special span.CodeMirror-matchhighlight css class (also optionally a separate one for .CodeMirror-focused -- see demo matchhighlighter.html) - -(function() { - var DEFAULT_MIN_CHARS = 2; - - function MatchHighlightState() { - this.marked = []; - } - function getMatchHighlightState(cm) { - return cm._matchHighlightState || (cm._matchHighlightState = new MatchHighlightState()); - } - - function clearMarks(cm) { - var state = getMatchHighlightState(cm); - for (var i = 0; i < state.marked.length; ++i) - state.marked[i].clear(); - state.marked = []; - } - - function markDocument(cm, className, minChars) { - clearMarks(cm); - minChars = (typeof minChars !== 'undefined' ? minChars : DEFAULT_MIN_CHARS); - if (cm.somethingSelected() && cm.getSelection().replace(/^\s+|\s+$/g, "").length >= minChars) { - var state = getMatchHighlightState(cm); - var query = cm.getSelection(); - cm.operation(function() { - if (cm.lineCount() < 2000) { // This is too expensive on big documents. - for (var cursor = cm.getSearchCursor(query); cursor.findNext();) { - //Only apply matchhighlight to the matches other than the one actually selected - if (!(cursor.from().line === cm.getCursor(true).line && cursor.from().ch === cm.getCursor(true).ch)) - state.marked.push(cm.markText(cursor.from(), cursor.to(), className)); - } - } - }); - } - } - - CodeMirror.defineExtension("matchHighlight", function(className, minChars) { - markDocument(this, className, minChars); - }); -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/overlay.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/overlay.js deleted file mode 100644 index 6471a5e..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/overlay.js +++ /dev/null @@ -1,51 +0,0 @@ -// Utility function that allows modes to be combined. The mode given -// as the base argument takes care of most of the normal mode -// functionality, but a second (typically simple) mode is used, which -// can override the style of text. Both modes get to parse all of the -// text, but when both assign a non-null style to a piece of code, the -// overlay wins, unless the combine argument was true, in which case -// the styles are combined. - -CodeMirror.overlayParser = function(base, overlay, combine) { - return { - startState: function() { - return { - base: CodeMirror.startState(base), - overlay: CodeMirror.startState(overlay), - basePos: 0, baseCur: null, - overlayPos: 0, overlayCur: null - }; - }, - copyState: function(state) { - return { - base: CodeMirror.copyState(base, state.base), - overlay: CodeMirror.copyState(overlay, state.overlay), - basePos: state.basePos, baseCur: null, - overlayPos: state.overlayPos, overlayCur: null - }; - }, - - token: function(stream, state) { - if (stream.start == state.basePos) { - state.baseCur = base.token(stream, state.base); - state.basePos = stream.pos; - } - if (stream.start == state.overlayPos) { - stream.pos = stream.start; - state.overlayCur = overlay.token(stream, state.overlay); - state.overlayPos = stream.pos; - } - stream.pos = Math.min(state.basePos, state.overlayPos); - if (stream.eol()) state.basePos = state.overlayPos = 0; - - if (state.overlayCur == null) return state.baseCur; - if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur; - else return state.overlayCur; - }, - - indent: base.indent && function(state, textAfter) { - return base.indent(state.base, textAfter); - }, - electricChars: base.electricChars - }; -}; diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/runmode.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/runmode.js deleted file mode 100644 index fc58d85..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/runmode.js +++ /dev/null @@ -1,49 +0,0 @@ -CodeMirror.runMode = function(string, modespec, callback, options) { - var mode = CodeMirror.getMode(CodeMirror.defaults, modespec); - var isNode = callback.nodeType == 1; - var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize; - if (isNode) { - var node = callback, accum = [], col = 0; - callback = function(text, style) { - if (text == "\n") { - accum.push("
"); - col = 0; - return; - } - var escaped = ""; - // HTML-escape and replace tabs - for (var pos = 0;;) { - var idx = text.indexOf("\t", pos); - if (idx == -1) { - escaped += CodeMirror.htmlEscape(text.slice(pos)); - col += text.length - pos; - break; - } else { - col += idx - pos; - escaped += CodeMirror.htmlEscape(text.slice(pos, idx)); - var size = tabSize - col % tabSize; - col += size; - for (var i = 0; i < size; ++i) escaped += " "; - pos = idx + 1; - } - } - - if (style) - accum.push("" + escaped + ""); - else - accum.push(escaped); - } - } - var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode); - for (var i = 0, e = lines.length; i < e; ++i) { - if (i) callback("\n"); - var stream = new CodeMirror.StringStream(lines[i]); - while (!stream.eol()) { - var style = mode.token(stream, state); - callback(stream.current(), style, i, stream.start); - stream.start = stream.pos; - } - } - if (isNode) - node.innerHTML = accum.join(""); -}; diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/search.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/search.js deleted file mode 100644 index f194c63..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/search.js +++ /dev/null @@ -1,114 +0,0 @@ -// Define search commands. Depends on dialog.js or another -// implementation of the openDialog method. - -// Replace works a little oddly -- it will do the replace on the next -// Ctrl-G (or whatever is bound to findNext) press. You prevent a -// replace by making sure the match is no longer selected when hitting -// Ctrl-G. - -(function() { - function SearchState() { - this.posFrom = this.posTo = this.query = null; - this.marked = []; - } - function getSearchState(cm) { - return cm._searchState || (cm._searchState = new SearchState()); - } - function dialog(cm, text, shortText, f) { - if (cm.openDialog) cm.openDialog(text, f); - else f(prompt(shortText, "")); - } - function confirmDialog(cm, text, shortText, fs) { - if (cm.openConfirm) cm.openConfirm(text, fs); - else if (confirm(shortText)) fs[0](); - } - function parseQuery(query) { - var isRE = query.match(/^\/(.*)\/$/); - return isRE ? new RegExp(isRE[1]) : query; - } - var queryDialog = - 'Search: (Use /re/ syntax for regexp search)'; - function doSearch(cm, rev) { - var state = getSearchState(cm); - if (state.query) return findNext(cm, rev); - dialog(cm, queryDialog, "Search for:", function(query) { - cm.operation(function() { - if (!query || state.query) return; - state.query = parseQuery(query); - if (cm.lineCount() < 2000) { // This is too expensive on big documents. - for (var cursor = cm.getSearchCursor(query); cursor.findNext();) - state.marked.push(cm.markText(cursor.from(), cursor.to(), "CodeMirror-searching")); - } - state.posFrom = state.posTo = cm.getCursor(); - findNext(cm, rev); - }); - }); - } - function findNext(cm, rev) {cm.operation(function() { - var state = getSearchState(cm); - var cursor = cm.getSearchCursor(state.query, rev ? state.posFrom : state.posTo); - if (!cursor.find(rev)) { - cursor = cm.getSearchCursor(state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0}); - if (!cursor.find(rev)) return; - } - cm.setSelection(cursor.from(), cursor.to()); - state.posFrom = cursor.from(); state.posTo = cursor.to(); - })} - function clearSearch(cm) {cm.operation(function() { - var state = getSearchState(cm); - if (!state.query) return; - state.query = null; - for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear(); - state.marked.length = 0; - })} - - var replaceQueryDialog = - 'Replace: (Use /re/ syntax for regexp search)'; - var replacementQueryDialog = 'With: '; - var doReplaceConfirm = "Replace? "; - function replace(cm, all) { - dialog(cm, replaceQueryDialog, "Replace:", function(query) { - if (!query) return; - query = parseQuery(query); - dialog(cm, replacementQueryDialog, "Replace with:", function(text) { - if (all) { - cm.compoundChange(function() { cm.operation(function() { - for (var cursor = cm.getSearchCursor(query); cursor.findNext();) { - if (typeof query != "string") { - var match = cm.getRange(cursor.from(), cursor.to()).match(query); - cursor.replace(text.replace(/\$(\d)/, function(w, i) {return match[i];})); - } else cursor.replace(text); - } - })}); - } else { - clearSearch(cm); - var cursor = cm.getSearchCursor(query, cm.getCursor()); - function advance() { - var start = cursor.from(), match; - if (!(match = cursor.findNext())) { - cursor = cm.getSearchCursor(query); - if (!(match = cursor.findNext()) || - (cursor.from().line == start.line && cursor.from().ch == start.ch)) return; - } - cm.setSelection(cursor.from(), cursor.to()); - confirmDialog(cm, doReplaceConfirm, "Replace?", - [function() {doReplace(match);}, advance]); - } - function doReplace(match) { - cursor.replace(typeof query == "string" ? text : - text.replace(/\$(\d)/, function(w, i) {return match[i];})); - advance(); - } - advance(); - } - }); - }); - } - - CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);}; - CodeMirror.commands.findNext = doSearch; - CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);}; - CodeMirror.commands.clearSearch = clearSearch; - CodeMirror.commands.replace = replace; - CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);}; -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/searchcursor.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/searchcursor.js deleted file mode 100644 index ec3f73c..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/searchcursor.js +++ /dev/null @@ -1,117 +0,0 @@ -(function(){ - function SearchCursor(cm, query, pos, caseFold) { - this.atOccurrence = false; this.cm = cm; - if (caseFold == null && typeof query == "string") caseFold = false; - - pos = pos ? cm.clipPos(pos) : {line: 0, ch: 0}; - this.pos = {from: pos, to: pos}; - - // The matches method is filled in based on the type of query. - // It takes a position and a direction, and returns an object - // describing the next occurrence of the query, or null if no - // more matches were found. - if (typeof query != "string") // Regexp match - this.matches = function(reverse, pos) { - if (reverse) { - var line = cm.getLine(pos.line).slice(0, pos.ch), match = line.match(query), start = 0; - while (match) { - var ind = line.indexOf(match[0]); - start += ind; - line = line.slice(ind + 1); - var newmatch = line.match(query); - if (newmatch) match = newmatch; - else break; - start++; - } - } - else { - var line = cm.getLine(pos.line).slice(pos.ch), match = line.match(query), - start = match && pos.ch + line.indexOf(match[0]); - } - if (match) - return {from: {line: pos.line, ch: start}, - to: {line: pos.line, ch: start + match[0].length}, - match: match}; - }; - else { // String query - if (caseFold) query = query.toLowerCase(); - var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;}; - var target = query.split("\n"); - // Different methods for single-line and multi-line queries - if (target.length == 1) - this.matches = function(reverse, pos) { - var line = fold(cm.getLine(pos.line)), len = query.length, match; - if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1) - : (match = line.indexOf(query, pos.ch)) != -1) - return {from: {line: pos.line, ch: match}, - to: {line: pos.line, ch: match + len}}; - }; - else - this.matches = function(reverse, pos) { - var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(cm.getLine(ln)); - var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match)); - if (reverse ? offsetA >= pos.ch || offsetA != match.length - : offsetA <= pos.ch || offsetA != line.length - match.length) - return; - for (;;) { - if (reverse ? !ln : ln == cm.lineCount() - 1) return; - line = fold(cm.getLine(ln += reverse ? -1 : 1)); - match = target[reverse ? --idx : ++idx]; - if (idx > 0 && idx < target.length - 1) { - if (line != match) return; - else continue; - } - var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length); - if (reverse ? offsetB != line.length - match.length : offsetB != match.length) - return; - var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB}; - return {from: reverse ? end : start, to: reverse ? start : end}; - } - }; - } - } - - SearchCursor.prototype = { - findNext: function() {return this.find(false);}, - findPrevious: function() {return this.find(true);}, - - find: function(reverse) { - var self = this, pos = this.cm.clipPos(reverse ? this.pos.from : this.pos.to); - function savePosAndFail(line) { - var pos = {line: line, ch: 0}; - self.pos = {from: pos, to: pos}; - self.atOccurrence = false; - return false; - } - - for (;;) { - if (this.pos = this.matches(reverse, pos)) { - this.atOccurrence = true; - return this.pos.match || true; - } - if (reverse) { - if (!pos.line) return savePosAndFail(0); - pos = {line: pos.line-1, ch: this.cm.getLine(pos.line-1).length}; - } - else { - var maxLine = this.cm.lineCount(); - if (pos.line == maxLine - 1) return savePosAndFail(maxLine); - pos = {line: pos.line+1, ch: 0}; - } - } - }, - - from: function() {if (this.atOccurrence) return this.pos.from;}, - to: function() {if (this.atOccurrence) return this.pos.to;}, - - replace: function(newText) { - var self = this; - if (this.atOccurrence) - self.pos.to = this.cm.replaceRange(newText, self.pos.from, self.pos.to); - } - }; - - CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) { - return new SearchCursor(this, query, pos, caseFold); - }); -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/simple-hint.css b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/simple-hint.css deleted file mode 100644 index 4387cb9..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/simple-hint.css +++ /dev/null @@ -1,16 +0,0 @@ -.CodeMirror-completions { - position: absolute; - z-index: 10; - overflow: hidden; - -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); - -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); - box-shadow: 2px 3px 5px rgba(0,0,0,.2); -} -.CodeMirror-completions select { - background: #fafafa; - outline: none; - border: none; - padding: 0; - margin: 0; - font-family: monospace; -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/simple-hint.js b/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/simple-hint.js deleted file mode 100644 index 7decd58..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/mini-code-edit/cm/lib/util/simple-hint.js +++ /dev/null @@ -1,72 +0,0 @@ -(function() { - CodeMirror.simpleHint = function(editor, getHints) { - // We want a single cursor position. - if (editor.somethingSelected()) return; - var result = getHints(editor); - if (!result || !result.list.length) return; - var completions = result.list; - function insert(str) { - editor.replaceRange(str, result.from, result.to); - } - // When there is only one completion, use it directly. - if (completions.length == 1) {insert(completions[0]); return true;} - - // Build the select widget - var complete = document.createElement("div"); - complete.className = "CodeMirror-completions"; - var sel = complete.appendChild(document.createElement("select")); - // Opera doesn't move the selection when pressing up/down in a - // multi-select, but it does properly support the size property on - // single-selects, so no multi-select is necessary. - if (!window.opera) sel.multiple = true; - for (var i = 0; i < completions.length; ++i) { - var opt = sel.appendChild(document.createElement("option")); - opt.appendChild(document.createTextNode(completions[i])); - } - sel.firstChild.selected = true; - sel.size = Math.min(10, completions.length); - var pos = editor.cursorCoords(); - complete.style.left = pos.x + "px"; - complete.style.top = pos.yBot + "px"; - document.body.appendChild(complete); - // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. - var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); - if(winW - pos.x < sel.clientWidth) - complete.style.left = (pos.x - sel.clientWidth) + "px"; - // Hack to hide the scrollbar. - if (completions.length <= 10) - complete.style.width = (sel.clientWidth - 1) + "px"; - - var done = false; - function close() { - if (done) return; - done = true; - complete.parentNode.removeChild(complete); - } - function pick() { - insert(completions[sel.selectedIndex]); - close(); - setTimeout(function(){editor.focus();}, 50); - } - CodeMirror.connect(sel, "blur", close); - CodeMirror.connect(sel, "keydown", function(event) { - var code = event.keyCode; - // Enter - if (code == 13) {CodeMirror.e_stop(event); pick();} - // Escape - else if (code == 27) {CodeMirror.e_stop(event); close(); editor.focus();} - else if (code != 38 && code != 40) { - close(); editor.focus(); - // Pass the event to the CodeMirror instance so that it can handle things like backspace properly. - editor.triggerOnKeyDown(event); - setTimeout(function(){CodeMirror.simpleHint(editor, getHints);}, 50); - } - }); - CodeMirror.connect(sel, "dblclick", pick); - - sel.focus(); - // Opera sometimes ignores focusing a freshly created node - if (window.opera) setTimeout(function(){if (!done) sel.focus();}, 100); - return true; - }; -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/API.js b/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/API.js deleted file mode 100644 index bcb568b..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/API.js +++ /dev/null @@ -1,515 +0,0 @@ -/** - * API which opens the sockets and handles sending the data to - * and receiving the data from the AR Drone - * - * Additional thanks to Felix Geisendörfer (felixge) for the Node AR Drone lib - * which served as a helpful reference. - * - * @see https://github.com/felixge/node-ar-drone - */ -var DRONE = DRONE || {}; -DRONE.API = (function() { - - var SIMULATE = false; - - // Constants - var TO_DRONE = 0; - var TO_CLIENT = 1; - var DRONE_IP = "192.168.1.1"; - var CLIENT_IP = "192.168.1.2"; - var ONE_BUFFER = DRONE.Util.uint8ToArrayBuffer(1); - var BASE = (1 << 18) + (1 << 20) + (1 << 22) + (1 << 24) + (1 << 28); - var LAND = BASE + 0; - var TAKEOFF = BASE + (1 << 9); - var EMERGENCY = BASE + (1 << 8); - - // Vars - var noop = function() {}; - var keepAliveTimeout = 0; - var CONNECTIONS = 3; - var connectionsOutstanding = CONNECTIONS; - var looping = false; - var sockets = { - "nav": { - protocol: "udp", - port: 5554, - socket: null, - }, - "vid": { - protocol: "tcp", - port: 5555, - socket: null, - }, - "at": { - protocol: "udp", - port: 5556, - socket: null, - }, - "control": { - protocol: "tcp", - port: 5559, - socket: null, - } - }; - var status = { - verticalSpeed: 0, - angularSpeed: 0, - leftRightTilt: 0, - frontBackTilt: 0, - enabled: 0, - mode: LAND - }; - - callbacks = { - - /** - * Called whenever one of our sockets has connected - */ - onConnected: function(connectionResult) { - - // if we have 0 or higher we're good - if(connectionResult >= 0) { - - connectionsOutstanding--; - - // if we're all done with our connecting - if(connectionsOutstanding === 0 && callbacks.onAllConnected) { - - // start sending commands - sendKeepAliveCommand(); - sendFlatTrim(); - setConfigurations(); - - // now enable controls - status.enabled = 1; - - if(callbacks.onAllConnected) { - callbacks.onAllConnected(); - } - } - - } else { - // Flag that there was an issue - if(callbacks.onConnectionError) { - callbacks.onConnectionError(); - } - } - }, - - /** - * Called whenever one of our udp sockets receive messages - */ - onReceive: function(info) { - if (info.remotePort == 5554) { - if(info.data.byteLength > 0) { - DRONE.NavData.parse(info.data); - } else { - shutdown(); - } - } else if (info.remotePort == 5556) { - console.log("at socket receive data of size:" + info.data.byteLength); - } else if (info.remotePort == 5559) { - console.log("control socket receive data of size:" + info.data.byteLength); - } else { - console.log("unexpected data are received by port:" + info.remotePort); - } - }, - - onReceiveError: function(info) { - console.log("network in trouble socketId:" + info.socketId + " resultCode:" + info.resultCode); - shutdown(); - }, - - /* Placeholder callbacks */ - onAllConnected: null, - onConnectionError: null - }; - - // -- Bootstrap - - function bootstrapClientIp() { - // double check the Client IP (sometimes the Drone assignes 192.168.1.3) - chrome.socket.getNetworkList(function(entries) { - if (entries) { - for (var i = 0; i < entries.length; i++) { - if (entries[i] && entries[i].address - && entries[i].address.indexOf("192.168.1.") == 0) { - if (CLIENT_IP != entries[i].address) { - CLIENT_IP = entries[i].address; - log("Client IP changed to "+CLIENT_IP); - } - connectDrone(); - return; - } - } - } - callbacks.onConnectionError(); - }); - } - - /** - * Initialises client IP - */ - function init(cbConnected, cbConnectionError) { - if (sockets['at'].socket != null) { - return; - } - bootstrapClientIp(); - - // assign the callbacks - callbacks.onAllConnected = cbConnected; - callbacks.onConnectionError = cbConnectionError; - } - - /** - * Initialises the connections to the Drone - */ - function connectDrone() { - // send the drone AT commands - connect(sockets['at']); - - // get navigation data from the drone - connect(sockets['nav']); - - // get a video stream from the drone - // TODO: connect(sockets['vid'], 'tcp'); - - // send admin commands to the drone - connect(sockets['control']); - - chrome.sockets.tcp.onReceive.addListener(callbacks.onReceive); - chrome.sockets.tcp.onReceiveError.addListener(callbacks.onReceiveError); - chrome.sockets.udp.onReceive.addListener(callbacks.onReceive); - chrome.sockets.udp.onReceiveError.addListener(callbacks.onReceiveError); - log("connection completed."); - } - - - /** - * Closes and discards all the socket connections - */ - function shutdown() { - try { - connectionsOutstanding = CONNECTIONS; - if (keepAliveTimeout) clearTimeout(keepAliveTimeout); - status.mode = LAND; - status.enabled = 0; - disconnect(sockets['at']); - disconnect(sockets['nav']); - disconnect(sockets['control']); - } catch (err) { - sockets['at'].socket = null; - sockets['nav'].socket = null; - sockets['control'].socket = null; - } - log("disconnected. press X to reconnect"); - // TODO: disconnect(sockets['vid'].socket); - } - - /** - * Creates and connects a socket connection - * - * @see http://developer.chrome.com/apps/socket.html - */ - function connect(sockRef) { - - // grab the protocol, type, port and IP from - // the sockRef passed in and use that - // to create the socket - if (SIMULATE) { - callbacks.onConnected(1); - } else { - if (sockRef.protocol === "tcp") { - chrome.sockets.tcp.create({}, function(createInfo) { - sockRef.socket = createInfo.socketId; - chrome.sockets.tcp.connect(sockRef.socket, - DRONE_IP, - sockRef.port, - callbacks.onConnected); - }); - } else if (sockRef.protocol === "udp") { - chrome.sockets.udp.create({}, function(createInfo) { - sockRef.socket = createInfo.socketId; - chrome.sockets.udp.bind(sockRef.socket, - CLIENT_IP, sockRef.port, callbacks.onConnected); - }); - } - } - } - - /** - * Disconnects and destroys the socket connection - */ - function disconnect(sockRef) { - if (!SIMULATE) { - if (sockRef.protocol === "tcp") { - chrome.sockets.tcp.disconnect(sockRef.socket, function(result) { - chrome.sockets.tcp.close(sockRef.socket, noop); - sockRef.socket = null; - }); - } else if (sockRef.protocol === "udp") { - chrome.sockets.udp.close(sockRef.socket, noop); - sockRef.socket = null; - } - } - } - - // -- Stream functions - - /** - * Converts an array of commands to a string and then - * an ArrayBuffer to send over the socket to the drone - */ - function sendCommands(commands) { - var atSock = sockets['at']; - var commandBuffer = DRONE.Util.stringToArrayBuffer(commands.join("")); - - // output the commands - log(commands.join("")+" "+JSON.stringify(status)); - - // send all the commands - if (!SIMULATE) { - try { - chrome.sockets.udp.send( - atSock.socket, - commandBuffer, - DRONE_IP, - atSock.port, - function(sendInfo) { - if (sendInfo.resultCode < 0) { - shutdown(); - } - }); - } catch(err) { - shutdown(); - } - } - } - - /** - * Helper function that tells the drone what sensitivity - * we want. This is quite a high value (min = 0, max = 0.52) - */ - function setConfigurations() { - var outdoor = 'FALSE'; - sendCommands([ - // Set sensitivity; This is quite a high value (min = 0, max = 0.52) - new DRONE.Command('CONFIG', ['"control:euler_angle_max"', '"0.11"']), - new DRONE.Command('CONFIG', ['"control:indoor_euler_angle_max"', '"0.11"']), - new DRONE.Command('CONFIG', ['"control:outdoor_euler_angle_max"', '"0.11"']), - // Informs the drone that it is going to be flying outdoors - new DRONE.Command('CONFIG', ['"control:outdoor"', '"' + outdoor + '"']), - // Set navdata_demo to receive navdata - new DRONE.Command('CONFIG', ['"general:navdata_demo"', '"TRUE"']), - ]); - } - - /** - * Sends a keepalive command and attempts to read - * back the latest data from the drone - */ - function sendKeepAliveCommand() { - var navSock = sockets['nav']; - if (!SIMULATE) { - try { - chrome.sockets.udp.send( - navSock.socket, - (new Uint8Array([1])).buffer, - DRONE_IP, - navSock.port, - function(sendInfo) { - if (sendInfo.resultCode < 0) { - shutdown(); - } - }); - } catch(err) { - shutdown(); - } - - } - - // set up a keepalive because The drone does not receive any traffic for more than 2000ms; - // it will then stop all communication with the client - if (keepAliveTimeout) clearTimeout(keepAliveTimeout); - keepAliveTimeout = setTimeout(sendKeepAliveCommand, 1000); - } - - var takeoffLandStart = 0; - var previousTakeoffStatus = LAND; - - /** - * The takeoff loop. This should keep sending the REF command until the - * navdata shows that it has taken off, but since we don't yet interpret navdata, - * let's just keep it doing this for four seconds. - */ - function takeOffOrLandInternal() { - looping = false; - if (!takeoffLandStart || previousTakeoffStatus != status.mode) { - takeoffLandStart = Date.now(); - previousTakeoffStatus = status.mode; - } else { - // five seconds - if (takeoffLandStart + 5000 < Date.now()) { - takeoffLandStart = 0; - if (status.mode == TAKEOFF) { - looping = true; - loop(); - } - return; - } - } - - commands = [ - // Take off - new DRONE.Command('REF', [ - status.mode - ]) - - ]; - - // send and reschedule - sendCommands(commands); - setTimeout(takeOffOrLandInternal, 500); - } - - /** - * The main loop. This sends the commands to the drone, including - * the tilt, speed and whether or not we want it to take off or land - */ - function loop() { - if (looping == false) { - return; - } - - commands = [ - // Take off - new DRONE.Command('REF', [ - status.mode - ]), - - new DRONE.Command('PCMD', [ - // Enables/Disables commands - status.enabled, - // Left - Right tilt - DRONE.Util.float32ToInt32(status.leftRightTilt), - // Front - Back tilt - DRONE.Util.float32ToInt32(status.frontBackTilt), - // Vertical Speed - DRONE.Util.float32ToInt32(status.verticalSpeed), - // Angular Speed - DRONE.Util.float32ToInt32(status.angularSpeed) - - ]) - ]; - - // send and schedule the update - sendCommands(commands); - setTimeout(loop, 60); - } - - // -- Actions - - function takeOffOrLand() { - if (status.mode == TAKEOFF) { - status.mode = LAND; - } else if (status.mode == LAND) { - status.mode = TAKEOFF; - } - if (takeoffLandStart == 0) { - takeOffOrLandInternal(); - } - } - - function emergency() { - // don't want drone to fly immediately after going to normal mode. - status.mode = LAND; - sendCommands([new DRONE.Command('REF', [EMERGENCY])]); - } - - function raiseLower(val) { - val = check(val, 0); - status.verticalSpeed = val; - } - - function tiltLeftRight(val) { - val = check(val, 0); - status.leftRightTilt = val; - } - - function tiltFrontBack(val) { - val = check(val, 0); - status.frontBackTilt = val; - } - - function rotateLeftRight(val) { - val = check(val, 0); - status.angularSpeed = -val; - } - - function check(val, defaultVal) { - if(typeof val === "undefined") { - val = defaultVal; - } - return val; - } - - /** - * Helper function we use before letting the drone take off - * that we use to let it know that it's horizontal - */ - function sendFlatTrim() { - if (status.mode == LAND) { - sendCommands([new DRONE.Command('FTRIM')]); - } - } - - // from ARDrone_SDK_2_0/ControlEngine/iPhone/Release/ARDroneGeneratedTypes.h - var ANIMATIONS = [ - 'phiM30Deg', - 'phi30Deg', - 'thetaM30Deg', - 'theta30Deg', - 'theta20degYaw200deg', - 'theta20degYawM200deg', - 'turnaround', - 'turnaroundGodown', - 'yawShake', - 'yawDance', - 'phiDance', - 'thetaDance', - 'vzDance', - 'wave', - 'phiThetaMixed', - 'doublePhiThetaMixed', - 'flipAhead', - 'flipBehind', - 'flipLeft', - 'flipRight', - ]; - - function flipAnimation() { - if (status.mode == LAND) { - return; - } - looping = false; - sendCommands([new DRONE.Command('ANIM', [ANIMATIONS.indexOf('flipLeft'), 500])]); - setTimeout(function() { - looping = true; - loop(); - }, 1000); - } - - return { - init: init, - takeOffOrLand: takeOffOrLand, - emergency: emergency, - sendFlatTrim: sendFlatTrim, - raiseLower: raiseLower, - tiltLeftRight: tiltLeftRight, - tiltFrontBack: tiltFrontBack, - rotateLeftRight: rotateLeftRight, - shutdown: shutdown, - flipAnimation: flipAnimation, - }; - -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Command.js b/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Command.js deleted file mode 100644 index fd9a4e7..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Command.js +++ /dev/null @@ -1,15 +0,0 @@ -var DRONE = DRONE || {}; -DRONE.Command = function(command, parts) { - this.command = command; - this.parts = parts || []; -}; - -DRONE.Command.prototype.create = function(command, parts) { - return new DRONE.Command(command, parts); -}; - -DRONE.Command.prototype.toString = function() { - return "AT*" + this.command + "=" + - DRONE.Sequence.next() + (this.parts.length ? "," : "") + - this.parts.join(",") + "\r"; -}; diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Gamepad.js b/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Gamepad.js deleted file mode 100644 index 9cefa4f..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Gamepad.js +++ /dev/null @@ -1,89 +0,0 @@ -var DRONE = DRONE || {}; -DRONE.Gamepad = (function() { - var AXIS_THRESHOLD = 0.1; - var ANALOGUE_BUTTON_THRESHOLD = 0.5; - - function showNotSupported() { - // TODO Show a connection message - log("Press a button to connect the gamepad"); - } - - function updateGamepads() { - // Not implemented - } - - function updateButton(button, gamepadId, label) { - var value, pressed; - if (typeof(button) == 'object') { - value = button.value; - pressed = button.pressed; - } else { - value = button; - pressed = button > tester.ANALOGUE_BUTTON_THRESHOLD; - } - - if(pressed == true) { - switch(label) { - case 'button-left-shoulder-top': - DRONE.API.emergency(); - break; - case 'button-select': - DRONE.API.shutdown(); - break; - case 'button-1': - if(!!this.onConnected) { - this.onConnected(); - } - break; - case 'button-2': - DRONE.API.takeOffOrLand(); - break; - case 'button-3': - DRONE.API.sendFlatTrim(); - break; - case 'button-4': - DRONE.API.flipAnimation(); - break; - } - } - } - - function updateAxis(value, gamepadId, label, stick, xAxis) { - value = (Math.floor(value * 100) / 100); - - if(Math.abs(value) < AXIS_THRESHOLD) { - value = 0; - } - - switch(stick) { - case "stick-1": - // tilt - if(xAxis) { - DRONE.API.tiltLeftRight(value); - } else { - DRONE.API.tiltFrontBack(value); - } - break; - case "stick-2": - // rotate, raise, lower - value *= -1; - - if(xAxis) { - DRONE.API.rotateLeftRight(value); - } else { - DRONE.API.raiseLower(value); - } - break; - } - - } - - return { - onConnected: function() { console.log("Override DRONE.Gamepad.onConnected"); }, - showNotSupported: showNotSupported, - updateGamepads: updateGamepads, - updateButton: updateButton, - updateAxis: updateAxis - }; - -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/NavData.js b/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/NavData.js deleted file mode 100644 index 6aee7e9..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/NavData.js +++ /dev/null @@ -1,54 +0,0 @@ -var DRONE = DRONE || {}; -DRONE.NavData = (function() { - function parse(data) { - // See ARDroneLib/Soft/Common/navdata_common.h - var start = 16, checksum_block = 8; - var view = new DataView(data), - dataLen = data.byteLength; - - if(start + checksum_block >= dataLen) { - return; - } - - var header = view.getInt32(0, true); - var droneState = view.getInt32(4, true); - var sequence = view.getInt32(8, true); - var visonFlag = view.getInt32(12, true); - var options = null; - - var optionId = view.getInt16(start, true); - if (optionId == 0) { - options = { - optionId: optionId, - optionSize: view.getInt16(start + 2, true), - controlState: view.getUint32(start + 4, true), - batteryPercentage: view.getUint32(start + 8, true), - theta: view.getFloat32(start + 12, true), - phi: view.getFloat32(start + 16, true), - psi: view.getFloat32(start + 20, true), - altitude: view.getInt32(start + 24, true), - vx: view.getFloat32(start + 28, true), - vy: view.getFloat32(start + 32, true), - vz: view.getFloat32(start + 36, true) - }; - } - - // TODO: parse droneState and controlState - document.getElementById('droneState').innerHTML = droneState; - document.getElementById('visonFlag').innerHTML = visonFlag; - document.getElementById('controlState').innerHTML = options.controlState; - document.getElementById('batteryPercentage').innerHTML = options.batteryPercentage; - document.getElementById('theta').innerHTML = options.theta; - document.getElementById('phi').innerHTML = options.phi; - document.getElementById('psi').innerHTML = options.psi; - document.getElementById('altitude').innerHTML = options.altitude; - document.getElementById('vx').innerHTML = options.vx; - document.getElementById('vy').innerHTML = options.vy; - document.getElementById('vz').innerHTML = options.vz; - } - - return { - parse: parse - }; - -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Sequence.js b/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Sequence.js deleted file mode 100644 index 808353e..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Sequence.js +++ /dev/null @@ -1,19 +0,0 @@ -var DRONE = DRONE || {}; -DRONE.Sequence = (function() { - - var sequence = 0; - - function next() { - sequence++; - return sequence; - } - - function reset() { - sequence = 0; - } - - return { - next: next, - reset: reset - }; -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Util.js b/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Util.js deleted file mode 100644 index 0da7f68..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/parrot-ar-drone/lib/Util.js +++ /dev/null @@ -1,49 +0,0 @@ -var DRONE = DRONE || {}; -DRONE.Util = (function() { - - function stringToArrayBuffer(string) { - var buffer = new ArrayBuffer(string.length); - var view = new Uint8Array(buffer); - for(var i = 0; i < string.length; i++) { - view[i] = string.charCodeAt(i); - } - return buffer; - } - - function float32ToInt32(floatVal) { - var buffer = new ArrayBuffer(4); - var view = new DataView(buffer); - view.setFloat32(0, floatVal, true); - return view.getInt32(0, true); - } - - function uint8ToArrayBuffer(intVal) { - var view = new Uint8Array([intVal]); - return view.buffer; - } - - function uint8ArrayToString(uArrayVal) { - var str = ''; - for(var s = 0; s < uArrayVal.length; s++) { - str += String.fromCharCode(uArrayVal[s]); - } - return str; - } - - function uint8ArrayToHex(uArrayVal) { - var str = ''; - for(var s = 0; s < uArrayVal.length; s++) { - str += uArrayVal[s].toString(16) + ' '; - } - return str; - } - - return { - stringToArrayBuffer: stringToArrayBuffer, - float32ToInt32: float32ToInt32, - uint8ToArrayBuffer: uint8ToArrayBuffer, - uint8ArrayToString: uint8ArrayToString, - uint8ArrayToHex: uint8ArrayToHex - }; - -})(); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ace.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ace.js deleted file mode 100644 index 3b952c6..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ace.js +++ /dev/null @@ -1,86 +0,0 @@ -/* ***** 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): - * Kevin Dangoor (kdangoor@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(function(require, exports, module) { -"use strict"; - -require("./lib/fixoldbrowsers"); - -var Dom = require("./lib/dom"); -var Event = require("./lib/event"); - -var Editor = require("./editor").Editor; -var EditSession = require("./edit_session").EditSession; -var UndoManager = require("./undomanager").UndoManager; -var Renderer = require("./virtual_renderer").VirtualRenderer; -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"); -require("./config").init(); - -exports.edit = function(el) { - if (typeof(el) == "string") { - el = document.getElementById(el); - } - - 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; -}; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/anchor.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/anchor.js deleted file mode 100644 index 8b13e3b..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/anchor.js +++ /dev/null @@ -1,193 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; - -/** - * An Anchor is a floating pointer in the document. Whenever text is inserted or - * deleted before the cursor, the position of the cursor is updated - */ -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); - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/anchor_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/anchor_test.js deleted file mode 100644 index 62511c7..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/anchor_test.js +++ /dev/null @@ -1,184 +0,0 @@ -/* ***** 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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); -} - -define(function(require, exports, module) { -"use strict"; - -var Document = require("./document").Document; -var Anchor = require("./anchor").Anchor; -var Range = require("./range").Range; -var assert = require("./test/assertions"); - -module.exports = { - - "test create anchor" : function() { - var doc = new Document("juhu"); - var anchor = new Anchor(doc, 0, 0); - - assert.position(anchor.getPosition(), 0, 0); - assert.equal(anchor.getDocument(), doc); - }, - - "test insert text in same row before cursor should move anchor column": function() { - var doc = new Document("juhu\nkinners"); - var anchor = new Anchor(doc, 1, 4); - - doc.insert({row: 1, column: 1}, "123"); - assert.position(anchor.getPosition(), 1, 7); - }, - - "test insert lines before cursor should move anchor row": function() { - var doc = new Document("juhu\nkinners"); - var anchor = new Anchor(doc, 1, 4); - - doc.insertLines(1, ["123", "456"]); - assert.position(anchor.getPosition(), 3, 4); - }, - - "test insert new line before cursor should move anchor column": function() { - var doc = new Document("juhu\nkinners"); - var anchor = new Anchor(doc, 1, 4); - - doc.insertNewLine({row: 0, column: 0}); - assert.position(anchor.getPosition(), 2, 4); - }, - - "test insert new line in anchor line before anchor should move anchor column and row": function() { - var doc = new Document("juhu\nkinners"); - var anchor = new Anchor(doc, 1, 4); - - doc.insertNewLine({row: 1, column: 2}); - assert.position(anchor.getPosition(), 2, 2); - }, - - "test delete text in anchor line before anchor should move anchor column": function() { - var doc = new Document("juhu\nkinners"); - var anchor = new Anchor(doc, 1, 4); - - doc.remove(new Range(1, 1, 1, 3)); - assert.position(anchor.getPosition(), 1, 2); - }, - - "test remove range which contains the anchor should move the anchor to the start of the range": function() { - var doc = new Document("juhu\nkinners"); - var anchor = new Anchor(doc, 0, 3); - - doc.remove(new Range(0, 1, 1, 3)); - assert.position(anchor.getPosition(), 0, 1); - }, - - "test delete character before the anchor should have no effect": function() { - var doc = new Document("juhu\nkinners"); - var anchor = new Anchor(doc, 1, 4); - - doc.remove(new Range(1, 4, 1, 5)); - assert.position(anchor.getPosition(), 1, 4); - }, - - "test delete lines in anchor line before anchor should move anchor row": function() { - var doc = new Document("juhu\n1\n2\nkinners"); - var anchor = new Anchor(doc, 3, 4); - - doc.removeLines(1, 2); - assert.position(anchor.getPosition(), 1, 4); - }, - - "test remove new line before the cursor": function() { - var doc = new Document("juhu\nkinners"); - var anchor = new Anchor(doc, 1, 4); - - doc.removeNewLine(0); - assert.position(anchor.getPosition(), 0, 8); - }, - - "test delete range which contains the anchor should move anchor to the end of the range": function() { - var doc = new Document("juhu\nkinners"); - var anchor = new Anchor(doc, 1, 4); - - doc.remove(new Range(0, 2, 1, 2)); - assert.position(anchor.getPosition(), 0, 4); - }, - - "test delete line which contains the anchor should move anchor to the end of the range": function() { - var doc = new Document("juhu\nkinners\n123"); - var anchor = new Anchor(doc, 1, 5); - - doc.removeLines(1, 1); - assert.position(anchor.getPosition(), 1, 0); - }, - - "test remove after the anchor should have no effect": function() { - var doc = new Document("juhu\nkinners\n123"); - var anchor = new Anchor(doc, 1, 2); - - doc.remove(new Range(1, 4, 2, 2)); - assert.position(anchor.getPosition(), 1, 2); - }, - - "test anchor changes triggered by document changes should emit change event": function(next) { - var doc = new Document("juhu\nkinners\n123"); - var anchor = new Anchor(doc, 1, 5); - - anchor.on("change", function(e) { - assert.position(anchor.getPosition(), 0, 0); - next(); - }); - - doc.remove(new Range(0, 0, 2, 1)); - }, - - "test only fire change event if position changes": function() { - var doc = new Document("juhu\nkinners\n123"); - var anchor = new Anchor(doc, 1, 5); - - anchor.on("change", function(e) { - assert.fail(); - }); - - doc.remove(new Range(2, 0, 2, 1)); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec() -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/background_tokenizer.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/background_tokenizer.js deleted file mode 100644 index 0cfe794..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/background_tokenizer.js +++ /dev/null @@ -1,176 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; - -var BackgroundTokenizer = function(tokenizer, editor) { - this.running = false; - this.lines = []; - this.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.lines[self.currentLine] = self.$tokenizeRows(self.currentLine, self.currentLine)[0]; - self.currentLine++; - - // only check every 5 lines - processedLines += 1; - 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.start(0); - }; - - this.setDocument = function(doc) { - this.doc = doc; - this.lines = []; - - 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.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(firstRow, lastRow) { - return this.$tokenizeRows(firstRow, lastRow); - }; - - this.getState = function(row) { - return this.$tokenizeRows(row, row)[0].state; - }; - - this.$tokenizeRows = function(firstRow, lastRow) { - if (!this.doc || isNaN(firstRow) || isNaN(lastRow)) - return [{'state':'start','tokens':[]}]; - - var rows = []; - - // determine start state - var state = "start"; - var doCache = false; - if (firstRow > 0 && this.lines[firstRow - 1]) { - state = this.lines[firstRow - 1].state; - doCache = true; - } else if (firstRow == 0) { - state = "start"; - doCache = true; - } else if (this.lines.length > 0) { - // Guess that we haven't changed state. - state = this.lines[this.lines.length-1].state; - } - - var lines = this.doc.getLines(firstRow, lastRow); - for (var row=firstRow; row<=lastRow; row++) { - if (!this.lines[row]) { - var tokens = this.tokenizer.getLineTokens(lines[row-firstRow] || "", state); - var state = tokens.state; - rows.push(tokens); - - if (doCache) { - this.lines[row] = tokens; - } - } - else { - var tokens = this.lines[row]; - state = tokens.state; - rows.push(tokens); - } - } - return rows; - }; - -}).call(BackgroundTokenizer.prototype); - -exports.BackgroundTokenizer = BackgroundTokenizer; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/command_manager.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/command_manager.js deleted file mode 100644 index 380611e..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/command_manager.js +++ /dev/null @@ -1,98 +0,0 @@ -define(function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var HashHandler = require("../keyboard/hash_handler").HashHandler; -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var CommandManager = function(platform, commands) { - this.platform = platform; - this.commands = {}; - this.commmandKeyBinding = {}; - - this.addCommands(commands); - - this.setDefaultHandler("exec", function(e) { - 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; - - this._emit("exec", {editor: editor, command: command, args: args}); - return 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; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/command_manager_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/command_manager_test.js deleted file mode 100644 index 3ad11d5..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/command_manager_test.js +++ /dev/null @@ -1,193 +0,0 @@ -/* ***** 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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); -} - -define(function(require, exports, module) { -"use strict"; - -var CommandManager = require("./command_manager").CommandManager; -var keys = require("../lib/keys"); -var assert = require("../test/assertions"); - -module.exports = { - - setUp: function() { - this.command = { - name: "gotoline", - bindKey: { - mac: "Command-L", - win: "Ctrl-L" - }, - called: false, - exec: function(editor) { this.called = true; } - }; - - this.cm = new CommandManager("mac", [this.command]); - }, - - "test: register command": function() { - this.cm.exec("gotoline"); - assert.ok(this.command.called); - }, - - "test: mac hotkeys": function() { - var command = this.cm.findKeyCommand(keys.KEY_MODS.command, "L"); - assert.equal(command, this.command); - - var command = this.cm.findKeyCommand(keys.KEY_MODS.ctrl, "L"); - assert.equal(command, undefined); - }, - - "test: win hotkeys": function() { - var cm = new CommandManager("win", [this.command]); - - var command = cm.findKeyCommand(keys.KEY_MODS.command, "L"); - assert.equal(command, undefined); - - var command = cm.findKeyCommand(keys.KEY_MODS.ctrl, "L"); - assert.equal(command, this.command); - }, - - "test: remove command by object": function() { - this.cm.removeCommand(this.command); - - this.cm.exec("gotoline"); - assert.ok(!this.command.called); - - var command = this.cm.findKeyCommand(keys.KEY_MODS.command, "L"); - assert.equal(command, null); - }, - - "test: remove command by name": function() { - this.cm.removeCommand("gotoline"); - - this.cm.exec("gotoline"); - assert.ok(!this.command.called); - - var command = this.cm.findKeyCommand(keys.KEY_MODS.command, "L"); - assert.equal(command, null); - }, - - "test: adding a new command with the same name as an existing one should remove the old one first": function() { - var command = { - name: "gotoline", - bindKey: { - mac: "Command-L", - win: "Ctrl-L" - }, - called: false, - exec: function(editor) { this.called = true; } - }; - this.cm.addCommand(command); - - this.cm.exec("gotoline"); - assert.ok(command.called); - assert.ok(!this.command.called); - - assert.equal(this.cm.findKeyCommand(keys.KEY_MODS.command, "L"), command); - }, - - "test: adding commands and recording a macro": function() { - var called = ""; - this.cm.addCommands({ - togglerecording: function(editor) { - editor.cm.toggleRecording(); - }, - replay: function(editor) { - editor.cm.replay(); - }, - cm1: function(editor, arg) { - called += "1" + (arg || ""); - }, - cm2: function(editor) { - called += "2"; - } - }); - - this.cm.exec("togglerecording", this); - assert.ok(this.cm.recording); - - this.cm.exec("cm1", this, "-"); - this.cm.exec("cm2"); - this.cm.exec("replay", this); - assert.ok(!this.cm.recording); - assert.equal(called, "1-2"); - - called = ""; - this.cm.exec("replay", this); - assert.equal(called, "1-2"); - }, - - "test: bindkeys": function() { - var called = ""; - this.cm.addCommands({ - cm1: function(editor, arg) { - called += "1" + (arg || ""); - }, - cm2: function(editor) { - called += "2"; - } - }); - - this.cm.bindKeys({ - "Ctrl-L|Command-C": "cm1", - "Ctrl-R": "cm2" - }); - - var command = this.cm.findKeyCommand(keys.KEY_MODS.command, "C"); - assert.equal(command, "cm1"); - - var command = this.cm.findKeyCommand(keys.KEY_MODS.ctrl, "R"); - assert.equal(command, "cm2"); - - this.cm.bindKeys({ - "Ctrl-R": null - }); - - var command = this.cm.findKeyCommand(keys.KEY_MODS.ctrl, "R"); - assert.equal(command, null); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec(); -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/default_commands.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/default_commands.js deleted file mode 100644 index f109b33..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/default_commands.js +++ /dev/null @@ -1,440 +0,0 @@ -/* 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 - * Julian Viereck - * Mihai Sucan - * - * 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(function(require, exports, module) { -"use strict"; - -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-7", "Command-7"), - 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" -}]; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/multi_select_commands.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/multi_select_commands.js deleted file mode 100644 index 3662039..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/commands/multi_select_commands.js +++ /dev/null @@ -1,100 +0,0 @@ -/* 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): - * Harutyun Amirjanyan - * - * 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(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.multiEditCommands = [{ - name: "singleSelection", - bindKey: "esc", - exec: function(editor) { editor.exitMultiSelectMode(); }, - readonly: true -}]; - -var HashHandler = require("../keyboard/hash_handler").HashHandler; -exports.keyboardHandler = new HashHandler(exports.multiEditCommands); - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/config.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/config.js deleted file mode 100644 index 969fc7e..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/config.js +++ /dev/null @@ -1,128 +0,0 @@ -/* 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 - * - * 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(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 confik key: " + key); - - return options[key]; -}; - -exports.set = function(key, value) { - if (!options.hasOwnProperty(key)) - throw new Error("Unknown confik 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 suffix; - - var scripts = document.getElementsByTagName("script"); - for (var i=0; i .ace_gutter-cell { - padding-right: 13px; -} - -.ace_fold-widget { - box-sizing: border-box; - -moz-box-sizing: border-box; - -webkit-box-sizing: border-box; - - margin: 0 -12px 1px 1px; - display: inline-block; - height: 14px; - width: 11px; - vertical-align: text-bottom; - - 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"); - background-repeat: no-repeat; - background-position: center 5px; - - border-radius: 3px; -} - -.ace_fold-widget.end { - 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"); -} - -.ace_fold-widget.closed { - 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"); -} - -.ace_fold-widget:hover { - border: 1px solid rgba(0, 0, 0, 0.3); - background-color: rgba(255, 255, 255, 0.2); - -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7); - -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7); - -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7); - -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7); - box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7); - box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7); - background-position: center 4px; -} - -.ace_fold-widget:active { - border: 1px solid rgba(0, 0, 0, 0.4); - background-color: rgba(0, 0, 0, 0.05); - -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255); - -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8); - -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255); - -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8); - box-shadow:inset 0 1px 1px rgba(255, 255, 255); - box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8); -} - -.ace_fold-widget.invalid { - background-color: #FFB4B4; - border-color: #DE5555; -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/css/expand-marker.png b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/css/expand-marker.png deleted file mode 100644 index 535e819..0000000 Binary files a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/css/expand-marker.png and /dev/null differ diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/document.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/document.js deleted file mode 100644 index 237072a..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/document.js +++ /dev/null @@ -1,407 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -var oop = require("./lib/oop"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; -var Range = require("./range").Range; -var Anchor = require("./anchor").Anchor; - -var Document = function(text) { - this.$lines = []; - - if (Array.isArray(text)) { - this.insertLines(0, text); - } - // 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. - else if (text.length == 0) { - this.$lines = [""]; - } 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"); - }; - - /** - * Get a verbatim copy of the given line as it is in the document - */ - this.getLine = function(row) { - return this.$lines[row] || ""; - }; - - this.getLines = function(firstRow, lastRow) { - return this.$lines.slice(firstRow, lastRow + 1); - }; - - /** - * Returns all lines in the document as string array. Warning: The caller - * should not modify this array! - */ - 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 = []; - lines.push(this.$lines[range.start.row].substring(range.start.column)); - lines.push.apply(lines, this.getLines(range.start.row+1, range.end.row-1)); - 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}; - - 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 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; - }; - - /** - * Removes a range of full lines - * - * @param firstRow {Integer} The first row to be removed - * @param lastRow {Integer} The last row to be removed - * @return {String[]} The removed lines - */ - 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=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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/document_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/document_test.js deleted file mode 100644 index f140e3d..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/document_test.js +++ /dev/null @@ -1,314 +0,0 @@ -/* ***** 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 - * Julian Viereck - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); - require("./test/mockdom"); -} - -define(function(require, exports, module) { -"use strict"; - -var Document = require("./document").Document; -var Range = require("./range").Range; -var assert = require("./test/assertions"); - -module.exports = { - - "test: insert text in line" : function() { - var doc = new Document(["12", "34"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.insert({row: 0, column: 1}, "juhu"); - assert.equal(doc.getValue(), ["1juhu2", "34"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["12", "34"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["1juhu2", "34"].join("\n")); - }, - - "test: insert new line" : function() { - var doc = new Document(["12", "34"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.insertNewLine({row: 0, column: 1}); - assert.equal(doc.getValue(), ["1", "2", "34"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["12", "34"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["1", "2", "34"].join("\n")); - }, - - "test: insert lines at the beginning" : function() { - var doc = new Document(["12", "34"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.insertLines(0, ["aa", "bb"]); - assert.equal(doc.getValue(), ["aa", "bb", "12", "34"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["12", "34"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["aa", "bb", "12", "34"].join("\n")); - }, - - "test: insert lines at the end" : function() { - var doc = new Document(["12", "34"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.insertLines(2, ["aa", "bb"]); - assert.equal(doc.getValue(), ["12", "34", "aa", "bb"].join("\n")); - }, - - "test: insert lines in the middle" : function() { - var doc = new Document(["12", "34"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.insertLines(1, ["aa", "bb"]); - assert.equal(doc.getValue(), ["12", "aa", "bb", "34"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["12", "34"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["12", "aa", "bb", "34"].join("\n")); - }, - - "test: insert multi line string at the start" : function() { - var doc = new Document(["12", "34"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.insert({row: 0, column: 0}, "aa\nbb\ncc"); - assert.equal(doc.getValue(), ["aa", "bb", "cc12", "34"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["12", "34"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["aa", "bb", "cc12", "34"].join("\n")); - }, - - "test: insert multi line string at the end" : function() { - var doc = new Document(["12", "34"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.insert({row: 2, column: 0}, "aa\nbb\ncc"); - assert.equal(doc.getValue(), ["12", "34aa", "bb", "cc"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["12", "34"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["12", "34aa", "bb", "cc"].join("\n")); - }, - - "test: insert multi line string in the middle" : function() { - var doc = new Document(["12", "34"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.insert({row: 0, column: 1}, "aa\nbb\ncc"); - assert.equal(doc.getValue(), ["1aa", "bb", "cc2", "34"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["12", "34"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["1aa", "bb", "cc2", "34"].join("\n")); - }, - - "test: delete in line" : function() { - var doc = new Document(["1234", "5678"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.remove(new Range(0, 1, 0, 3)); - assert.equal(doc.getValue(), ["14", "5678"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["1234", "5678"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["14", "5678"].join("\n")); - }, - - "test: delete new line" : function() { - var doc = new Document(["1234", "5678"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.remove(new Range(0, 4, 1, 0)); - assert.equal(doc.getValue(), ["12345678"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["1234", "5678"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["12345678"].join("\n")); - }, - - "test: delete multi line range line" : function() { - var doc = new Document(["1234", "5678", "abcd"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.remove(new Range(0, 2, 2, 2)); - assert.equal(doc.getValue(), ["12cd"].join("\n")); - - var d = deltas.concat(); - doc.revertDeltas(d); - assert.equal(doc.getValue(), ["1234", "5678", "abcd"].join("\n")); - - doc.applyDeltas(d); - assert.equal(doc.getValue(), ["12cd"].join("\n")); - }, - - "test: delete full lines" : function() { - var doc = new Document(["1234", "5678", "abcd"]); - - var deltas = []; - doc.on("change", function(e) { deltas.push(e.data); }); - - doc.remove(new Range(1, 0, 3, 0)); - assert.equal(doc.getValue(), ["1234", ""].join("\n")); - }, - - "test: remove lines should return the removed lines" : function() { - var doc = new Document(["1234", "5678", "abcd"]); - - var removed = doc.removeLines(1, 2); - assert.equal(removed.join("\n"), ["5678", "abcd"].join("\n")); - }, - - "test: should handle unix style new lines" : function() { - var doc = new Document(["1", "2", "3"]); - assert.equal(doc.getValue(), ["1", "2", "3"].join("\n")); - }, - - "test: should handle windows style new lines" : function() { - var doc = new Document(["1", "2", "3"].join("\r\n")); - - doc.setNewLineMode("unix"); - assert.equal(doc.getValue(), ["1", "2", "3"].join("\n")); - }, - - "test: set new line mode to 'windows' should use '\\r\\n' as new lines": function() { - var doc = new Document(["1", "2", "3"].join("\n")); - doc.setNewLineMode("windows"); - assert.equal(doc.getValue(), ["1", "2", "3"].join("\r\n")); - }, - - "test: set new line mode to 'unix' should use '\\n' as new lines": function() { - var doc = new Document(["1", "2", "3"].join("\r\n")); - - doc.setNewLineMode("unix"); - assert.equal(doc.getValue(), ["1", "2", "3"].join("\n")); - }, - - "test: set new line mode to 'auto' should detect the incoming nl type": function() { - var doc = new Document(["1", "2", "3"].join("\n")); - - doc.setNewLineMode("auto"); - assert.equal(doc.getValue(), ["1", "2", "3"].join("\n")); - - var doc = new Document(["1", "2", "3"].join("\r\n")); - - doc.setNewLineMode("auto"); - assert.equal(doc.getValue(), ["1", "2", "3"].join("\r\n")); - - doc.replace(new Range(0, 0, 2, 1), ["4", "5", "6"].join("\n")); - assert.equal(["4", "5", "6"].join("\n"), doc.getValue()); - }, - - "test: set value": function() { - var doc = new Document("1"); - assert.equal("1", doc.getValue()); - - doc.setValue(doc.getValue()); - assert.equal("1", doc.getValue()); - - var doc = new Document("1\n2"); - assert.equal("1\n2", doc.getValue()); - - doc.setValue(doc.getValue()); - assert.equal("1\n2", doc.getValue()); - }, - - "test: empty document has to contain one line": function() { - var doc = new Document(""); - assert.equal(doc.$lines.length, 1); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec() -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session.js deleted file mode 100644 index 2bdfca4..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session.js +++ /dev/null @@ -1,1766 +0,0 @@ -/* 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 - * Mihai Sucan - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -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 EditSession = function(text, mode) { - this.$modified = true; - this.$breakpoints = []; - this.$frontMarkers = {}; - this.$backMarkers = {}; - this.$markerId = 1; - this.$rowCache = []; - this.$wrapData = []; - this.$foldData = []; - this.$undoSelect = true; - this.$foldData.toString = function() { - var str = ""; - this.forEach(function(foldLine) { - str += "\n" + foldLine.toString(); - }); - return str; - } - - if (text instanceof Document) { - this.setDocument(text); - } else { - this.setDocument(new Document(text)); - } - - this.selection = new Selection(this); - if (mode) - this.setMode(mode); - else - this.setMode(new TextMode()); -}; - - -(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(row) { - if (row == 0) { - this.$rowCache = []; - return; - } - var rowCache = this.$rowCache; - for (var i = 0; i < rowCache.length; i++) { - if (rowCache[i].docRow >= row) { - rowCache.splice(i, rowCache.length); - return; - } - } - }; - - 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.start(delta.range.start.row); - 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(); - }; - - 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(firstRow, lastRow) { - return this.bgTokenizer.getTokens(firstRow, lastRow); - }; - - this.getTokenAt = function(row, column) { - var tokens = this.bgTokenizer.getTokens(row, row)[0].tokens; - var token, c = 0; - if (column == null) { - i = tokens.length - 1; - c = this.getLine(row).length; - } else { - for (var i = 0; i < tokens.length; i++) { - c += tokens[i].value.length; - if (c >= column) - break; - } - } - token = tokens[i]; - if (!token) - return null; - token.index = i; - token.start = c - token.value.length; - return token; - }; - - this.setUndoManager = function(undoManager) { - this.$undoManager = undoManager; - this.$resetRowCache(0); - 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; - }, - - 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.$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 0) { - inToken = !!line.charAt(column - 1).match(this.tokenRe); - } - - if (!inToken) { - inToken = !!line.charAt(column).match(this.tokenRe); - } - - var re = inToken ? this.tokenRe : 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); - }; - - // Gets the range of a word including its right whitespace - 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[mode]) - return callback(this.$modes[mode]); - - var _self = this; - var module; - try { - module = require(mode); - } catch (e) {}; - if (module) - return done(module); - - fetch(function() { - require([mode], done); - }); - - function done(module) { - if (_self.$modes[mode]) - return callback(_self.$modes[mode]); - - _self.$modes[mode] = new module.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 + config.get("suffix"); - net.loadScript(filename, callback); - } - }; - - this.$mode = null; - this.$origMode = null; - this.setMode = function(mode) { - this.$origMode = mode; - - // load on demand - if (typeof mode === "string") { - var _self = this; - this._loadMode(mode, function(module) { - if (_self.$origMode !== mode) - return; - - _self.setMode(module); - }); - return; - } - - if (this.$mode === mode) return; - this.$mode = mode; - - - this.$stopWorker(); - - if (this.$useWorker) - this.$startWorker(); - - var tokenizer = mode.getTokenizer(); - - if(tokenizer.addEventListener !== undefined) { - var onReloadTokenizer = this.onReloadTokenizer.bind(this); - tokenizer.addEventListener("update", onReloadTokenizer); - } - - if (!this.bgTokenizer) { - this.bgTokenizer = new BackgroundTokenizer(tokenizer); - var _self = this; - this.bgTokenizer.addEventListener("update", function(e) { - _self._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.getWidth = function() { - this.$computeWidth(); - return this.width; - }; - - this.getScreenWidth = function() { - this.$computeWidth(); - return this.screenWidth; - }; - - this.$computeWidth = function(force) { - if (this.$modified || force) { - this.$modified = false; - - var lines = this.doc.getAllLines(); - var longestLine = 0; - var longestScreenLine = 0; - - for ( var i = 0; i < lines.length; i++) { - var foldLine = this.getFoldLine(i), - line, len; - - line = lines[i]; - if (foldLine) { - var end = foldLine.range.end; - line = this.getFoldDisplayLine(foldLine); - // Continue after the foldLine.end.row. All the lines in - // between are folded. - i = end.row; - } - len = line.length; - longestLine = Math.max(longestLine, len); - if (!this.$useWrapMode) { - longestScreenLine = Math.max( - longestScreenLine, - this.$getStringScreenWidth(line)[0] - ); - } - } - this.width = longestLine; - - if (this.$useWrapMode) { - this.screenWidth = this.$wrapLimit; - } else { - this.screenWidth = longestScreenLine; - } - } - }; - - /** - * Get a verbatim copy of the given line as it is in the document - */ - 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.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; - }, - - this.replace = function(range, text) { - return this.doc.replace(range, text); - }; - - /** - * Move a range of text from the given range to the given position. - * - * @param fromRange {Range} The range of text you want moved within the - * document. - * @param toPosition {Object} The location (row and column) where you want - * to move the text to. - * @return {Range} The new range where the text was moved to. - */ - 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. - 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 should generally only be called by the renderer when a resize - // is detected. - 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) { - useWrapMode && this.$wrapData.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); - } - - // 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!"); - } - - useWrapMode && this.$updateWrapData(firstRow, lastRow); - - return removedFolds; - }; - - 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; - } - - /** - * @param - * offset: The offset in screenColumn at which position str starts. - * Important for calculating the realTabSize. - */ - 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; - } - - /** - * Calculates the width of the a string on the screen while assuming that - * the string starts at the first column on the screen. - * - * @param string str String to calculate the screen width of - * @return array - * [0]: number of columns for str on screen. - * [1]: docColumn position that was read until (useful with screenColumn) - */ - this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { - if (maxScreenColumn == 0) { - return [0, 0]; - } - if (maxScreenColumn == null) { - maxScreenColumn = screenColumn + - str.length * Math.max(this.getTabSize(), 2); - } - 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]; - } - - /** - * Returns the number of rows required to render this row on the screen - */ - this.getRowLength = function(row) { - if (!this.$useWrapMode || !this.$wrapData[row]) { - return 1; - } else { - return this.$wrapData[row].length + 1; - } - } - - /** - * Returns the height in pixels required to render this row on the screen - **/ - this.getRowHeight = function(config, row) { - return this.getRowLength(row) * config.lineHeight; - } - - 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]; - } - }; - - /** - * Returns the width of a tab character at screenColumn. - */ - 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.$rowCache; - for (var i = 0; i < rowCache.length; i++) { - if (rowCache[i].screenRow < screenRow) { - row = rowCache[i].screenRow; - docRow = rowCache[i].docRow; - } - else { - break; - } - } - var doCache = !rowCache.length || i == rowCache.length; - - 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) { - rowCache.push({ - docRow: docRow, - screenRow: 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 wrapData; - // Special case in wrapMode if the doc is at the end of the document. - if (this.$useWrapMode) { - wrapData = this.$wrapData; - if (docRow > wrapData.length - 1) { - return { - row: this.getScreenLength(), - column: wrapData.length == 0 - ? 0 - : (wrapData[wrapData.length - 1].length - 1) - }; - } - } - - 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.$rowCache; - - for (var i = 0; i < rowCache.length; i++) { - if (rowCache[i].docRow < docRow) { - screenRow = rowCache[i].screenRow; - row = rowCache[i].docRow; - } else { - break; - } - } - var doCache = !rowCache.length || i == rowCache.length; - - 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) { - rowCache.push({ - docRow: row, - screenRow: 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 = 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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/bracket_match.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/bracket_match.js deleted file mode 100644 index 89e6506..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/bracket_match.js +++ /dev/null @@ -1,181 +0,0 @@ -/* 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 - * - * 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(function(require, exports, module) { -"use strict"; - -var TokenIterator = require("../token_iterator").TokenIterator; - -function BracketMatch() { - - 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) { - var openBracket = this.$brackets[bracket]; - var depth = 1; - - var iterator = new TokenIterator(this, position.row, position.column); - var token = iterator.getCurrentToken(); - if (!token) return null; - - // token.type contains a period-delimited list of token identifiers - // (e.g.: "constant.numeric" or "paren.lparen"). Create a pattern that - // matches any token containing the same identifiers or a subset. In - // addition, if token.type includes "rparen", then also match "lparen". - // So if type.token is "paren.rparen", then typeRe will match "lparen.paren". - var typeRe = new RegExp("(\\.?" + - token.type.replace(".", "|").replace("rparen", "lparen|rparen") + ")+"); - - // 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) { - var closingBracket = this.$brackets[bracket]; - var depth = 1; - - var iterator = new TokenIterator(this, position.row, position.column); - var token = iterator.getCurrentToken(); - if (!token) return null; - - // token.type contains a period-delimited list of token identifiers - // (e.g.: "constant.numeric" or "paren.lparen"). Create a pattern that - // matches any token containing the same identifiers or a subset. In - // addition, if token.type includes "lparen", then also match "rparen". - // So if type.token is "lparen.paren", then typeRe will match "paren.rparen". - var typeRe = new RegExp("(\\.?" + - token.type.replace(".", "|").replace("lparen", "lparen|rparen") + ")+"); - - // 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(); - } while (token && !typeRe.test(token.type)); - - if (token == null) - break; - - valueIndex = 0; - } - - return null; - }; -} -exports.BracketMatch = BracketMatch; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/fold.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/fold.js deleted file mode 100644 index 4041ecb..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/fold.js +++ /dev/null @@ -1,116 +0,0 @@ -/* 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): - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -/** - * 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); - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/fold_line.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/fold_line.js deleted file mode 100644 index 569598e..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/fold_line.js +++ /dev/null @@ -1,274 +0,0 @@ -/* 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): - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -var Range = require("../range").Range; - -/** - * If an array is passed in, the folds are expected to be sorted already. - */ -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) - { - throw "Moving characters inside of a fold should never be reached"; - } 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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/folding.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/folding.js deleted file mode 100644 index d6a0810..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session/folding.js +++ /dev/null @@ -1,756 +0,0 @@ -/* 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): - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -var Range = require("../range").Range; -var FoldLine = require("./fold_line").FoldLine; -var Fold = require("./fold").Fold; -var TokenIterator = require("../token_iterator").TokenIterator; - -function Folding() { - /** - * 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; - } - } - }; - - /** - * Returns all folds in the given range. Note, that this will return folds - * - */ - 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; - }; - - /** - * Returns all folds in the document - */ - 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; - }; - - /** - * Returns the string between folds at the given position. - * E.g. - * foob|arwolrd -> "bar" - * foobarwol|rd -> "world" - * foobarwolrd -> - * - * where | means the position of row/column - * - * The trim option determs if the return string should be trimed according - * to the "side" passed with the trim value: - * - * E.g. - * foob|arwolrd -trim=-1> "b" - * foobarwol|rd -trim=+1> "rld" - * fo|obarwolrd -trim=00> "foo" - */ - 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; - }; - - /** - * Adds a new fold. - * - * @returns - * The new created Fold object or an existing fold object in case the - * passed in range fits an existing fold exactly. - */ - 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); - - // 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); - } - - // 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); - } - } - }; - - /** - * Checks if a given documentRow is folded. This is true if there are some - * folded parts such that some parts of the line is still visible. - **/ - 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; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session_test.js deleted file mode 100644 index e2bc7fa..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/edit_session_test.js +++ /dev/null @@ -1,985 +0,0 @@ -/* ***** 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 - * Julian Viereck - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); - require("./test/mockdom"); -} - -define(function(require, exports, module) { -"use strict"; - -var lang = require("./lib/lang"); -var EditSession = require("./edit_session").EditSession; -var Editor = require("./editor").Editor; -var UndoManager = require("./undomanager").UndoManager; -var MockRenderer = require("./test/mockrenderer").MockRenderer; -var Range = require("./range").Range; -var assert = require("./test/assertions"); -var JavaScriptMode = require("./mode/javascript").Mode; - -function createFoldTestSession() { - var lines = [ - "function foo(items) {", - " for (var i=0; i>", [1, 2], 1); - }, - - "test get longest line" : function() { - var session = new EditSession(["12"]); - session.setTabSize(4); - assert.equal(session.getWidth(), 2); - assert.equal(session.getScreenWidth(), 2); - - session.doc.insertNewLine(0); - session.doc.insertLines(1, ["123"]); - assert.equal(session.getWidth(), 3); - assert.equal(session.getScreenWidth(), 3); - - session.doc.insertNewLine(0); - session.doc.insertLines(1, ["\t\t"]); - - assert.equal(session.getWidth(), 3); - assert.equal(session.getScreenWidth(), 8); - - session.setTabSize(2); - assert.equal(session.getWidth(), 3); - assert.equal(session.getScreenWidth(), 4); - }, - - "test getDisplayString": function() { - var session = new EditSession(["12"]); - session.setTabSize(4); - - assert.equal(session.$getDisplayTokens("\t").length, 4); - assert.equal(session.$getDisplayTokens("abc").length, 3); - assert.equal(session.$getDisplayTokens("abc\t").length, 4); - }, - - "test issue 83": function() { - var session = new EditSession(""); - var editor = new Editor(new MockRenderer(), session); - var document = session.getDocument(); - - session.setUseWrapMode(true); - - document.insertLines(0, ["a", "b"]); - document.insertLines(2, ["c", "d"]); - document.removeLines(1, 2); - }, - - "test wrapMode init has to create wrapData array": function() { - var session = new EditSession("foo bar\nfoo bar"); - var editor = new Editor(new MockRenderer(), session); - var document = session.getDocument(); - - session.setUseWrapMode(true); - session.setWrapLimitRange(3, 3); - session.adjustWrapLimit(80); - - // Test if wrapData is there and was computed. - assert.equal(session.$wrapData.length, 2); - assert.equal(session.$wrapData[0].length, 1); - assert.equal(session.$wrapData[1].length, 1); - }, - - "test first line blank with wrap": function() { - var session = new EditSession("\nfoo"); - session.setUseWrapMode(true); - assert.equal(session.doc.getValue(), ["", "foo"].join("\n")); - }, - - "test first line blank with wrap 2" : function() { - var session = new EditSession(""); - session.setUseWrapMode(true); - session.setValue("\nfoo"); - - assert.equal(session.doc.getValue(), ["", "foo"].join("\n")); - }, - - "test fold getFoldDisplayLine": function() { - var session = createFoldTestSession(); - function assertDisplayLine(foldLine, str) { - var line = session.getLine(foldLine.end.row); - var displayLine = - session.getFoldDisplayLine(foldLine, foldLine.end.row, line.length); - assert.equal(displayLine, str); - } - - assertDisplayLine(session.$foldData[0], "function foo(args...) {") - assertDisplayLine(session.$foldData[1], " for (vfoo...ert(items[bar...\"juhu\");"); - }, - - "test foldLine idxToPosition": function() { - var session = createFoldTestSession(); - - function assertIdx2Pos(foldLineIdx, idx, row, column) { - var foldLine = session.$foldData[foldLineIdx]; - assert.position(foldLine.idxToPosition(idx), row, column); - } - -// "function foo(items) {", -// " for (var i=0; i - * Irakli Gozalishvili (http://jeditoolkit.com) - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -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; - -var Editor = function(renderer, session) { - var container = renderer.getContainerElement(); - this.container = container; - this.renderer = renderer; - - this.textInput = new TextInput(renderer.getTextAreaContainer(), this); - 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.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands); - 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.getSelection = function() { - return this.selection; - }; - - this.resize = function() { - this.renderer.onResize(); - }; - - 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() { - this.renderer.showCursor(); - this.renderer.visualizeFocus(); - this._emit("focus"); - }; - - this.onBlur = function() { - this.renderer.hideCursor(); - this.renderer.visualizeBlur(); - this._emit("blur"); - }; - - 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.onCursorChange(); - }; - - 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.renderer.updateCursor(); - - if (!this.$blockScrolling) { - this.renderer.scrollCursorIntoView(); - } - - // move text input over the cursor - // this is required for iOS and IME - this.renderer.moveTextAreaToCursor(this.textInput.getElement()); - - this.$highlightBrackets(); - this.$updateHighlightActiveLine(); - }; - - this.$updateHighlightActiveLine = function() { - var session = this.getSession(); - - if (session.$highlightLineMarker) - session.removeMarker(session.$highlightLineMarker); - if (typeof this.$lastrow == "number") - this.renderer.removeGutterDecoration(this.$lastrow, "ace_gutter_active_line"); - - session.$highlightLineMarker = null; - this.$lastrow = null; - - if (this.getHighlightActiveLine()) { - var cursor = this.getCursorPosition(), - 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.renderer.addGutterDecoration(this.$lastrow = cursor.row, "ace_gutter_active_line"); - } - }; - - this.onSelectionChange = function(e) { - var session = this.getSession(); - - 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(); - } - - if (this.$highlightSelectedWord) - this.session.getMode().highlightSelection(this); - }; - - this.onChangeFrontMarker = function() { - this.renderer.updateFrontMarkers(); - }; - - this.onChangeBackMarker = function() { - this.renderer.updateBackMarkers(); - }; - - this.onChangeBreakpoint = function() { - this.renderer.setBreakpoints(this.session.getBreakpoints()); - }; - - 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.onCut = function() { - this.commands.exec("cut", this); - }; - - 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, pasted) { - if (pasted) - this._emit("paste", text); - - this.keyBinding.onTextInput(text, pasted); - }; - - 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.$highlightSelectedWord = true; - this.setHighlightSelectedWord = function(shouldHighlight) { - if (this.$highlightSelectedWord == shouldHighlight) - return; - - this.$highlightSelectedWord = shouldHighlight; - if (shouldHighlight) - this.session.getMode().highlightSelection(this); - else - this.session.getMode().clearSelectionHighlight(this); - }; - - 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.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.$getPageDownRow = function() { - return this.renderer.getScrollBottomRow(); - }; - - this.$getPageUpRow = function() { - var firstRow = this.renderer.getScrollTopRow(); - var lastRow = this.renderer.getScrollBottomRow(); - - return firstRow - (lastRow - firstRow); - }; - - this.selectPageDown = function() { - var row = this.$getPageDownRow() + Math.floor(this.$getVisibleRowCount() / 2); - - this.scrollPageDown(); - - var selection = this.getSelection(); - var leadScreenPos = this.session.documentToScreenPosition(selection.getSelectionLead()); - var dest = this.session.screenToDocumentPosition(row, leadScreenPos.column); - selection.selectTo(dest.row, dest.column); - }; - - this.selectPageUp = function() { - var visibleRows = this.renderer.getScrollTopRow() - this.renderer.getScrollBottomRow(); - var row = this.$getPageUpRow() + Math.round(visibleRows / 2); - - this.scrollPageUp(); - - var selection = this.getSelection(); - var leadScreenPos = this.session.documentToScreenPosition(selection.getSelectionLead()); - var dest = this.session.screenToDocumentPosition(row, leadScreenPos.column); - selection.selectTo(dest.row, dest.column); - }; - - this.gotoPageDown = function() { - var row = this.$getPageDownRow(); - var column = this.getCursorPositionScreen().column; - - this.scrollToRow(row); - this.getSelection().moveCursorToScreen(row, column); - }; - - this.gotoPageUp = function() { - var row = this.$getPageUpRow(); - var column = this.getCursorPositionScreen().column; - - this.scrollToRow(row); - this.getSelection().moveCursorToScreen(row, column); - }; - - this.scrollPageDown = function() { - this.scrollToRow(this.$getPageDownRow()); - }; - - this.scrollPageUp = function() { - this.renderer.scrollToRow(this.$getPageUpRow()); - }; - - this.scrollToRow = function(row) { - this.renderer.scrollToRow(row); - }; - - this.scrollToLine = function(line, center) { - this.renderer.scrollToLine(line, center); - }; - - 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) { - 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(this.getCursorPosition().row)) - this.scrollToLine(lineNumber, true); - }; - - 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() { - this.selection.moveCursorFileEnd(); - this.clearSelection(); - }; - - this.navigateFileStart = function() { - this.selection.moveCursorFileStart(); - this.clearSelection(); - }; - - this.navigateWordRight = function() { - this.selection.moveCursorWordRight(); - this.clearSelection(); - }; - - this.navigateWordLeft = function() { - this.selection.moveCursorWordLeft(); - this.clearSelection(); - }; - - this.replace = function(replacement, options) { - if (options) - this.$search.set(options); - - var range = this.$search.find(this.session); - var replaced = 0; - if (!range) - return replaced; - - if (this.$tryReplace(range, replacement)) { - replaced = 1; - } - if (range !== null) { - this.selection.setSelectionRange(range); - this.renderer.scrollSelectionIntoView(range.start, range.end); - } - - return replaced; - }; - - this.replaceAll = function(replacement, options) { - if (options) { - this.$search.set(options); - } - - var ranges = this.$search.findAll(this.session); - var replaced = 0; - if (!ranges.length) - return replaced; - - this.$blockScrolling += 1; - - var selection = this.getSelectionRange(); - this.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) { - this.clearSelection(); - options = options || {}; - options.needle = needle; - this.$search.set(options); - this.$find(); - }; - - this.findNext = function(options) { - options = options || {}; - if (typeof options.backwards == "undefined") - options.backwards = false; - this.$search.set(options); - this.$find(); - }; - - this.findPrevious = function(options) { - options = options || {}; - if (typeof options.backwards == "undefined") - options.backwards = true; - this.$search.set(options); - this.$find(); - }; - - this.$find = function(backwards) { - if (!this.selection.isEmpty()) - this.$search.set({needle: this.session.getTextRange(this.getSelectionRange())}); - - if (typeof backwards != "undefined") - this.$search.set({backwards: backwards}); - - var range = this.$search.find(this.session); - if (range) { - this.session.unfold(range); - - this.$blockScrolling += 1; - this.selection.setSelectionRange(range); - this.$blockScrolling -= 1; - - if (this.getAnimatedScroll()) { - var cursor = this.getCursorPosition(); - if (!this.isRowFullyVisible(cursor.row)) - this.scrollToLine(cursor.row, true); - - //@todo scroll X - //if (!this.isColumnFullyVisible(cursor.column)) - //this.scrollToRow(cursor.column); - } - else { - this.renderer.scrollSelectionIntoView(range.start, range.end); - } - } - }; - - this.undo = function() { - this.session.getUndoManager().undo(); - }; - - this.redo = function() { - this.session.getUndoManager().redo(); - }; - - this.destroy = function() { - this.renderer.destroy(); - }; - -}).call(Editor.prototype); - - -exports.Editor = Editor; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_change_document_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_change_document_test.js deleted file mode 100644 index 9464202..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_change_document_test.js +++ /dev/null @@ -1,195 +0,0 @@ -/* ***** 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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); - require("./test/mockdom"); -} - -define(function(require, exports, module) { -"use strict"; - -var EditSession = require("./edit_session").EditSession; -var Editor = require("./editor").Editor; -var Text = require("./mode/text").Mode; -var JavaScriptMode = require("./mode/javascript").Mode; -var CssMode = require("./mode/css").Mode; -var HtmlMode = require("./mode/html").Mode; -var MockRenderer = require("./test/mockrenderer").MockRenderer; -var assert = require("./test/assertions"); - -module.exports = { - - setUp : function(next) { - this.session1 = new EditSession(["abc", "def"]); - this.session2 = new EditSession(["ghi", "jkl"]); - - - this.editor = new Editor(new MockRenderer()); - next(); - }, - - "test: change document" : function() { - this.editor.setSession(this.session1); - assert.equal(this.editor.getSession(), this.session1); - - this.editor.setSession(this.session2); - assert.equal(this.editor.getSession(), this.session2); - }, - - "test: only changes to the new document should have effect" : function() { - var called = false; - this.editor.onDocumentChange = function() { - called = true; - }; - - this.editor.setSession(this.session1); - this.editor.setSession(this.session2); - - this.session1.duplicateLines(0, 0); - assert.notOk(called); - - this.session2.duplicateLines(0, 0); - assert.ok(called); - }, - - "test: should use cursor of new document" : function() { - this.session1.getSelection().moveCursorTo(0, 1); - this.session2.getSelection().moveCursorTo(1, 0); - - this.editor.setSession(this.session1); - assert.position(this.editor.getCursorPosition(), 0, 1); - - this.editor.setSession(this.session2); - assert.position(this.editor.getCursorPosition(), 1, 0); - }, - - "test: only changing the cursor of the new doc should not have an effect" : function() { - this.editor.onCursorChange = function() { - called = true; - }; - - this.editor.setSession(this.session1); - this.editor.setSession(this.session2); - assert.position(this.editor.getCursorPosition(), 0, 0); - - var called = false; - this.session1.getSelection().moveCursorTo(0, 1); - assert.position(this.editor.getCursorPosition(), 0, 0); - assert.notOk(called); - - this.session2.getSelection().moveCursorTo(1, 1); - assert.position(this.editor.getCursorPosition(), 1, 1); - assert.ok(called); - }, - - "test: should use selection of new document" : function() { - this.session1.getSelection().selectTo(0, 1); - this.session2.getSelection().selectTo(1, 0); - - this.editor.setSession(this.session1); - assert.position(this.editor.getSelection().getSelectionLead(), 0, 1); - - this.editor.setSession(this.session2); - assert.position(this.editor.getSelection().getSelectionLead(), 1, 0); - }, - - "test: only changing the selection of the new doc should not have an effect" : function() { - this.editor.onSelectionChange = function() { - called = true; - }; - - this.editor.setSession(this.session1); - this.editor.setSession(this.session2); - assert.position(this.editor.getSelection().getSelectionLead(), 0, 0); - - var called = false; - this.session1.getSelection().selectTo(0, 1); - assert.position(this.editor.getSelection().getSelectionLead(), 0, 0); - assert.notOk(called); - - this.session2.getSelection().selectTo(1, 1); - assert.position(this.editor.getSelection().getSelectionLead(), 1, 1); - assert.ok(called); - }, - - "test: should use mode of new document" : function() { - this.editor.onChangeMode = function() { - called = true; - }; - this.editor.setSession(this.session1); - this.editor.setSession(this.session2); - - var called = false; - this.session1.setMode(new Text()); - assert.notOk(called); - - this.session2.setMode(new JavaScriptMode()); - assert.ok(called); - }, - - "test: should use stop worker of old document" : function(next) { - var self = this; - - // 1. Open an editor and set the session to CssMode - self.editor.setSession(self.session1); - self.session1.setMode(new CssMode()); - - // 2. Add a line or two of valid CSS. - self.session1.setValue("DIV { color: red; }"); - - // 3. Clear the session value. - self.session1.setValue(""); - - // 4. Set the session to HtmlMode - self.session1.setMode(new HtmlMode()); - - // 5. Try to type valid HTML - self.session1.insert({row: 0, column: 0}, ""); - - setTimeout(function() { - assert.equal(Object.keys(self.session1.getAnnotations()).length, 0); - next(); - }, 600); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec() -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_highlight_selected_word_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_highlight_selected_word_test.js deleted file mode 100644 index b734b63..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_highlight_selected_word_test.js +++ /dev/null @@ -1,215 +0,0 @@ -/* 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 - * Mihai Sucan. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Mihai Sucan - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); - require("./test/mockdom"); -} - -define(function(require, exports, module) { -"use strict"; - -var EditSession = require("./edit_session").EditSession; -var Editor = require("./editor").Editor; -var MockRenderer = require("./test/mockrenderer").MockRenderer; -var assert = require("./test/assertions"); - -var lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + - "Mauris at arcu mi, eu lobortis mauris. Quisque ut libero eget " + - "diam congue vehicula. Quisque ut odio ut mi aliquam tincidunt. " + - "Duis lacinia aliquam lorem eget eleifend. Morbi eget felis mi. " + - "Duis quam ligula, consequat vitae convallis volutpat, blandit " + - "nec neque. Nulla facilisi. Etiam suscipit lorem ac justo " + - "sollicitudin tristique. Phasellus ut posuere nunc. Aliquam " + - "scelerisque mollis felis non gravida. Vestibulum lacus sem, " + - "posuere non bibendum id, luctus non dolor. Aenean id metus " + - "lorem, vel dapibus est. Donec gravida feugiat augue nec " + - "accumsan.Lorem ipsum dolor sit amet, consectetur adipiscing " + - "elit. Nulla vulputate, velit vitae tincidunt congue, nunc " + - "augue accumsan velit, eu consequat turpis lectus ac orci. " + - "Pellentesque ornare dolor feugiat dui auctor eu varius nulla " + - "fermentum. Sed aliquam odio at velit lacinia vel fermentum " + - "felis sodales. In dignissim magna eget nunc lobortis non " + - "fringilla nibh ullamcorper. Donec facilisis malesuada elit " + - "at egestas. Etiam bibendum, diam vitae tempor aliquet, dui " + - "libero vehicula odio, eget bibendum mauris velit eu lorem.\n" + - "consectetur"; - -module.exports = { - setUp: function(next) { - this.session = new EditSession(lipsum); - this.editor = new Editor(new MockRenderer(), this.session); - this.selection = this.session.getSelection(); - this.search = this.editor.$search; - next(); - }, - - "test: highlight selected words by default": function() { - assert.equal(this.editor.getHighlightSelectedWord(), true); - }, - - "test: highlight a word": function() { - this.editor.moveCursorTo(0, 9); - this.selection.selectWord(); - - var range = this.selection.getRange(); - assert.equal(this.session.getTextRange(range), "ipsum"); - assert.equal(this.session.$selectionOccurrences.length, 1); - }, - - "test: highlight a word and clear highlight": function() { - this.editor.moveCursorTo(0, 8); - this.selection.selectWord(); - - var range = this.selection.getRange(); - assert.equal(this.session.getTextRange(range), "ipsum"); - assert.equal(this.session.$selectionOccurrences.length, 1); - - this.session.getMode().clearSelectionHighlight(this.editor); - assert.equal(this.session.$selectionOccurrences.length, 0); - }, - - "test: highlight another word": function() { - this.selection.moveCursorTo(0, 14); - this.selection.selectWord(); - - var range = this.selection.getRange(); - assert.equal(this.session.getTextRange(range), "dolor"); - assert.equal(this.session.$selectionOccurrences.length, 3); - }, - - "test: no selection, no highlight": function() { - this.selection.clearSelection(); - assert.equal(this.session.$selectionOccurrences.length, 0); - }, - - "test: select a word, no highlight": function() { - this.editor.setHighlightSelectedWord(false); - this.selection.moveCursorTo(0, 14); - this.selection.selectWord(); - - var range = this.selection.getRange(); - assert.equal(this.session.getTextRange(range), "dolor"); - assert.equal(this.session.$selectionOccurrences.length, 0); - }, - - "test: select a word with no matches": function() { - this.editor.setHighlightSelectedWord(true); - - var currentOptions = this.search.getOptions(); - var newOptions = { - wrap: true, - wholeWord: true, - caseSensitive: true, - needle: "Mauris" - }; - this.search.set(newOptions); - - var match = this.search.find(this.session); - assert.notEqual(match, null, "found a match for 'Mauris'"); - - this.search.set(currentOptions); - - this.selection.setSelectionRange(match); - - assert.equal(this.session.getTextRange(match), "Mauris"); - assert.equal(this.session.$selectionOccurrences.length, 0); - }, - - "test: partial word selection 1": function() { - this.selection.moveCursorTo(0, 14); - this.selection.selectWord(); - this.selection.selectLeft(); - - var range = this.selection.getRange(); - assert.equal(this.session.getTextRange(range), "dolo"); - assert.equal(this.session.$selectionOccurrences.length, 0); - }, - - "test: partial word selection 2": function() { - this.selection.moveCursorTo(0, 13); - this.selection.selectWord(); - this.selection.selectRight(); - - var range = this.selection.getRange(); - assert.equal(this.session.getTextRange(range), "dolor "); - assert.equal(this.session.$selectionOccurrences.length, 0); - }, - - "test: partial word selection 3": function() { - this.selection.moveCursorTo(0, 14); - this.selection.selectWord(); - this.selection.selectLeft(); - this.selection.shiftSelection(1); - - var range = this.selection.getRange(); - assert.equal(this.session.getTextRange(range), "olor"); - assert.equal(this.session.$selectionOccurrences.length, 0); - }, - - "test: select last word": function() { - this.selection.moveCursorTo(0, 1); - - var currentOptions = this.search.getOptions(); - var newOptions = { - wrap: true, - wholeWord: true, - caseSensitive: true, - backwards: true, - needle: "consectetur" - }; - this.search.set(newOptions); - - var match = this.search.find(this.session); - assert.notEqual(match, null, "found a match for 'consectetur'"); - assert.position(match.start, 1, 0); - - this.search.set(currentOptions); - - this.selection.setSelectionRange(match); - - assert.equal(this.session.getTextRange(match), "consectetur"); - assert.equal(this.session.$selectionOccurrences.length, 2); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec(); -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_navigation_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_navigation_test.js deleted file mode 100644 index 97ba4b3..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_navigation_test.js +++ /dev/null @@ -1,171 +0,0 @@ -/* ***** 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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); - require("./test/mockdom"); -} - -define(function(require, exports, module) { -"use strict"; - -var EditSession = require("./edit_session").EditSession; -var Editor = require("./editor").Editor; -var MockRenderer = require("./test/mockrenderer").MockRenderer; -var assert = require("./test/assertions"); - -module.exports = { - createEditSession : function(rows, cols) { - var line = new Array(cols + 1).join("a"); - var text = new Array(rows).join(line + "\n") + line; - return new EditSession(text); - }, - - "test: navigate to end of file should scroll the last line into view" : function() { - var doc = this.createEditSession(200, 10); - var editor = new Editor(new MockRenderer(), doc); - - editor.navigateFileEnd(); - var cursor = editor.getCursorPosition(); - - assert.ok(editor.getFirstVisibleRow() <= cursor.row); - assert.ok(editor.getLastVisibleRow() >= cursor.row); - }, - - "test: navigate to start of file should scroll the first row into view" : function() { - var doc = this.createEditSession(200, 10); - var editor = new Editor(new MockRenderer(), doc); - - editor.moveCursorTo(editor.getLastVisibleRow() + 20); - editor.navigateFileStart(); - - assert.equal(editor.getFirstVisibleRow(), 0); - }, - - "test: goto hidden line should scroll the line into the middle of the viewport" : function() { - var editor = new Editor(new MockRenderer(), this.createEditSession(200, 5)); - - editor.navigateTo(0, 0); - editor.gotoLine(101); - assert.position(editor.getCursorPosition(), 100, 0); - assert.equal(editor.getFirstVisibleRow(), 90); - - editor.navigateTo(100, 0); - editor.gotoLine(11); - assert.position(editor.getCursorPosition(), 10, 0); - assert.equal(editor.getFirstVisibleRow(), 0); - - editor.navigateTo(100, 0); - editor.gotoLine(6); - assert.position(editor.getCursorPosition(), 5, 0); - assert.equal(0, editor.getFirstVisibleRow(), 0); - - editor.navigateTo(100, 0); - editor.gotoLine(1); - assert.position(editor.getCursorPosition(), 0, 0); - assert.equal(editor.getFirstVisibleRow(), 0); - - editor.navigateTo(0, 0); - editor.gotoLine(191); - assert.position(editor.getCursorPosition(), 190, 0); - assert.equal(editor.getFirstVisibleRow(), 180); - - editor.navigateTo(0, 0); - editor.gotoLine(196); - assert.position(editor.getCursorPosition(), 195, 0); - assert.equal(editor.getFirstVisibleRow(), 180); - }, - - "test: goto visible line should only move the cursor and not scroll": function() { - var editor = new Editor(new MockRenderer(), this.createEditSession(200, 5)); - - editor.navigateTo(0, 0); - editor.gotoLine(12); - assert.position(editor.getCursorPosition(), 11, 0); - assert.equal(editor.getFirstVisibleRow(), 0); - - editor.navigateTo(30, 0); - editor.gotoLine(33); - assert.position(editor.getCursorPosition(), 32, 0); - assert.equal(editor.getFirstVisibleRow(), 30); - }, - - "test: navigate from the end of a long line down to a short line and back should maintain the curser column": function() { - var editor = new Editor(new MockRenderer(), new EditSession(["123456", "1"])); - - editor.navigateTo(0, 6); - assert.position(editor.getCursorPosition(), 0, 6); - - editor.navigateDown(); - assert.position(editor.getCursorPosition(), 1, 1); - - editor.navigateUp(); - assert.position(editor.getCursorPosition(), 0, 6); - }, - - "test: reset desired column on navigate left or right": function() { - var editor = new Editor(new MockRenderer(), new EditSession(["123456", "12"])); - - editor.navigateTo(0, 6); - assert.position(editor.getCursorPosition(), 0, 6); - - editor.navigateDown(); - assert.position(editor.getCursorPosition(), 1, 2); - - editor.navigateLeft(); - assert.position(editor.getCursorPosition(), 1, 1); - - editor.navigateUp(); - assert.position(editor.getCursorPosition(), 0, 1); - }, - - "test: typing text should update the desired column": function() { - var editor = new Editor(new MockRenderer(), new EditSession(["1234", "1234567890"])); - - editor.navigateTo(0, 3); - editor.insert("juhu"); - - editor.navigateDown(); - assert.position(editor.getCursorPosition(), 1, 7); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec() -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_text_edit_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_text_edit_test.js deleted file mode 100644 index 244c299..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/editor_text_edit_test.js +++ /dev/null @@ -1,562 +0,0 @@ -/* ***** 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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); - require("./test/mockdom"); -} - -define(function(require, exports, module) { -"use strict"; - -var EditSession = require("./edit_session").EditSession; -var Editor = require("./editor").Editor; -var JavaScriptMode = require("./mode/javascript").Mode; -var UndoManager = require("./undomanager").UndoManager; -var MockRenderer = require("./test/mockrenderer").MockRenderer; -var assert = require("./test/assertions"); - -module.exports = { - "test: delete line from the middle" : function() { - var session = new EditSession(["a", "b", "c", "d"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(1, 1); - editor.removeLines(); - - assert.equal(session.toString(), "a\nc\nd"); - assert.position(editor.getCursorPosition(), 1, 0); - - editor.removeLines(); - - assert.equal(session.toString(), "a\nd"); - assert.position(editor.getCursorPosition(), 1, 0); - - editor.removeLines(); - - assert.equal(session.toString(), "a"); - assert.position(editor.getCursorPosition(), 0, 1); - - editor.removeLines(); - - assert.equal(session.toString(), ""); - assert.position(editor.getCursorPosition(), 0, 0); - }, - - "test: delete multiple selected lines" : function() { - var session = new EditSession(["a", "b", "c", "d"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(1, 1); - editor.getSelection().selectDown(); - - editor.removeLines(); - assert.equal(session.toString(), "a\nd"); - assert.position(editor.getCursorPosition(), 1, 0); - }, - - "test: delete first line" : function() { - var session = new EditSession(["a", "b", "c"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.removeLines(); - - assert.equal(session.toString(), "b\nc"); - assert.position(editor.getCursorPosition(), 0, 0); - }, - - "test: delete last should also delete the new line of the previous line" : function() { - var session = new EditSession(["a", "b", "c", ""].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(3, 0); - - editor.removeLines(); - assert.equal(session.toString(), "a\nb\nc"); - assert.position(editor.getCursorPosition(), 2, 1); - - editor.removeLines(); - assert.equal(session.toString(), "a\nb"); - assert.position(editor.getCursorPosition(), 1, 1); - }, - - "test: indent block" : function() { - var session = new EditSession(["a12345", "b12345", "c12345"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(1, 3); - editor.getSelection().selectDown(); - - editor.indent(); - - assert.equal(["a12345", " b12345", " c12345"].join("\n"), session.toString()); - - assert.position(editor.getCursorPosition(), 2, 7); - - var range = editor.getSelectionRange(); - assert.position(range.start, 1, 7); - assert.position(range.end, 2, 7); - }, - - "test: indent selected lines" : function() { - var session = new EditSession(["a12345", "b12345", "c12345"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(1, 0); - editor.getSelection().selectDown(); - - editor.indent(); - assert.equal(["a12345", " b12345", "c12345"].join("\n"), session.toString()); - }, - - "test: no auto indent if cursor is before the {" : function() { - var session = new EditSession("{", new JavaScriptMode()); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(0, 0); - editor.onTextInput("\n"); - assert.equal(["", "{"].join("\n"), session.toString()); - }, - - "test: outdent block" : function() { - var session = new EditSession([" a12345", " b12345", " c12345"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(0, 5); - editor.getSelection().selectDown(); - editor.getSelection().selectDown(); - - editor.blockOutdent(); - assert.equal(session.toString(), [" a12345", "b12345", " c12345"].join("\n")); - - assert.position(editor.getCursorPosition(), 2, 1); - - var range = editor.getSelectionRange(); - assert.position(range.start, 0, 1); - assert.position(range.end, 2, 1); - - editor.blockOutdent(); - assert.equal(session.toString(), ["a12345", "b12345", "c12345"].join("\n")); - - var range = editor.getSelectionRange(); - assert.position(range.start, 0, 0); - assert.position(range.end, 2, 0); - }, - - "test: outent without a selection should update cursor" : function() { - var session = new EditSession(" 12"); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(0, 3); - editor.blockOutdent(" "); - - assert.equal(session.toString(), " 12"); - assert.position(editor.getCursorPosition(), 0, 0); - }, - - "test: comment lines should perserve selection" : function() { - var session = new EditSession([" abc", "cde"].join("\n"), new JavaScriptMode()); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(0, 2); - editor.getSelection().selectDown(); - editor.toggleCommentLines(); - - assert.equal(["// abc", "//cde"].join("\n"), session.toString()); - - var selection = editor.getSelectionRange(); - assert.position(selection.start, 0, 4); - assert.position(selection.end, 1, 4); - }, - - "test: uncomment lines should perserve selection" : function() { - var session = new EditSession(["// abc", "//cde"].join("\n"), new JavaScriptMode()); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(0, 1); - editor.getSelection().selectDown(); - editor.getSelection().selectRight(); - editor.getSelection().selectRight(); - - editor.toggleCommentLines(); - - assert.equal([" abc", "cde"].join("\n"), session.toString()); - assert.range(editor.getSelectionRange(), 0, 0, 1, 1); - }, - - "test: toggle comment lines twice should return the original text" : function() { - var session = new EditSession([" abc", "cde", "fg"], new JavaScriptMode()); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(0, 0); - editor.getSelection().selectDown(); - editor.getSelection().selectDown(); - - editor.toggleCommentLines(); - editor.toggleCommentLines(); - - assert.equal([" abc", "cde", "fg"].join("\n"), session.toString()); - }, - - - "test: comment lines - if the selection end is at the line start it should stay there": function() { - //select down - var session = new EditSession(["abc", "cde"].join("\n"), new JavaScriptMode()); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(0, 0); - editor.getSelection().selectDown(); - - editor.toggleCommentLines(); - assert.range(editor.getSelectionRange(), 0, 2, 1, 0); - - // select up - var session = new EditSession(["abc", "cde"].join("\n"), new JavaScriptMode()); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(1, 0); - editor.getSelection().selectUp(); - - editor.toggleCommentLines(); - assert.range(editor.getSelectionRange(), 0, 2, 1, 0); - }, - - "test: move lines down should select moved lines" : function() { - var session = new EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(0, 1); - editor.getSelection().selectDown(); - - editor.moveLinesDown(); - assert.equal(["33", "11", "22", "44"].join("\n"), session.toString()); - assert.position(editor.getCursorPosition(), 1, 0); - assert.position(editor.getSelection().getSelectionAnchor(), 3, 0); - assert.position(editor.getSelection().getSelectionLead(), 1, 0); - - editor.moveLinesDown(); - assert.equal(["33", "44", "11", "22"].join("\n"), session.toString()); - assert.position(editor.getCursorPosition(), 2, 0); - assert.position(editor.getSelection().getSelectionAnchor(), 3, 2); - assert.position(editor.getSelection().getSelectionLead(), 2, 0); - - // moving again should have no effect - editor.moveLinesDown(); - assert.equal(["33", "44", "11", "22"].join("\n"), session.toString()); - assert.position(editor.getCursorPosition(), 2, 0); - assert.position(editor.getSelection().getSelectionAnchor(), 3, 2); - assert.position(editor.getSelection().getSelectionLead(), 2, 0); - }, - - "test: move lines up should select moved lines" : function() { - var session = new EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(2, 1); - editor.getSelection().selectDown(); - - editor.moveLinesUp(); - assert.equal(session.toString(), ["11", "33", "44", "22"].join("\n")); - assert.position(editor.getCursorPosition(), 1, 0); - assert.position(editor.getSelection().getSelectionAnchor(), 3, 0); - assert.position(editor.getSelection().getSelectionLead(), 1, 0); - - editor.moveLinesUp(); - assert.equal(session.toString(), ["33", "44", "11", "22"].join("\n")); - assert.position(editor.getCursorPosition(), 0, 0); - assert.position(editor.getSelection().getSelectionAnchor(), 2, 0); - assert.position(editor.getSelection().getSelectionLead(), 0, 0); - }, - - "test: move line without active selection should not move cursor relative to the moved line" : function() - { - var session = new EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(1, 1); - editor.clearSelection(); - - editor.moveLinesDown(); - assert.equal(["11", "33", "22", "44"].join("\n"), session.toString()); - assert.position(editor.getCursorPosition(), 2, 1); - - editor.clearSelection(); - - editor.moveLinesUp(); - assert.equal(["11", "22", "33", "44"].join("\n"), session.toString()); - assert.position(editor.getCursorPosition(), 1, 1); - }, - - "test: copy lines down should select lines and place cursor at the selection start" : function() { - var session = new EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(1, 1); - editor.getSelection().selectDown(); - - editor.copyLinesDown(); - assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString()); - - assert.position(editor.getCursorPosition(), 3, 0); - assert.position(editor.getSelection().getSelectionAnchor(), 5, 0); - assert.position(editor.getSelection().getSelectionLead(), 3, 0); - }, - - "test: copy lines up should select lines and place cursor at the selection start" : function() { - var session = new EditSession(["11", "22", "33", "44"].join("\n")); - var editor = new Editor(new MockRenderer(), session); - - editor.moveCursorTo(1, 1); - editor.getSelection().selectDown(); - - editor.copyLinesUp(); - assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString()); - - assert.position(editor.getCursorPosition(), 1, 0); - assert.position(editor.getSelection().getSelectionAnchor(), 3, 0); - assert.position(editor.getSelection().getSelectionLead(), 1, 0); - }, - - "test: input a tab with soft tab should convert it to spaces" : function() { - var session = new EditSession(""); - var editor = new Editor(new MockRenderer(), session); - - session.setTabSize(2); - session.setUseSoftTabs(true); - - editor.onTextInput("\t"); - assert.equal(session.toString(), " "); - - session.setTabSize(5); - editor.onTextInput("\t"); - assert.equal(session.toString(), " "); - }, - - "test: input tab without soft tabs should keep the tab character" : function() { - var session = new EditSession(""); - var editor = new Editor(new MockRenderer(), session); - - session.setUseSoftTabs(false); - - editor.onTextInput("\t"); - assert.equal(session.toString(), "\t"); - }, - - "test: undo/redo for delete line" : function() { - var session = new EditSession(["111", "222", "333"]); - var undoManager = new UndoManager(); - session.setUndoManager(undoManager); - - var initialText = session.toString(); - var editor = new Editor(new MockRenderer(), session); - - editor.removeLines(); - var step1 = session.toString(); - assert.equal(step1, "222\n333"); - session.$syncInformUndoManager(); - - editor.removeLines(); - var step2 = session.toString(); - assert.equal(step2, "333"); - session.$syncInformUndoManager(); - - editor.removeLines(); - var step3 = session.toString(); - assert.equal(step3, ""); - session.$syncInformUndoManager(); - - undoManager.undo(); - session.$syncInformUndoManager(); - assert.equal(session.toString(), step2); - - undoManager.undo(); - session.$syncInformUndoManager(); - assert.equal(session.toString(), step1); - - undoManager.undo(); - session.$syncInformUndoManager(); - assert.equal(session.toString(), initialText); - - undoManager.undo(); - session.$syncInformUndoManager(); - assert.equal(session.toString(), initialText); - }, - - "test: remove left should remove character left of the cursor" : function() { - var session = new EditSession(["123", "456"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 1); - editor.remove("left"); - assert.equal(session.toString(), "123\n56"); - }, - - "test: remove left should remove line break if cursor is at line start" : function() { - var session = new EditSession(["123", "456"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 0); - editor.remove("left"); - assert.equal(session.toString(), "123456"); - }, - - "test: remove left should remove tabsize spaces if cursor is on a tab stop and preceeded by spaces" : function() { - var session = new EditSession(["123", " 456"]); - session.setUseSoftTabs(true); - session.setTabSize(4); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 8); - editor.remove("left"); - assert.equal(session.toString(), "123\n 456"); - }, - - "test: transpose at line start should be a noop": function() { - var session = new EditSession(["123", "4567", "89"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 0); - editor.transposeLetters(); - - assert.equal(session.getValue(), ["123", "4567", "89"].join("\n")); - }, - - "test: transpose in line should swap the charaters before and after the cursor": function() { - var session = new EditSession(["123", "4567", "89"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 2); - editor.transposeLetters(); - - assert.equal(session.getValue(), ["123", "4657", "89"].join("\n")); - }, - - "test: transpose at line end should swap the last two characters": function() { - var session = new EditSession(["123", "4567", "89"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 4); - editor.transposeLetters(); - - assert.equal(session.getValue(), ["123", "4576", "89"].join("\n")); - }, - - "test: transpose with non empty selection should be a noop": function() { - var session = new EditSession(["123", "4567", "89"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 1); - editor.getSelection().selectRight(); - editor.transposeLetters(); - - assert.equal(session.getValue(), ["123", "4567", "89"].join("\n")); - }, - - "test: transpose should move the cursor behind the last swapped character": function() { - var session = new EditSession(["123", "4567", "89"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 2); - editor.transposeLetters(); - assert.position(editor.getCursorPosition(), 1, 3); - }, - - "test: remove to line end": function() { - var session = new EditSession(["123", "4567", "89"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 2); - editor.removeToLineEnd(); - assert.equal(session.getValue(), ["123", "45", "89"].join("\n")); - }, - - "test: remove to line end at line end should remove the new line": function() { - var session = new EditSession(["123", "4567", "89"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 4); - editor.removeToLineEnd(); - assert.position(editor.getCursorPosition(), 1, 4); - assert.equal(session.getValue(), ["123", "456789"].join("\n")); - }, - - "test: transform selection to uppercase": function() { - var session = new EditSession(["ajax", "dot", "org"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 0); - editor.getSelection().selectLineEnd(); - editor.toUpperCase() - assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n")); - }, - - "test: transform word to uppercase": function() { - var session = new EditSession(["ajax", "dot", "org"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 0); - editor.toUpperCase() - assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n")); - assert.position(editor.getCursorPosition(), 1, 0); - }, - - "test: transform selection to lowercase": function() { - var session = new EditSession(["AJAX", "DOT", "ORG"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 0); - editor.getSelection().selectLineEnd(); - editor.toLowerCase() - assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n")); - }, - - "test: transform word to lowercase": function() { - var session = new EditSession(["AJAX", "DOT", "ORG"]); - - var editor = new Editor(new MockRenderer(), session); - editor.moveCursorTo(1, 0); - editor.toLowerCase() - assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n")); - assert.position(editor.getCursorPosition(), 1, 0); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec() -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/static.css b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/static.css deleted file mode 100644 index 7d785b4..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/static.css +++ /dev/null @@ -1,22 +0,0 @@ -.ace_editor { - font-family: 'Monaco', 'Menlo', 'Droid Sans Mono', 'Courier New', monospace; - font-size: 12px; -} - -.ace_editor .ace_gutter { - width: 25px !important; - display: block; - float: left; - text-align: right; - padding: 0 3px 0 0; - margin-right: 3px; -} - -.ace_line { clear: both; } - -*.ace_gutter-cell { - -moz-user-select: -moz-none; - -khtml-user-select: none; - -webkit-user-select: none; - user-select: none; -} \ No newline at end of file diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/static_highlight.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/static_highlight.js deleted file mode 100644 index 49602f3..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/static_highlight.js +++ /dev/null @@ -1,98 +0,0 @@ -/* 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): - * Jan Jongboom - * Fabian Jakobs - * - * 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(function(require, exports, module) { -"use strict"; - -var EditSession = require("../edit_session").EditSession; -var TextLayer = require("../layer/text").Text; -var baseStyles = require("../requirejs/text!./static.css"); - -/** Transforms a given input code snippet into HTML using the given mode -* -* @param {string} input Code snippet -* @param {mode} mode Mode loaded from /ace/mode (use 'ServerSideHiglighter.getMode') -* @param {string} r Code snippet -* @returns {object} An object containing: html, css -*/ - -exports.render = function(input, mode, theme, lineStart) { - lineStart = parseInt(lineStart || 1, 10); - - var session = new EditSession(""); - session.setMode(mode); - session.setUseWorker(false); - - var textLayer = new TextLayer(document.createElement("div")); - textLayer.setSession(session); - textLayer.config = { - characterWidth: 10, - lineHeight: 20 - }; - - session.setValue(input); - - var stringBuilder = []; - var length = session.getLength(); - var tokens = session.getTokens(0, length - 1); - - for(var ix = 0; ix < length; ix++) { - var lineTokens = tokens[ix].tokens; - stringBuilder.push("
"); - stringBuilder.push("" + (ix + lineStart) + ""); - textLayer.$renderLine(stringBuilder, 0, lineTokens, true); - stringBuilder.push("
"); - } - - // let's prepare the whole html - var html = "
\ -
\ - :code\ -
\ -
".replace(/:cssClass/, theme.cssClass).replace(/:code/, stringBuilder.join("")); - - textLayer.destroy(); - - return { - css: baseStyles + theme.cssText, - html: html - }; -}; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/static_highlight_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/static_highlight_test.js deleted file mode 100644 index f6e5c90..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/static_highlight_test.js +++ /dev/null @@ -1,81 +0,0 @@ -if (typeof process !== "undefined") { - require("amd-loader"); - require("../test/mockdom"); -} - -define(function(require, exports, module) { -"use strict"; - -var assert = require("assert"); -var highlighter = require("./static_highlight"); -var JavaScriptMode = require("../mode/javascript").Mode; - -// Execution ORDER: test.setUpSuite, setUp, testFn, tearDown, test.tearDownSuite -module.exports = { - timeout: 10000, - - "test simple snippet": function(next) { - var theme = require("../theme/tomorrow"); - var snippet = "/** this is a function\n\ -*\n\ -*/\n\ -function hello (a, b, c) {\n\ - console.log(a * b + c + 'sup?');\n\ -}"; - var mode = new JavaScriptMode(); - - var isError = false, result; - try { - result = highlighter.render(snippet, mode, theme); - } - catch (e) { - console.log(e); - isError = true; - } - // todo: write something more meaningful - assert.equal(isError, false); - - next(); - }, - - "test css from theme is used": function(next) { - var theme = require("../theme/tomorrow"); - var snippet = "/** this is a function\n\ -*\n\ -*/\n\ -function hello (a, b, c) {\n\ - console.log(a * b + c + 'sup?');\n\ -}"; - var mode = new JavaScriptMode(); - - var isError = false, result; - result = highlighter.render(snippet, mode, theme); - - assert.ok(result.css.indexOf(theme.cssText) !== -1); - - next(); - }, - - "test theme classname should be in output html": function (next) { - var theme = require("../theme/tomorrow"); - var snippet = "/** this is a function\n\ -*\n\ -*/\n\ -function hello (a, b, c) {\n\ - console.log(a * b + c + 'sup?');\n\ -}"; - var mode = new JavaScriptMode(); - - var isError = false, result; - result = highlighter.render(snippet, mode, theme); - assert.equal(!!result.html.match(/
/), true); - - next(); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec(); -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/textarea.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/textarea.js deleted file mode 100644 index 5dee3ec..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/ext/textarea.js +++ /dev/null @@ -1,506 +0,0 @@ -/* ***** 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): - * Kevin Dangoor (kdangoor@mozilla.com) - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -var Event = require("../lib/event"); -var UA = require("../lib/useragent"); -var net = require("../lib/net"); -var ace = require("../ace"); - -require("ace/theme/textmate"); - -/** - * Returns the CSS property of element. - * 1) If the CSS property is on the style object of the element, use it, OR - * 2) Compute the CSS property - * - * If the property can't get computed, is 'auto' or 'intrinsic', the former - * calculated property is uesd (this can happen in cases where the textarea - * is hidden and has no dimension styles). - */ -var getCSSProperty = function(element, container, property) { - var ret = element.style[property]; - - if (!ret) { - if (window.getComputedStyle) { - ret = window.getComputedStyle(element, '').getPropertyValue(property); - } else { - ret = element.currentStyle[property]; - } - } - - if (!ret || ret == 'auto' || ret == 'intrinsic') { - ret = container.style[property]; - } - return ret; -}; - -function applyStyles(elm, styles) { - for (var style in styles) { - elm.style[style] = styles[style]; - } -} - -function setupContainer(element, getValue) { - if (element.type != 'textarea') { - throw "Textarea required!"; - } - - var parentNode = element.parentNode; - - // This will hold the editor. - var container = document.createElement('div'); - - // To put Ace in the place of the textarea, we have to copy a few of the - // textarea's style attributes to the div container. - // - // The problem is that the properties have to get computed (they might be - // defined by a CSS file on the page - you can't access such rules that - // apply to an element via elm.style). Computed properties are converted to - // pixels although the dimension might be given as percentage. When the - // window resizes, the dimensions defined by percentages changes, so the - // properties have to get recomputed to get the new/true pixels. - var resizeEvent = function() { - var style = 'position:relative;'; - [ - 'margin-top', 'margin-left', 'margin-right', 'margin-bottom' - ].forEach(function(item) { - style += item + ':' + - getCSSProperty(element, container, item) + ';'; - }); - - // Calculating the width/height of the textarea is somewhat tricky. To - // do it right, you have to include the paddings to the sides as well - // (eg. width = width + padding-left, -right). This works well, as - // long as the width of the element is not set or given in pixels. In - // this case and after the textarea is hidden, getCSSProperty(element, - // container, 'width') will still return pixel value. If the element - // has realtiv dimensions (e.g. width='95') - // getCSSProperty(...) will return pixel values only as long as the - // textarea is visible. After it is hidden getCSSProperty will return - // the relative dimensions as they are set on the element (in the case - // of width, 95). - // Making the sum of pixel vaules (e.g. padding) and realtive values - // (e.g. ) is not possible. As such the padding styles are - // ignored. - - // The complete width is the width of the textarea + the padding - // to the left and right. - var width = getCSSProperty(element, container, 'width') || (element.clientWidth + "px"); - var height = getCSSProperty(element, container, 'height') || (element.clientHeight + "px"); - style += 'height:' + height + ';width:' + width + ';'; - - // Set the display property to 'inline-block'. - style += 'display:inline-block;'; - container.setAttribute('style', style); - }; - Event.addListener(window, 'resize', resizeEvent); - - // Call the resizeEvent once, so that the size of the container is - // calculated. - resizeEvent(); - - // Insert the div container after the element. - if (element.nextSibling) { - parentNode.insertBefore(container, element.nextSibling); - } else { - parentNode.appendChild(container); - } - - // Override the forms onsubmit function. Set the innerHTML and value - // of the textarea before submitting. - while (parentNode !== document) { - if (parentNode.tagName.toUpperCase() === 'FORM') { - var oldSumit = parentNode.onsubmit; - // Override the onsubmit function of the form. - parentNode.onsubmit = function(evt) { - element.innerHTML = getValue(); - element.value = getValue(); - // If there is a onsubmit function already, then call - // it with the current context and pass the event. - if (oldSumit) { - oldSumit.call(this, evt); - } - }; - break; - } - parentNode = parentNode.parentNode; - } - return container; -} - -exports.transformTextarea = function(element, loader) { - var session; - var container = setupContainer(element, function() { - return session.getValue(); - }); - - // Hide the element. - element.style.display = 'none'; - container.style.background = 'white'; - - // - var editorDiv = document.createElement("div"); - applyStyles(editorDiv, { - top: "0px", - left: "0px", - right: "0px", - bottom: "0px", - border: "1px solid gray" - }); - container.appendChild(editorDiv); - - var settingOpener = document.createElement("div"); - applyStyles(settingOpener, { - position: "absolute", - width: "15px", - right: "0px", - bottom: "0px", - background: "red", - cursor: "pointer", - textAlign: "center", - fontSize: "12px" - }); - settingOpener.innerHTML = "I"; - - var settingDiv = document.createElement("div"); - var settingDivStyles = { - top: "0px", - left: "0px", - right: "0px", - bottom: "0px", - position: "absolute", - padding: "5px", - zIndex: 100, - color: "white", - display: "none", - overflow: "auto", - fontSize: "14px" - }; - if (!UA.isOldIE) { - settingDivStyles.backgroundColor = "rgba(0, 0, 0, 0.6)"; - } else { - settingDivStyles.backgroundColor = "#333"; - } - - applyStyles(settingDiv, settingDivStyles); - container.appendChild(settingDiv); - - // Power up ace on the textarea: - var options = {}; - - var editor = ace.edit(editorDiv); - session = editor.getSession(); - - session.setValue(element.value || element.innerHTML); - editor.focus(); - - // Add the settingPanel opener to the editor's div. - editorDiv.appendChild(settingOpener); - - // Create the API. - var api = setupApi(editor, editorDiv, settingDiv, ace, options, loader); - - // Create the setting's panel. - setupSettingPanel(settingDiv, settingOpener, api, options); - - return api; -}; - -function load(url, module, callback) { - net.loadScript(url, function() { - require([module], callback); - }); -} - -function setupApi(editor, editorDiv, settingDiv, ace, options, loader) { - var session = editor.getSession(); - var renderer = editor.renderer; - loader = loader || load; - - function toBool(value) { - return value == "true"; - } - - var ret = { - setDisplaySettings: function(display) { - settingDiv.style.display = display ? "block" : "none"; - }, - - setOption: function(key, value) { - if (options[key] == value) return; - - switch (key) { - case "gutter": - renderer.setShowGutter(toBool(value)); - break; - - case "mode": - if (value != "text") { - // Load the required mode file. Files get loaded only once. - loader("mode-" + value + ".js", "ace/mode/" + value, function() { - var aceMode = require("../mode/" + value).Mode; - session.setMode(new aceMode()); - }); - } else { - session.setMode(new (require("../mode/text").Mode)); - } - break; - - case "theme": - if (value != "textmate") { - // Load the required theme file. Files get loaded only once. - loader("theme-" + value + ".js", "ace/theme/" + value, function() { - editor.setTheme("ace/theme/" + value); - }); - } else { - editor.setTheme("ace/theme/textmate"); - } - break; - - case "fontSize": - editorDiv.style.fontSize = value; - break; - - case "softWrap": - switch (value) { - case "off": - session.setUseWrapMode(false); - renderer.setPrintMarginColumn(80); - break; - case "40": - session.setUseWrapMode(true); - session.setWrapLimitRange(40, 40); - renderer.setPrintMarginColumn(40); - break; - case "80": - session.setUseWrapMode(true); - session.setWrapLimitRange(80, 80); - renderer.setPrintMarginColumn(80); - break; - case "free": - session.setUseWrapMode(true); - session.setWrapLimitRange(null, null); - renderer.setPrintMarginColumn(80); - break; - } - break; - - case "useSoftTabs": - session.setUseSoftTabs(toBool(value)); - break; - - case "showPrintMargin": - renderer.setShowPrintMargin(toBool(value)); - break; - - case "showInvisibles": - editor.setShowInvisibles(toBool(value)); - break; - } - - options[key] = value; - }, - - getOption: function(key) { - return options[key]; - }, - - getOptions: function() { - return options; - } - }; - - for (var option in exports.options) { - ret.setOption(option, exports.options[option]); - } - - return ret; -} - -function setupSettingPanel(settingDiv, settingOpener, api, options) { - var BOOL = { - "true": true, - "false": false - }; - - var desc = { - mode: "Mode:", - gutter: "Display Gutter:", - theme: "Theme:", - fontSize: "Font Size:", - softWrap: "Soft Wrap:", - showPrintMargin: "Show Print Margin:", - useSoftTabs: "Use Soft Tabs:", - showInvisibles: "Show Invisibles" - }; - - var optionValues = { - mode: { - text: "Plain", - javascript: "JavaScript", - xml: "XML", - html: "HTML", - css: "CSS", - scss: "SCSS", - python: "Python", - php: "PHP", - java: "Java", - ruby: "Ruby", - c_cpp: "C/C++", - coffee: "CoffeeScript", - json: "json", - perl: "Perl", - clojure: "Clojure", - ocaml: "OCaml", - csharp: "C#", - haxe: "haXe", - svg: "SVG", - textile: "Textile", - groovy: "Groovy", - liquid: "Liquid", - Scala: "Scala" - }, - theme: { - clouds: "Clouds", - clouds_midnight: "Clouds Midnight", - cobalt: "Cobalt", - crimson_editor: "Crimson Editor", - dawn: "Dawn", - eclipse: "Eclipse", - idle_fingers: "Idle Fingers", - kr_theme: "Kr Theme", - merbivore: "Merbivore", - merbivore_soft: "Merbivore Soft", - mono_industrial: "Mono Industrial", - monokai: "Monokai", - pastel_on_dark: "Pastel On Dark", - solarized_dark: "Solarized Dark", - solarized_light: "Solarized Light", - textmate: "Textmate", - twilight: "Twilight", - vibrant_ink: "Vibrant Ink" - }, - gutter: BOOL, - fontSize: { - "10px": "10px", - "11px": "11px", - "12px": "12px", - "14px": "14px", - "16px": "16px" - }, - softWrap: { - off: "Off", - 40: "40", - 80: "80", - free: "Free" - }, - showPrintMargin: BOOL, - useSoftTabs: BOOL, - showInvisibles: BOOL - }; - - var table = []; - table.push("
"); - - function renderOption(builder, option, obj, cValue) { - builder.push(""); - } - - for (var option in options) { - table.push(""); - table.push(""); - } - table.push("
SettingValue
", desc[option], ""); - renderOption(table, option, optionValues[option], options[option]); - table.push("
"); - settingDiv.innerHTML = table.join(""); - - var selects = settingDiv.getElementsByTagName("select"); - for (var i = 0; i < selects.length; i++) { - var onChange = (function() { - var select = selects[i]; - return function() { - var option = select.title; - var value = select.value; - api.setOption(option, value); - }; - })(); - selects[i].onchange = onChange; - } - - var button = document.createElement("input"); - button.type = "button"; - button.value = "Hide"; - button.onclick = function() { - api.setDisplaySettings(false); - }; - settingDiv.appendChild(button); - - settingOpener.onclick = function() { - api.setDisplaySettings(true); - }; -} - -// Default startup options. -exports.options = { - mode: "text", - theme: "textmate", - gutter: "false", - fontSize: "12px", - softWrap: "off", - showPrintMargin: "false", - useSoftTabs: "true", - showInvisibles: "true" -}; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/hash_handler.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/hash_handler.js deleted file mode 100644 index 9a8f289..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/hash_handler.js +++ /dev/null @@ -1,167 +0,0 @@ -/* ***** 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): - * Fabian Jakobs - * Julian Viereck (julian.viereck@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(function(require, exports, module) { -"use strict"; - -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.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.bindKey = function(key, command) { - if(!key) - return; - - var ckb = this.commmandKeyBinding; - key.split("|").forEach(function(keyPart) { - var binding = parseKeys(keyPart, command); - var hashId = binding.hashId; - (ckb[hashId] || (ckb[hashId] = {}))[binding.key] = command; - }); - }; - - 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); - }; - - function parseKeys(keys, val, ret) { - var key; - var hashId = 0; - var parts = splitSafe(keys.toLowerCase()); - - 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 '-' - } - - return { - key: key, - hashId: hashId - }; - } - - function splitSafe(s) { - return (s.trim() - .split(new RegExp("[\\s ]*\\-[\\s ]*", "g"), 999)); - } - - 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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/keybinding.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/keybinding.js deleted file mode 100644 index 6e6656d..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/keybinding.js +++ /dev/null @@ -1,128 +0,0 @@ -/* ***** 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 - * Julian Viereck - * Harutyun Amirjanyan - * - * 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(function(require, exports, module) { -"use strict"; - -var keyUtil = require("../lib/keys"); -var event = require("../lib/event"); -require("../commands/default_commands"); - -var KeyBinding = function(editor) { - this.$editor = editor; - this.$data = { }; - this.$handlers = [this]; -}; - -(function() { - this.setKeyboardHandler = function(keyboardHandler) { - if (this.$handlers[this.$handlers.length - 1] == keyboardHandler) - return; - this.$data = { }; - this.$handlers = keyboardHandler ? [this, keyboardHandler] : [this]; - }; - - this.addKeyboardHandler = function(keyboardHandler) { - this.removeKeyboardHandler(keyboardHandler); - this.$handlers.push(keyboardHandler); - }; - - this.removeKeyboardHandler = function(keyboardHandler) { - var i = this.$handlers.indexOf(keyboardHandler); - if (i == -1) - return false; - this.$handlers.splice(i, 1); - 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); - else - success = true; - - if (success && e) - event.stopEvent(e); - - return success; - }; - - this.handleKeyboard = function(data, hashId, keyString) { - return { - command: this.$editor.commands.findKeyCommand(hashId, keyString) - }; - }; - - this.onCommandKey = function(e, hashId, keyCode) { - var keyString = keyUtil.keyCodeToString(keyCode); - this.$callKeyboardHandlers(hashId, keyString, keyCode, e); - }; - - this.onTextInput = function(text, pasted) { - var success = false; - if (!pasted && text.length == 1) - success = this.$callKeyboardHandlers(0, text); - if (!success) - this.$editor.commands.exec("insertstring", this.$editor, text); - }; - -}).call(KeyBinding.prototype); - -exports.KeyBinding = KeyBinding; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/keybinding/emacs.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/keybinding/emacs.js deleted file mode 100644 index 1c4619f..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/keybinding/emacs.js +++ /dev/null @@ -1,150 +0,0 @@ -/* ***** 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) - * - * 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(function(require, exports, module) { -"use strict"; - -var StateHandler = require("../state_handler").StateHandler; -var matchCharacterOnly = require("../state_handler").matchCharacterOnly; - -var emacsState = { - start: [ - { - key: "ctrl-x", - then: "c-x" - }, - { - regex: [ "(?:command-([0-9]*))*", "(down|ctrl-n)" ], - exec: "golinedown", - params: [ - { - name: "times", - match: 1, - type: "number", - defaultValue: 1 - } - ] - }, - { - regex: [ "(?:command-([0-9]*))*", "(right|ctrl-f)" ], - exec: "gotoright", - params: [ - { - name: "times", - match: 1, - type: "number", - defaultValue: 1 - } - ] - }, - { - regex: [ "(?:command-([0-9]*))*", "(up|ctrl-p)" ], - exec: "golineup", - params: [ - { - name: "times", - match: 1, - type: "number", - defaultValue: 1 - } - ] - }, - { - regex: [ "(?:command-([0-9]*))*", "(left|ctrl-b)" ], - exec: "gotoleft", - params: [ - { - name: "times", - match: 1, - type: "number", - defaultValue: 1 - } - ] - }, - { - comment: "This binding matches all printable characters except numbers as long as they are no numbers and print them n times.", - regex: [ "(?:command-([0-9]*))", "([^0-9]+)*" ], - match: matchCharacterOnly, - exec: "inserttext", - params: [ - { - name: "times", - match: 1, - type: "number", - defaultValue: "1" - }, - { - name: "text", - match: 2 - } - ] - }, - { - comment: "This binding matches numbers as long as there is no meta_number in the buffer.", - regex: [ "(command-[0-9]*)*", "([0-9]+)" ], - match: matchCharacterOnly, - disallowMatches: [ 1 ], - exec: "inserttext", - params: [ - { - name: "text", - match: 2, - type: "text" - } - ] - }, - { - regex: [ "command-([0-9]*)", "(command-[0-9]|[0-9])" ], - comment: "Stops execution if the regex /meta_[0-9]+/ matches to avoid resetting the buffer." - } - ], - "c-x": [ - { - key: "ctrl-g", - then: "start" - }, - { - key: "ctrl-s", - exec: "save", - then: "start" - } - ] -}; - -exports.Emacs = new StateHandler(emacsState); - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/keybinding/vim.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/keybinding/vim.js deleted file mode 100644 index 6cc5d91..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/keybinding/vim.js +++ /dev/null @@ -1,138 +0,0 @@ -/* ***** 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) - * - * 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(function(require, exports, module) { -"use strict"; - -var StateHandler = require("../state_handler").StateHandler; -var matchCharacterOnly = require("../state_handler").matchCharacterOnly; - -var vimcommand = function(key, exec, then) { - return { - regex: [ "([0-9]*)", key ], - exec: exec, - params: [ - { - name: "times", - match: 1, - type: "number", - defaultValue: 1 - } - ], - then: then - } -} - -var vimStates = { - start: [ - { - key: "i", - then: "insertMode" - }, - { - key: "d", - then: "deleteMode" - }, - { - key: "a", - exec: "gotoright", - then: "insertMode" - }, - { - key: "shift-i", - exec: "gotolinestart", - then: "insertMode" - }, - { - key: "shift-a", - exec: "gotolineend", - then: "insertMode" - }, - { - key: "shift-c", - exec: "removetolineend", - then: "insertMode" - }, - { - key: "shift-r", - exec: "overwrite", - then: "replaceMode" - }, - vimcommand("(k|up)", "golineup"), - vimcommand("(j|down)", "golinedown"), - vimcommand("(l|right)", "gotoright"), - vimcommand("(h|left)", "gotoleft"), - { - key: "shift-g", - exec: "gotoend" - }, - vimcommand("b", "gotowordleft"), - vimcommand("e", "gotowordright"), - vimcommand("x", "del"), - vimcommand("shift-x", "backspace"), - vimcommand("shift-d", "removetolineend"), - vimcommand("u", "undo"), // [count] on this may/may not work, depending on browser implementation... - { - comment: "Catch some keyboard input to stop it here", - match: matchCharacterOnly - } - ], - insertMode: [ - { - key: "esc", - then: "start" - } - ], - replaceMode: [ - { - key: "esc", - exec: "overwrite", - then: "start" - } - ], - deleteMode: [ - { - key: "d", - exec: "removeline", - then: "start" - } - ] -}; - -exports.Vim = new StateHandler(vimStates); - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/state_handler.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/state_handler.js deleted file mode 100644 index 541fa1c..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/state_handler.js +++ /dev/null @@ -1,255 +0,0 @@ -/* ***** 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) - * - * 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(function(require, exports, module) { -"use strict"; - -// 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 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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/textinput.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/textinput.js deleted file mode 100644 index bb917f5..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/keyboard/textinput.js +++ /dev/null @@ -1,278 +0,0 @@ -/* 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 - * Mihai Sucan - * - * 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(function(require, exports, module) { -"use strict"; - -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.style.left = "-10000px"; - text.style.position = "fixed"; - parentNode.insertBefore(text, parentNode.firstChild); - - var PLACEHOLDER = String.fromCharCode(0); - sendText(); - - var inCompostion = false; - var copied = false; - var pasted = false; - var tempStyle = ''; - - function select() { - try { - text.select(); - } catch (e) {} - } - - function sendText(valueToSend) { - if (!copied) { - var value = valueToSend || text.value; - if (value) { - if (value.charCodeAt(value.length-1) == PLACEHOLDER.charCodeAt(0)) { - value = value.slice(0, -1); - if (value) - host.onTextInput(value, pasted); - } - else { - host.onTextInput(value, pasted); - } - - // If editor is no longer focused we quit immediately, since - // it means that something else is in charge now. - if (!isFocused()) - return false; - } - } - - copied = false; - pasted = false; - - // Safari doesn't fire copy events if no text is selected - text.value = PLACEHOLDER; - select(); - } - - var onTextInput = function(e) { - setTimeout(function () { - if (!inCompostion) - sendText(e.data); - }, 0); - }; - - var onPropertyChange = function(e) { - if (useragent.isOldIE && text.value.charCodeAt(0) > 128) return; - setTimeout(function() { - if (!inCompostion) - sendText(); - }, 0); - }; - - var onCompositionStart = function(e) { - inCompostion = true; - host.onCompositionStart(); - if (!useragent.isGecko) 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(); - select(); - setTimeout(function () { - sendText(); - }, 0); - }; - - var onCut = function(e) { - copied = true; - var copyText = host.getCopyText(); - if(copyText) { - text.value = copyText; - host.onCut(); - } else - e.preventDefault(); - select(); - setTimeout(function () { - sendText(); - }, 0); - }; - - event.addCommandKeyListener(text, host.onCommandKey.bind(host)); - if (useragent.isOldIE) { - var keytable = { 13:1, 27:1 }; - event.addListener(text, "keyup", function (e) { - if (inCompostion && (!text.value || keytable[e.keyCode])) - setTimeout(onCompositionEnd, 0); - if ((text.value.charCodeAt(0)|0) < 129) { - return; - } - inCompostion ? onCompositionUpdate() : onCompositionStart(); - }); - } - - if ("onpropertychange" in text && !("oninput" in text)) - event.addListener(text, "propertychange", onPropertyChange); - else - event.addListener(text, "input", 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) { - 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); - } - }); - } - 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(); - select(); - }); - - this.focus = function() { - host.onFocus(); - select(); - text.focus(); - }; - - this.blur = function() { - text.blur(); - }; - - function isFocused() { - return document.activeElement === text; - } - this.isFocused = isFocused; - - this.getElement = function() { - return text; - }; - - this.onContextMenu = function(mousePos, isEmpty){ - if (mousePos) { - if (!tempStyle) - tempStyle = text.style.cssText; - - text.style.cssText = - 'position:fixed; z-index:1000;' + - 'left:' + (mousePos.x - 2) + 'px; top:' + (mousePos.y - 2) + 'px;'; - - } - if (isEmpty) - text.value=''; - }; - - this.onContextMenuClose = function(){ - setTimeout(function () { - if (tempStyle) { - text.style.cssText = tempStyle; - tempStyle = ''; - } - sendText(); - }, 0); - }; -}; - -exports.TextInput = TextInput; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/cursor.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/cursor.js deleted file mode 100644 index 1c55d7a..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/cursor.js +++ /dev/null @@ -1,199 +0,0 @@ -/* 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 - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -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); - - 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; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/gutter.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/gutter.js deleted file mode 100644 index e700dc7..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/gutter.js +++ /dev/null @@ -1,187 +0,0 @@ -/* 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 - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -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.setBreakpoints = function(rows) { - this.$breakpoints = rows.concat(); - }; - - 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 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("
", (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( - "" - ); - } - - var wrappedRowLength = this.session.getRowLength(i) - 1; - while (wrappedRowLength--) { - html.push("
\xA6"); - } - - html.push("
"); - - i++; - } - 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; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/marker.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/marker.js deleted file mode 100644 index 741a271..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/marker.js +++ /dev/null @@ -1,219 +0,0 @@ -/* 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 - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -var Range = require("../range").Range; -var dom = require("../lib/dom"); - -var Marker = function(parentEl) { - this.element = dom.createElement("div"); - this.element.className = "ace_layer ace_marker-layer"; - parentEl.appendChild(this.element); -}; - -(function() { - - this.$padding = 0; - - this.setPadding = function(padding) { - this.$padding = padding; - }; - this.setSession = function(session) { - this.session = session; - }; - - this.setMarkers = function(markers) { - this.markers = markers; - }; - - this.update = function(config) { - var config = config || this.config; - if (!config) - return; - - this.config = config; - - - var html = []; - for ( var key in this.markers) { - var marker = this.markers[key]; - - 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( - "
" - ); - - // 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( - "
" - ); - - // 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( - "
" - ); - }; - - /** - * 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( - "
" - ); - }; - -}).call(Marker.prototype); - -exports.Marker = Marker; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/text.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/text.js deleted file mode 100644 index d4d39bc..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/text.js +++ /dev/null @@ -1,612 +0,0 @@ -/* 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 - * Julian Viereck - * Mihai Sucan - * Irakli Gozalishvili (http://jeditoolkit.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(function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var dom = require("../lib/dom"); -var lang = require("../lib/lang"); -var useragent = require("../lib/useragent"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var Text = function(parentEl) { - this.element = dom.createElement("div"); - this.element.className = "ace_layer ace_text-layer"; - parentEl.appendChild(this.element); - - this.$characterSize = this.$measureSizes() || {width: 0, height: 0}; - this.$pollSizeChanges(); -}; - -(function() { - - oop.implement(this, EventEmitter); - - this.EOF_CHAR = "\xB6"; //"¶"; - this.EOL_CHAR = "\xAC"; //"¬"; - this.TAB_CHAR = "\u2192"; //"→"; - this.SPACE_CHAR = "\xB7"; //"·"; - 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("" - + this.TAB_CHAR - + new Array(i).join(" ") - + ""); - } else { - tabStr.push(new Array(i+1).join(" ")); - } - } - - }; - - 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, i); - this.$renderLine(html, i, tokens[0].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. - // OPTIMIZE: If there is a long block of unfolded lines, just make - // this call once for that big block of unfolded lines. - var tokens = this.session.getTokens(row, row); - if (tokens.length == 1) - this.$renderLine(html, row, tokens[0].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("
") - - // Get the tokens per line as there might be some lines in between - // beeing folded. - // OPTIMIZE: If there is a long block of unfolded lines, just make - // this call once for that big block of unfolded lines. - var tokens = this.session.getTokens(row, row); - if (tokens.length == 1) - this.$renderLine(html, row, tokens[0].tokens, false); - - if (this.$useLineGroups()) - html.push("
"); // 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|&|<|( +)|([\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000])|[\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 (c.charCodeAt(0) == 32) { - return new Array(c.length+1).join(" "); - } else if (c == "\t") { - var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx); - screenColumn += tabSize - 1; - return self.$tabStrings[tabSize]; - } else if (c == "&") { - if (useragent.isOldGecko) - return "&"; - else - return "&"; - } else if (c == "<") { - return "<"; - } 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 "" + space + ""; - } else if (c.match(/[\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]/)) { - if (self.showInvisibles) { - var space = new Array(c.length+1).join(self.SPACE_CHAR); - return "" + space + ""; - } else { - return " "; - } - } else { - screenColumn += 1; - return "" + c + ""; - } - }; - - var output = value.replace(replaceReg, replaceFunc); - - if (!this.$textToken[token.type]) { - var classes = "ace_" + token.type.replace(/\./g, " ace_"); - var style = ""; - if (token.type == "fold") - style = " style='width:" + (token.value.length * this.config.characterWidth) + "px;' "; - stringBuilder.push("", output, ""); - } - else { - stringBuilder.push(output); - } - return screenColumn + value.length; - }; - - this.$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("
" - ); - } - - 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("
", - "
" - ); - } - - 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("" + this.EOL_CHAR + ""); - else - stringBuilder.push("" + this.EOF_CHAR + ""); - } - if (!onlyContents) - stringBuilder.push("
"); - }; - - 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, row)[0].tokens; - } - if (tokens.length != 0) { - 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; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/text_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/text_test.js deleted file mode 100644 index ef7d8cb..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/layer/text_test.js +++ /dev/null @@ -1,106 +0,0 @@ -/* ***** 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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); - require("../test/mockdom"); -} - -define(function(require, exports, module) { -"use strict"; - -var assert = require("../test/assertions"); -var EditSession = require("../edit_session").EditSession; -var TextLayer = require("./text").Text; -var JavaScriptMode = require("../mode/javascript").Mode; - -module.exports = { - - setUp: function(next) { - this.session = new EditSession(""); - this.session.setMode(new JavaScriptMode()); - this.textLayer = new TextLayer(document.createElement("div")); - this.textLayer.setSession(this.session); - this.textLayer.config = { - characterWidth: 10, - lineHeight: 20 - }; - next() - }, - - "test: render line with hard tabs should render the same as lines with soft tabs" : function() { - this.session.setValue("a\ta\ta\t\na a a \n"); - this.textLayer.$computeTabString(); - - // row with hard tabs - var row = 0; - var tokens = this.session.getTokens(row, row)[0].tokens; - var stringBuilder = []; - this.textLayer.$renderLine(stringBuilder, row, tokens); - - // row with soft tabs - row = 1; - tokens = this.session.getTokens(row, row)[0].tokens; - var stringBuilder2 = []; - this.textLayer.$renderLine(stringBuilder2, row, tokens); - assert.equal(stringBuilder.join(""), stringBuilder2.join("")); - }, - - "test rendering width of ideographic space (U+3000)" : function() { - this.session.setValue("\u3000"); - - var tokens = this.session.getTokens(0, 0)[0].tokens; - var stringBuilder = []; - this.textLayer.$renderLine(stringBuilder, 0, tokens, true); - assert.equal(stringBuilder.join(""), ""); - - this.textLayer.setShowInvisibles(true); - var stringBuilder = []; - this.textLayer.$renderLine(stringBuilder, 0, tokens, true); - assert.equal( - stringBuilder.join(""), - "" + this.textLayer.SPACE_CHAR + "" - + "\xB6" - ); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec() -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/browser_focus.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/browser_focus.js deleted file mode 100644 index fdc4e6f..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/browser_focus.js +++ /dev/null @@ -1,105 +0,0 @@ -/* 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 - * Irakli Gozalishvili (http://jeditoolkit.com) - * Julian Viereck - * - * 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(function(require, exports, module) { -"use strict"; - -var oop = require("./oop"); -var event = require("./event"); -var EventEmitter = require("./event_emitter").EventEmitter; - -/** - * This class keeps track of the focus state of the given window. - * Focus changes for example when the user switches a browser tab, - * goes to the location bar or switches to another application. - */ -var BrowserFocus = function(win) { - win = win || window; - - this.lastFocus = new Date().getTime(); - this._isFocused = true; - - var _self = this; - - // IE < 9 supports focusin and focusout events - if ("onfocusin" in win.document) { - event.addListener(win.document, "focusin", function(e) { - _self._setFocused(true); - }); - - event.addListener(win.document, "focusout", function(e) { - _self._setFocused(!!e.toElement); - }); - } - else { - event.addListener(win, "blur", function(e) { - _self._setFocused(false); - }); - - event.addListener(win, "focus", function(e) { - _self._setFocused(true); - }); - } -}; - -(function(){ - - oop.implement(this, EventEmitter); - - this.isFocused = function() { - return this._isFocused; - }; - - this._setFocused = function(isFocused) { - if (this._isFocused == isFocused) - return; - - if (isFocused) - this.lastFocus = new Date().getTime(); - - this._isFocused = isFocused; - this._emit("changeFocus"); - }; - -}).call(BrowserFocus.prototype); - - -exports.BrowserFocus = BrowserFocus; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/dom.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/dom.js deleted file mode 100644 index 6710606..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/dom.js +++ /dev/null @@ -1,292 +0,0 @@ -/* 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 - * Mihai Sucan - * Irakli Gozalishvili (http://jeditoolkit.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(function(require, exports, module) { -"use strict"; - -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; -}; - -/** -* Add a CSS class to the list of classes on the given node -*/ -exports.addCssClass = function(el, name) { - if (!exports.hasCssClass(el, name)) { - el.className += " " + name; - } -}; - -/** -* Remove a CSS class from the list of classes on the given node -*/ -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; -}; - -/** - * Add or remove a CSS class from the list of classes on the given node - * depending on the value of include - */ -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; -}; - -/** - * Optimized set innerHTML. This is faster than plain innerHTML if the element - * already contains a lot of child elements. - * - * See http://blog.stevenlevithan.com/archives/faster-than-innerhtml for details - */ -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; -}; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/es5-shim.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/es5-shim.js deleted file mode 100644 index 7164a3f..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/es5-shim.js +++ /dev/null @@ -1,1059 +0,0 @@ -// 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(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 -// 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); - }; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/event.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/event.js deleted file mode 100644 index 9a9d4e4..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/event.js +++ /dev/null @@ -1,324 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -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); - } -}; - -/** -* Prevents propagation and clobbers the default action of the passed event -*/ -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.getDocumentX = function(e) { - if (e.clientX) { - return e.clientX + dom.getPageScrollLeft(); - } else { - return e.pageX; - } -}; - -exports.getDocumentY = function(e) { - if (e.clientY) { - return e.clientY + dom.getPageScrollTop(); - } else { - return e.pageY; - } -}; - -/** - * @return {Number} 0 for left button, 1 for middle button, 2 for right button - */ -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, button, count, timeout, callback) { - var clicks = 0; - var startX, startY; - - var listener = function(e) { - clicks += 1; - if (clicks == 1) { - startX = e.clientX; - startY = e.clientY; - - setTimeout(function() { - clicks = 0; - }, timeout || 600); - } - - var isButton = exports.getButton(e) == button; - if (!isButton || Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5) - clicks = 0; - - if (clicks == count) { - clicks = 0; - callback(e); - } - - if (isButton) - return exports.preventDefault(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); - }; -} - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/event_emitter.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/event_emitter.js deleted file mode 100644 index b6ed91d..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/event_emitter.js +++ /dev/null @@ -1,121 +0,0 @@ -/* 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 - * Irakli Gozalishvili (http://jeditoolkit.com) - * Mike de Boer - * - * 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(function(require, exports, module) { -"use strict"; - -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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); -} - -define(function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("./event_emitter").EventEmitter; -var assert = require("../test/assertions"); - -var Emitter = function() {}; - -oop.implement(Emitter.prototype, EventEmitter); - -module.exports = { - "test: dispatch event with no data" : function() { - var emitter = new Emitter(); - - var called = false; - emitter.addEventListener("juhu", function(e) { - called = true; - assert.equal(e.type, "juhu"); - }); - - emitter._emit("juhu"); - assert.ok(called); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec() -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/fixoldbrowsers.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/fixoldbrowsers.js deleted file mode 100644 index 2da9b10..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/fixoldbrowsers.js +++ /dev/null @@ -1,19 +0,0 @@ -// 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(function(require, exports, module) { -"use strict"; - -require("./regexp"); -require("./es5-shim"); - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/keys.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/keys.js deleted file mode 100644 index 516c1f9..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/keys.js +++ /dev/null @@ -1,129 +0,0 @@ -/*! @license -========================================================================== -SproutCore -- JavaScript Application Framework -copyright 2006-2009, Sprout Systems Inc., Apple Inc. and contributors. - -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. - -SproutCore and the SproutCore logo are trademarks of Sprout Systems, Inc. - -For more information about SproutCore, visit http://www.sproutcore.com - - -========================================================================== -@license */ - -// Most of the following code is taken from SproutCore with a few changes. - -define(function(require, exports, module) { -"use strict"; - -var oop = require("./oop"); - -/** - * Helper functions and hashes for key handling. - */ -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(); -} - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/lang.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/lang.js deleted file mode 100644 index 2d1b4f9..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/lang.js +++ /dev/null @@ -1,150 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -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 - * - * 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(function(require, exports, module) { -"use strict"; - -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); -}; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/regexp.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/regexp.js deleted file mode 100644 index c3b9f5b..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/regexp.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Based on code from: - * - * XRegExp 1.5.0 - * (c) 2007-2010 Steven Levithan - * MIT License - * - * Provides an augmented, extensible, cross-browser implementation of regular expressions, - * including support for additional syntax, flags, and methods - */ - -define(function(require, exports, module) { -"use strict"; - - //--------------------------------- - // 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; - }(); - - //--------------------------------- - // 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; - }; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/useragent.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/useragent.js deleted file mode 100644 index 8b5a057..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/lib/useragent.js +++ /dev/null @@ -1,105 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -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; - -/** - * I hate doing this, but we need some way to determine if the user is on a Mac - * The reason is that users have different expectations of their key combinations. - * - * Take copy as an example, Mac people expect to use CMD or APPLE + C - * Windows folks expect to use CTRL + C - */ -exports.OS = { - LINUX: "LINUX", - MAC: "MAC", - WINDOWS: "WINDOWS" -}; - -/** - * Return an exports.OS constant - */ -exports.getOS = function() { - if (exports.isMac) { - return exports.OS.MAC; - } else if (exports.isLinux) { - return exports.OS.LINUX; - } else { - return exports.OS.WINDOWS; - } -}; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/behaviour.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/behaviour.js deleted file mode 100644 index 0559ff6..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/behaviour.js +++ /dev/null @@ -1,98 +0,0 @@ -/* 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): - * Chris Spencer - * - * 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(function(require, exports, module) { -"use strict"; - -var Behaviour = function() { - this.$behaviours = {}; -}; - -(function () { - - this.add = function (name, action, callback) { - switch (undefined) { - case this.$behaviours: - this.$behaviours = {}; - case this.$behaviours[name]: - this.$behaviours[name] = {}; - } - this.$behaviours[name][action] = callback; - } - - this.addBehaviours = function (behaviours) { - for (var key in behaviours) { - for (var action in behaviours[key]) { - this.add(key, action, behaviours[key][action]); - } - } - } - - this.remove = function (name) { - if (this.$behaviours && this.$behaviours[name]) { - delete this.$behaviours[name]; - } - } - - this.inherit = function (mode, filter) { - if (typeof mode === "function") { - var behaviours = new mode().getBehaviours(filter); - } else { - var behaviours = mode.getBehaviours(filter); - } - this.addBehaviours(behaviours); - } - - this.getBehaviours = function (filter) { - if (!filter) { - return this.$behaviours; - } else { - var ret = {} - for (var i = 0; i < filter.length; i++) { - if (this.$behaviours[filter[i]]) { - ret[filter[i]] = this.$behaviours[filter[i]]; - } - } - return ret; - } - } - -}).call(Behaviour.prototype); - -exports.Behaviour = Behaviour; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/behaviour/cstyle.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/behaviour/cstyle.js deleted file mode 100644 index 3db838a..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/behaviour/cstyle.js +++ /dev/null @@ -1,225 +0,0 @@ -/* 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): - * Chris Spencer - * - * 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(function(require, exports, module) { -"use strict"; - -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, selection.start.row)[0].tokens; - 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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/behaviour/xml.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/behaviour/xml.js deleted file mode 100644 index bdfa9d8..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/behaviour/xml.js +++ /dev/null @@ -1,92 +0,0 @@ -/* 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): - * Chris Spencer - * - * 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(function(require, exports, module) { -"use strict"; - -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 == '. -*/ -define(function(require, exports, module) { -"use strict"; - - 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 == ' 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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/c_cpp.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/c_cpp.js deleted file mode 100644 index ccc1f55..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/c_cpp.js +++ /dev/null @@ -1,132 +0,0 @@ -/* ***** 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 - * Gastón Kleiman - * - * 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(function(require, exports, module) { -"use strict"; - -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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/c_cpp_highlight_rules.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/c_cpp_highlight_rules.js deleted file mode 100644 index 236b728..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/c_cpp_highlight_rules.js +++ /dev/null @@ -1,180 +0,0 @@ -/* ***** 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 - * Gastón Kleiman - * - * Based on Bespin's C/C++ Syntax Plugin by Marc McIntyre. - * - * 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(function(require, exports, module) { -"use strict"; - -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", // - 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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/clojure.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/clojure.js deleted file mode 100644 index 37a0d58..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/clojure.js +++ /dev/null @@ -1,121 +0,0 @@ -/* ***** 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 - * Shlomo Zalman Heigh - * 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(function(require, exports, module) { -"use strict"; - -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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/clojure_highlight_rules.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/clojure_highlight_rules.js deleted file mode 100644 index d5e8ed8..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/clojure_highlight_rules.js +++ /dev/null @@ -1,220 +0,0 @@ -/* ***** 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 - * Shlomo Zalman Heigh - * 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(function(require, exports, module) { -"use strict"; - -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* + - -> -> ->> ->> .. / < < <= <= = ' + - '== > > >= >= 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", // 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 : ".+" - } - ] - }; -}; - -oop.inherits(ClojureHighlightRules, TextHighlightRules); - -exports.ClojureHighlightRules = ClojureHighlightRules; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee.js deleted file mode 100644 index 4afc289..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee.js +++ /dev/null @@ -1,121 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -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; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/coffee-script.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/coffee-script.js deleted file mode 100644 index 63bdcf5..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/coffee-script.js +++ /dev/null @@ -1,63 +0,0 @@ -/* ***** 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 - * - * 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(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)); - }; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/helpers.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/helpers.js deleted file mode 100644 index 7966a49..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/helpers.js +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright (c) 2011 Jeremy Ashkenas - * - * 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. - */ - -define(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]; - }; - - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/lexer.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/lexer.js deleted file mode 100644 index cd9c307..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/lexer.js +++ /dev/null @@ -1,739 +0,0 @@ -/** - * Copyright (c) 2011 Jeremy Ashkenas - * - * 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. - */ - -define(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']; - - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/nodes.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/nodes.js deleted file mode 100644 index 1040940..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/nodes.js +++ /dev/null @@ -1,2756 +0,0 @@ -/** - * Copyright (c) 2011 Jeremy Ashkenas - * - * 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. - */ - -define(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+$/, ''); - }; - - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/parser.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/parser.js deleted file mode 100644 index cf81625..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/parser.js +++ /dev/null @@ -1,603 +0,0 @@ -/** - * Copyright (c) 2011 Jeremy Ashkenas - * - * 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. - */ - -define(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; - - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/parser_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/parser_test.js deleted file mode 100644 index d7f7039..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/parser_test.js +++ /dev/null @@ -1,68 +0,0 @@ -/* ***** 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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); -} - -define(function(require, exports, module) { -"use strict"; - -var assert = require("../../test/assertions"); -var coffee = require("../coffee/coffee-script"); - - -module.exports = { - - "test parse valid coffee script": function() { - coffee.parse("square = (x) -> x * x"); - }, - - "test parse invalid coffee script": function() { - try { - coffee.parse("a = 12 f"); - } catch (e) { - assert.ok((e + "").indexOf("Parse error on line 1: Unexpected 'IDENTIFIER'") >= 0); - } - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec(); -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/rewriter.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/rewriter.js deleted file mode 100644 index 5f1996f..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/rewriter.js +++ /dev/null @@ -1,342 +0,0 @@ -/** - * Copyright (c) 2011 Jeremy Ashkenas - * - * 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. - */ - -define(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']; - - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/scope.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/scope.js deleted file mode 100644 index 69af1d4..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee/scope.js +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Copyright (c) 2011 Jeremy Ashkenas - * - * 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. - */ - -define(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; - - })(); - - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee_highlight_rules.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee_highlight_rules.js deleted file mode 100644 index 2772edf..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee_highlight_rules.js +++ /dev/null @@ -1,227 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - - 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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee_highlight_rules_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee_highlight_rules_test.js deleted file mode 100644 index 0393e65..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee_highlight_rules_test.js +++ /dev/null @@ -1,72 +0,0 @@ -/* ***** 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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); -} - -define(function(require, exports, module) { -"use strict"; - -var Mode = require("./coffee").Mode; -var assert = require("../test/assertions"); - -module.exports = { - setUp : function() { - this.tokenizer = new Mode().getTokenizer(); - }, - - "test: tokenize keyword": function() { - var tokens = this.tokenizer.getLineTokens("for", "start").tokens; - assert.equal(tokens.length, 1); - assert.equal(tokens[0].type, "keyword"); - }, - - // TODO: disable. not yet implemented - "!test tokenize string with interpolation": function() { - var tokens = this.tokenizer.getLineTokens('"#{ 22 / 7 } is a decent approximation of π"', "start").tokens; - console.log(tokens); - assert.equal(tokens.length, 12); - //assert.equal(tokens[0].type, "keyword"); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec(); -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee_worker.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee_worker.js deleted file mode 100644 index 6268f19..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coffee_worker.js +++ /dev/null @@ -1,92 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -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); - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coldfusion.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coldfusion.js deleted file mode 100644 index 8d5d2c0..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coldfusion.js +++ /dev/null @@ -1,71 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coldfusion_highlight_rules.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coldfusion_highlight_rules.js deleted file mode 100644 index 71d792e..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coldfusion_highlight_rules.js +++ /dev/null @@ -1,135 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coldfusion_test.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coldfusion_test.js deleted file mode 100644 index 18323d5..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/coldfusion_test.js +++ /dev/null @@ -1,74 +0,0 @@ -/* ***** 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 - * - * 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 ***** */ - -if (typeof process !== "undefined") { - require("amd-loader"); -} - -define(function(require, exports, module) { -"use strict"; - -var EditSession = require("../edit_session").EditSession; -var Range = require("../range").Range; -var ColdfusionMode = require("./coldfusion").Mode; -var assert = require("../test/assertions"); - -module.exports = { - setUp : function() { - this.mode = new ColdfusionMode(); - }, - - "test: toggle comment lines should not do anything" : function() { - var session = new EditSession([" abc", "cde", "fg"]); - - var range = new Range(0, 3, 1, 1); - var comment = this.mode.toggleCommentLines("start", session, 0, 1); - assert.equal([" abc", "cde", "fg"].join("\n"), session.toString()); - }, - - "test: next line indent should be the same as the current line indent" : function() { - assert.equal(" ", this.mode.getNextLineIndent("start", " abc")); - assert.equal("", this.mode.getNextLineIndent("start", "abc")); - assert.equal("\t", this.mode.getNextLineIndent("start", "\tabc")); - } -}; - -}); - -if (typeof module !== "undefined" && module === require.main) { - require("asyncjs").test.testcase(module.exports).exec() -} diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/csharp.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/csharp.js deleted file mode 100644 index 25586b8..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/csharp.js +++ /dev/null @@ -1,58 +0,0 @@ -define(function(require, exports, module) { -"use strict"; - -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; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/csharp_highlight_rules.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/csharp_highlight_rules.js deleted file mode 100644 index bbb5369..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/csharp_highlight_rules.js +++ /dev/null @@ -1,104 +0,0 @@ -define(function(require, exports, module) { -"use strict"; - -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 : "\\/\\/.*$" - }, - new 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-", - [ new DocCommentHighlightRules().getEndRule("start") ]); -}; - -oop.inherits(CSharpHighlightRules, TextHighlightRules); - -exports.CSharpHighlightRules = CSharpHighlightRules; -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/css.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/css.js deleted file mode 100644 index 2122ae9..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/css.js +++ /dev/null @@ -1,110 +0,0 @@ -/* ***** 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 - * - * 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(function(require, exports, module) { -"use strict"; - -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; - -}); diff --git a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/css/csslint.js b/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/css/csslint.js deleted file mode 100644 index a5973d3..0000000 --- a/extension/sandbox/chrome-extensions-samples/apps/samples/text-editor/lib/ace/mode/css/csslint.js +++ /dev/null @@ -1,9014 +0,0 @@ -define(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; - } - } - - - } - } -}; -/** - * Convenient way to read through strings. - * @namespace parserlib.util - * @class StringReader - * @constructor - * @param {String} text The text to read. - */ -function StringReader(text){ - - /** - * The input text with line endings normalized. - * @property _input - * @type String - * @private - */ - this._input = text.replace(/\n\r?/g, "\n"); - - - /** - * The row for the character to be read next. - * @property _line - * @type int - * @private - */ - this._line = 1; - - - /** - * The column for the character to be read next. - * @property _col - * @type int - * @private - */ - this._col = 1; - - /** - * The index of the character in the input to be read next. - * @property _cursor - * @type int - * @private - */ - 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; - - /* - * First, buffer must be the same length as the pattern. - * Then, buffer must end with the pattern or else reach the - * end of the input. - */ - 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; - } - -}; -/** - * Type to use when a syntax error occurs. - * @class SyntaxError - * @namespace parserlib.util - * @constructor - * @param {String} message The error message. - * @param {int} line The line at which the error occurred. - * @param {int} col The column at which the error occurred. - */ -function SyntaxError(message, line, col){ - - /** - * The column at which the error occurred. - * @type int - * @property col - */ - this.col = col; - - /** - * The line at which the error occurred. - * @type int - * @property line - */ - this.line = line; - - /** - * The text representation of the unit. - * @type String - * @property text - */ - this.message = message; - -} - -//inherit from Error -SyntaxError.prototype = new Error(); -/** - * Base type to represent a single syntactic unit. - * @class SyntaxUnit - * @namespace parserlib.util - * @constructor - * @param {String} text The text 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 SyntaxUnit(text, line, col, type){ - - - /** - * The column of text on which the unit resides. - * @type int - * @property col - */ - this.col = col; - - /** - * The line of text on which the unit resides. - * @type int - * @property line - */ - this.line = line; - - /** - * The text representation of the unit. - * @type String - * @property text - */ - this.text = text; - - /** - * The type of syntax unit. - * @type int - * @property type - */ - 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; - } - -}; -/*global StringReader, SyntaxError*/ - -/** - * 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; - - /** - * Token object for the last consumed token. - * @type Token - * @property _token - * @private - */ - this._token = null; - - /** - * The array of token information. - * @type Array - * @property _tokenData - * @private - */ - this._tokenData = tokenData; - - /** - * Lookahead token buffer. - * @type Array - * @property _lt - * @private - */ - this._lt = []; - - /** - * Lookahead token buffer index. - * @type int - * @property _ltIndex - * @private - */ - 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 -}; -})(); - - -/* -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 */ -(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" -}; -/*global SyntaxUnit, Parser*/ -/** - * 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); - - /** - * The type of modifier. - * @type String - * @property 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; - - -/*global SyntaxUnit, Parser*/ -/** - * 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); - - /** - * The name of the media feature - * @type String - * @property name - */ - this.name = name; - - /** - * The value for the feature or null if there is none. - * @type SyntaxUnit - * @property value - */ - this.value = value; -} - -MediaFeature.prototype = new SyntaxUnit(); -MediaFeature.prototype.constructor = MediaFeature; - - -/*global SyntaxUnit, Parser*/ -/** - * 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); - - /** - * The media modifier ("not" or "only") - * @type String - * @property modifier - */ - this.modifier = modifier; - - /** - * The mediaType (i.e., "print") - * @type String - * @property mediaType - */ - this.mediaType = mediaType; - - /** - * The parts that make up the selector. - * @type Array - * @property features - */ - this.features = features; - -} - -MediaQuery.prototype = new SyntaxUnit(); -MediaQuery.prototype.constructor = MediaQuery; - - -/*global Tokens, TokenStream, SyntaxError, Properties, Validation, ValidationError, SyntaxUnit, - PropertyValue, PropertyValuePart, SelectorPart, SelectorSubPart, Selector, - PropertyName, Combinator, MediaFeature, MediaQuery, EventTarget */ - -/** - * 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]); - /*if (!tokenStream.match(Tokens.STRING)){ - tokenStream.mustMatch(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; - - - /* - * Error Recovery: If even a single selector fails to parse, - * then the entire ruleset should be thrown away. - */ - 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; -}(); - - -/* -nth - : S* [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]? | - ['-'|'+']? INTEGER | {O}{D}{D} | {E}{V}{E}{N} ] S* - ; -*/ -/*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 | | ", - "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: "