"+b;a.removeChild(a.firstChild);bb(this,a.childNodes);this.remove()}else bb(this,b)}function cb(b){return b.cloneNode(!0)}function sa(b){sb(b);for(var a=0,b=b.childNodes||[];a-1}function vb(b,a){a&&m(a.split(" "),function(a){b.className=
+R((" "+b.className+" ").replace(/[\n\t]/g," ").replace(" "+R(a)+" "," "))})}function wb(b,a){a&&m(a.split(" "),function(a){if(!Ca(b,a))b.className=R(b.className+" "+R(a))})}function bb(b,a){if(a)for(var a=!a.nodeName&&v(a.length)&&!oa(a)?a:[a],c=0;c4096&&c.warn("Cookie '"+a+"' possibly not set or overflowed because it was too large ("+d+" > 4096 bytes)!"),W.length>20&&c.warn("Cookie '"+a+"' possibly not set or overflowed because too many cookies were already set ("+W.length+
+" > 20 )")}else{if(h.cookie!==y){y=h.cookie;d=y.split("; ");W={};for(f=0;f0&&(W[unescape(e.substring(0,k))]=unescape(e.substring(k+1)))}return W}};f.defer=function(a,b){var c;n++;c=l(function(){delete r[c];e(a)},b||0);r[c]=!0;return c};f.defer.cancel=function(a){return r[a]?(delete r[a],o(a),e(D),!0):!1}}function wc(){this.$get=["$window","$log","$sniffer","$document",function(b,a,c,d){return new vc(b,d,a,c)}]}function xc(){this.$get=function(){function b(b,
+d){function e(a){if(a!=l){if(o){if(o==a)o=a.n}else o=a;g(a.n,a.p);g(a,l);l=a;l.n=null}}function g(a,b){if(a!=b){if(a)a.p=b;if(b)b.n=a}}if(b in a)throw B("cacheId "+b+" taken");var i=0,f=x({},d,{id:b}),h={},k=d&&d.capacity||Number.MAX_VALUE,j={},l=null,o=null;return a[b]={put:function(a,b){var c=j[a]||(j[a]={key:a});e(c);t(b)||(a in h||i++,h[a]=b,i>k&&this.remove(o.key))},get:function(a){var b=j[a];if(b)return e(b),h[a]},remove:function(a){var b=j[a];if(b){if(b==l)l=b.p;if(b==o)o=b.n;g(b.n,b.p);delete j[a];
+delete h[a];i--}},removeAll:function(){h={};i=0;j={};l=o=null},destroy:function(){j=f=h=null;delete a[b]},info:function(){return x({},f,{size:i})}}}var a={};b.info=function(){var b={};m(a,function(a,e){b[e]=a.info()});return b};b.get=function(b){return a[b]};return b}}function yc(){this.$get=["$cacheFactory",function(b){return b("templates")}]}function Bb(b){var a={},c="Directive",d=/^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,e=/(([\d\w\-_]+)(?:\:([^;]+))?;?)/,g="Template must have exactly one root element. was: ";
+this.directive=function f(d,e){F(d)?(qa(e,"directive"),a.hasOwnProperty(d)||(a[d]=[],b.factory(d+c,["$injector","$exceptionHandler",function(b,c){var e=[];m(a[d],function(a){try{var f=b.invoke(a);if(N(f))f={compile:I(f)};else if(!f.compile&&f.link)f.compile=I(f.link);f.priority=f.priority||0;f.name=f.name||d;f.require=f.require||f.controller&&f.name;f.restrict=f.restrict||"A";e.push(f)}catch(k){c(k)}});return e}])),a[d].push(e)):m(d,mb(f));return this};this.$get=["$injector","$interpolate","$exceptionHandler",
+"$http","$templateCache","$parse","$controller","$rootScope",function(b,h,k,j,l,o,r,n){function w(a,b,c){a instanceof u||(a=u(a));m(a,function(b,c){b.nodeType==3&&(a[c]=u(b).wrap("").parent()[0])});var d=s(a,b,a,c);return function(b,c){qa(b,"scope");var e=c?ua.clone.call(a):a;e.data("$scope",b);q(e,"ng-scope");c&&c(e,b);d&&d(b,e,e);return e}}function q(a,b){try{a.addClass(b)}catch(c){}}function s(a,b,c,d){function e(a,c,d,k){for(var g,h,j,n,o,l=0,r=0,q=f.length;lz.priority)break;if(Y=z.scope)M("isolated scope",C,z,y),L(Y)&&(q(y,"ng-isolate-scope"),C=z),q(y,"ng-scope"),s=s||z;H=z.name;if(Y=z.controller)t=t||{},M("'"+H+"' controller",t[H],z,y),t[H]=z;if(Y=z.transclude)M("transclusion",D,z,y),D=z,n=z.priority,Y=="element"?(X=u(b),y=c.$$element=u("<\!-- "+H+": "+c[H]+" --\>"),b=y[0],Ga(e,u(X[0]),b),v=w(X,d,n)):(X=u(cb(b)).contents(),y.html(""),v=w(X,d));if(Y=z.template)if(M("template",A,z,y),A=z,Y=Ha(Y),z.replace){X=u("
"+R(Y)+"
").contents();
+b=X[0];if(X.length!=1||b.nodeType!==1)throw new B(g+Y);Ga(e,y,b);H={$attr:{}};a=a.concat(O(b,a.splice(E+1,a.length-(E+1)),H));K(c,H);G=a.length}else y.html(Y);if(z.templateUrl)M("template",A,z,y),A=z,j=W(a.splice(E,a.length-E),j,y,c,e,z.replace,v),G=a.length;else if(z.compile)try{x=z.compile(y,c,v),N(x)?f(null,x):x&&f(x.pre,x.post)}catch(I){k(I,pa(y))}if(z.terminal)j.terminal=!0,n=Math.max(n,z.priority)}j.scope=s&&s.scope;j.transclude=D&&v;return j}function A(d,e,g,h){var j=!1;if(a.hasOwnProperty(e))for(var n,
+e=b.get(e+c),o=0,l=e.length;on.priority)&&n.restrict.indexOf(g)!=-1)d.push(n),j=!0}catch(r){k(r)}return j}function K(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;m(a,function(d,e){e.charAt(0)!="$"&&(b[e]&&(d+=(e==="style"?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});m(b,function(b,f){f=="class"?(q(e,b),a["class"]=(a["class"]?a["class"]+" ":"")+b):f=="style"?e.attr("style",e.attr("style")+";"+b):f.charAt(0)!="$"&&!a.hasOwnProperty(f)&&(a[f]=b,d[f]=c[f])})}function W(a,b,c,d,e,
+f,k){var h=[],n,o,r=c[0],q=a.shift(),w=x({},q,{controller:null,templateUrl:null,transclude:null,scope:null});c.html("");j.get(q.templateUrl,{cache:l}).success(function(j){var l,q,j=Ha(j);if(f){q=u("
"+R(j)+"
").contents();l=q[0];if(q.length!=1||l.nodeType!==1)throw new B(g+j);j={$attr:{}};Ga(e,c,l);O(l,a,j);K(d,j)}else l=r,c.html(j);a.unshift(w);n=C(a,c,d,k);for(o=s(c.contents(),k);h.length;){var ba=h.pop(),j=h.pop();q=h.pop();var y=h.pop(),m=l;q!==r&&(m=cb(l),Ga(j,u(q),m));n(function(){b(o,
+y,m,e,ba)},y,m,e,ba)}h=null}).error(function(a,b,c,d){throw B("Failed to load template: "+d.url);});return function(a,c,d,e,f){h?(h.push(c),h.push(d),h.push(e),h.push(f)):n(function(){b(o,c,d,e,f)},c,d,e,f)}}function y(a,b){return b.priority-a.priority}function M(a,b,c,d){if(b)throw B("Multiple directives ["+b.name+", "+c.name+"] asking for "+a+" on: "+pa(d));}function H(a,b){var c=h(b,!0);c&&a.push({priority:0,compile:I(function(a,b){var d=b.parent(),e=d.data("$binding")||[];e.push(c);q(d.data("$binding",
+e),"ng-binding");a.$watch(c,function(a){b[0].nodeValue=a})})})}function X(a,b,c,d){var e=h(c,!0);e&&b.push({priority:100,compile:I(function(a,b,c){b=c.$$observers||(c.$$observers={});d==="class"&&(e=h(c[d],!0));c[d]=p;(b[d]||(b[d]=[])).$$inter=!0;(c.$$observers&&c.$$observers[d].$$scope||a).$watch(e,function(a){c.$set(d,a)})})})}function Ga(a,b,c){var d=b[0],e=d.parentNode,f,g;if(a){f=0;for(g=a.length;f0){var e=M[0],f=e.text;if(f==a||f==b||f==c||f==d||!a&&!b&&!c&&!d)return e}return!1}function f(b,c,d,f){return(b=i(b,c,d,f))?(a&&!b.json&&e("is not valid json",b),M.shift(),b):!1}function h(a){f(a)||e("is unexpected, expecting ["+a+"]",i())}function k(a,b){return function(c,d){return a(c,d,b)}}function j(a,b,c){return function(d,e){return b(d,e,a,c)}}function l(){for(var a=[];;)if(M.length>0&&!i("}",")",";","]")&&a.push(v()),!f(";"))return a.length==1?a[0]:function(b,c){for(var d,
+e=0;e","<=",">="))a=j(a,b.fn,q());return a}function s(){for(var a=m(),b;b=f("*","/","%");)a=j(a,b.fn,m());return a}function m(){var a;return f("+")?C():(a=f("-"))?j(W,a.fn,m()):(a=f("!"))?k(a.fn,m()):C()}function C(){var a;if(f("("))a=v(),h(")");else if(f("["))a=A();else if(f("{"))a=K();else{var b=f();(a=b.fn)||e("not a primary expression",b)}for(var c;b=f("(","[",".");)b.text==="("?(a=u(a,c),c=null):b.text==="["?(c=a,a=ea(a)):b.text==="."?(c=a,a=t(a)):e("IMPOSSIBLE");
+return a}function A(){var a=[];if(g().text!="]"){do a.push(H());while(f(","))}h("]");return function(b,c){for(var d=[],e=0;e1;d++){var e=a.shift(),g=
+b[e];g||(g={},b[e]=g);b=g}return b[a.shift()]=c}function fb(b,a,c){if(!a)return b;for(var a=a.split("."),d,e=b,g=a.length,i=0;i7),hasEvent:function(c){if(c=="input"&&aa==9)return!1;if(t(a[c])){var e=b.document.createElement("div");a[c]="on"+c in e}return a[c]},csp:!1}}]}function Uc(){this.$get=I(U)}function Mb(b){var a={},c,d,e;if(!b)return a;m(b.split("\n"),function(b){e=b.indexOf(":");c=E(R(b.substr(0,
+e)));d=R(b.substr(e+1));c&&(a[c]?a[c]+=", "+d:a[c]=d)});return a}function Nb(b){var a=L(b)?b:p;return function(c){a||(a=Mb(b));return c?a[E(c)]||null:a}}function Ob(b,a,c){if(N(c))return c(b,a);m(c,function(c){b=c(b,a)});return b}function Vc(){var b=/^\s*(\[|\{[^\{])/,a=/[\}\]]\s*$/,c=/^\)\]\}',?\n/,d=this.defaults={transformResponse:[function(d){F(d)&&(d=d.replace(c,""),b.test(d)&&a.test(d)&&(d=nb(d,!0)));return d}],transformRequest:[function(a){return L(a)&&Sa.apply(a)!=="[object File]"?da(a):a}],
+headers:{common:{Accept:"application/json, text/plain, */*","X-Requested-With":"XMLHttpRequest"},post:{"Content-Type":"application/json;charset=utf-8"},put:{"Content-Type":"application/json;charset=utf-8"}}},e=this.responseInterceptors=[];this.$get=["$httpBackend","$browser","$cacheFactory","$rootScope","$q","$injector",function(a,b,c,h,k,j){function l(a){function c(a){var b=x({},a,{data:Ob(a.data,a.headers,f)});return 200<=a.status&&a.status<300?b:k.reject(b)}a.method=la(a.method);var e=a.transformRequest||
+d.transformRequest,f=a.transformResponse||d.transformResponse,h=d.headers,h=x({"X-XSRF-TOKEN":b.cookies()["XSRF-TOKEN"]},h.common,h[E(a.method)],a.headers),e=Ob(a.data,Nb(h),e),g;t(a.data)&&delete h["Content-Type"];g=o(a,e,h);g=g.then(c,c);m(w,function(a){g=a(g)});g.success=function(b){g.then(function(c){b(c.data,c.status,c.headers,a)});return g};g.error=function(b){g.then(null,function(c){b(c.data,c.status,c.headers,a)});return g};return g}function o(b,c,d){function e(a,b,c){m&&(200<=a&&a<300?m.put(w,
+[a,b,Mb(c)]):m.remove(w));f(b,a,c);h.$apply()}function f(a,c,d){c=Math.max(c,0);(200<=c&&c<300?j.resolve:j.reject)({data:a,status:c,headers:Nb(d),config:b})}function i(){var a=za(l.pendingRequests,b);a!==-1&&l.pendingRequests.splice(a,1)}var j=k.defer(),o=j.promise,m,p,w=r(b.url,b.params);l.pendingRequests.push(b);o.then(i,i);b.cache&&b.method=="GET"&&(m=L(b.cache)?b.cache:n);if(m)if(p=m.get(w))if(p.then)return p.then(i,i),p;else J(p)?f(p[1],p[0],V(p[2])):f(p,200,{});else m.put(w,o);p||a(b.method,
+w,c,e,d,b.timeout,b.withCredentials);return o}function r(a,b){if(!b)return a;var c=[];ec(b,function(a,b){a==null||a==p||(L(a)&&(a=da(a)),c.push(encodeURIComponent(b)+"="+encodeURIComponent(a)))});return a+(a.indexOf("?")==-1?"?":"&")+c.join("&")}var n=c("$http"),w=[];m(e,function(a){w.push(F(a)?j.get(a):j.invoke(a))});l.pendingRequests=[];(function(a){m(arguments,function(a){l[a]=function(b,c){return l(x(c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){m(arguments,function(a){l[a]=
+function(b,c,d){return l(x(d||{},{method:a,url:b,data:c}))}})})("post","put");l.defaults=d;return l}]}function Wc(){this.$get=["$browser","$window","$document",function(b,a,c){return Xc(b,Yc,b.defer,a.angular.callbacks,c[0],a.location.protocol.replace(":",""))}]}function Xc(b,a,c,d,e,g){function i(a,b){var c=e.createElement("script"),d=function(){e.body.removeChild(c);b&&b()};c.type="text/javascript";c.src=a;aa?c.onreadystatechange=function(){/loaded|complete/.test(c.readyState)&&d()}:c.onload=c.onerror=
+d;e.body.appendChild(c)}return function(e,h,k,j,l,o,r){function n(a,c,d,e){c=(h.match(Fb)||["",g])[1]=="file"?d?200:404:c;a(c==1223?204:c,d,e);b.$$completeOutstandingRequest(D)}b.$$incOutstandingRequestCount();h=h||b.url();if(E(e)=="jsonp"){var p="_"+(d.counter++).toString(36);d[p]=function(a){d[p].data=a};i(h.replace("JSON_CALLBACK","angular.callbacks."+p),function(){d[p].data?n(j,200,d[p].data):n(j,-2);delete d[p]})}else{var q=new a;q.open(e,h,!0);m(l,function(a,b){a&&q.setRequestHeader(b,a)});
+var s;q.onreadystatechange=function(){q.readyState==4&&n(j,s||q.status,q.responseText,q.getAllResponseHeaders())};if(r)q.withCredentials=!0;q.send(k||"");o>0&&c(function(){s=-1;q.abort()},o)}}}function Zc(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},
+DATETIME_FORMATS:{MONTH:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),SHORTMONTH:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),DAY:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),SHORTDAY:"Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(","),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",
+shortTime:"h:mm a"},pluralCat:function(b){return b===1?"one":"other"}}}}function $c(){this.$get=["$rootScope","$browser","$q","$exceptionHandler",function(b,a,c,d){function e(e,f,h){var k=c.defer(),j=k.promise,l=v(h)&&!h,f=a.defer(function(){try{k.resolve(e())}catch(a){k.reject(a),d(a)}l||b.$apply()},f),h=function(){delete g[j.$$timeoutId]};j.$$timeoutId=f;g[f]=k;j.then(h,h);return j}var g={};e.cancel=function(b){return b&&b.$$timeoutId in g?(g[b.$$timeoutId].reject("canceled"),a.defer.cancel(b.$$timeoutId)):
+!1};return e}]}function Pb(b){function a(a,e){return b.factory(a+c,e)}var c="Filter";this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+c)}}];a("currency",Qb);a("date",Rb);a("filter",ad);a("json",bd);a("limitTo",cd);a("lowercase",dd);a("number",Sb);a("orderBy",Tb);a("uppercase",ed)}function ad(){return function(b,a){if(!(b instanceof Array))return b;var c=[];c.check=function(a){for(var b=0;b-1;case "object":for(var c in a)if(c.charAt(0)!=="$"&&d(a[c],b))return!0;return!1;case "array":for(c=0;ce+1?i="0":(f=i,k=!0)}if(!k){i=(i.split(Vb)[1]||"").length;t(e)&&(e=Math.min(Math.max(a.minFrac,i),a.maxFrac));var i=Math.pow(10,e),b=Math.round(b*i)/i,b=(""+b).split(Vb),i=b[0],b=b[1]||"",k=0,j=a.lgSize,l=a.gSize;if(i.length>=j+l)for(var k=i.length-j,o=0;o0||e>-c)e+=c;e===0&&c==-12&&(e=12);return ib(e,a,d)}}function La(b,a){return function(c,d){var e=c["get"+b](),g=la(a?"SHORT"+b:b);return d[g][e]}}function Rb(b){function a(a){var b;
+if(b=a.match(c)){var a=new Date(0),g=0,i=0;b[9]&&(g=G(b[9]+b[10]),i=G(b[9]+b[11]));a.setUTCFullYear(G(b[1]),G(b[2])-1,G(b[3]));a.setUTCHours(G(b[4]||0)-g,G(b[5]||0)-i,G(b[6]||0),G(b[7]||0))}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,e){var g="",i=[],f,h,e=e||"mediumDate",e=b.DATETIME_FORMATS[e]||e;F(c)&&(c=fd.test(c)?G(c):a(c));wa(c)&&(c=new Date(c));if(!na(c))return c;for(;e;)(h=gd.exec(e))?(i=i.concat(ia.call(h,
+1)),e=i.pop()):(i.push(e),e=null);m(i,function(a){f=hd[a];g+=f?f(c,b.DATETIME_FORMATS):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function bd(){return function(b){return da(b,!0)}}function cd(){return function(b,a){if(!(b instanceof Array))return b;var a=G(a),c=[],d,e;if(!b||!(b instanceof Array))return c;a>b.length?a=b.length:a<-b.length&&(a=-b.length);a>0?(d=0,e=a):(d=b.length+a,e=b.length);for(;dl?(d.$setValidity("maxlength",
+!1),p):(d.$setValidity("maxlength",!0),a)};d.$parsers.push(c);d.$formatters.push(c)}}function jb(b,a){b="ngClass"+b;return S(function(c,d,e){function g(b,d){if(a===!0||c.$index%2===a)d&&b!==d&&i(d),f(b)}function i(a){L(a)&&!J(a)&&(a=Ta(a,function(a,b){if(a)return b}));d.removeClass(J(a)?a.join(" "):a)}function f(a){L(a)&&!J(a)&&(a=Ta(a,function(a,b){if(a)return b}));a&&d.addClass(J(a)?a.join(" "):a)}c.$watch(e[b],g,!0);e.$observe("class",function(){var a=c.$eval(e[b]);g(a,a)});b!=="ngClass"&&c.$watch("$index",
+function(d,g){var j=d%2;j!==g%2&&(j==a?f(c.$eval(e[b])):i(c.$eval(e[b])))})})}var E=function(b){return F(b)?b.toLowerCase():b},la=function(b){return F(b)?b.toUpperCase():b},B=U.Error,aa=G((/msie (\d+)/.exec(E(navigator.userAgent))||[])[1]),u,ja,ia=[].slice,Ra=[].push,Sa=Object.prototype.toString,Yb=U.angular||(U.angular={}),ta,Cb,Z=["0","0","0"];D.$inject=[];ma.$inject=[];Cb=aa<9?function(b){b=b.nodeName?b:b[0];return b.scopeName&&b.scopeName!="HTML"?la(b.scopeName+":"+b.nodeName):b.nodeName}:function(b){return b.nodeName?
+b.nodeName:b[0].nodeName};var kc=/[A-Z]/g,id={full:"1.0.3",major:1,minor:0,dot:3,codeName:"bouncy-thunder"},Ba=Q.cache={},Aa=Q.expando="ng-"+(new Date).getTime(),oc=1,Zb=U.document.addEventListener?function(b,a,c){b.addEventListener(a,c,!1)}:function(b,a,c){b.attachEvent("on"+a,c)},db=U.document.removeEventListener?function(b,a,c){b.removeEventListener(a,c,!1)}:function(b,a,c){b.detachEvent("on"+a,c)},mc=/([\:\-\_]+(.))/g,nc=/^moz([A-Z])/,ua=Q.prototype={ready:function(b){function a(){c||(c=!0,b())}
+var c=!1;this.bind("DOMContentLoaded",a);Q(U).bind("load",a)},toString:function(){var b=[];m(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return b>=0?u(this[b]):u(this[this.length+b])},length:0,push:Ra,sort:[].sort,splice:[].splice},Ea={};m("multiple,selected,checked,disabled,readOnly,required".split(","),function(b){Ea[E(b)]=b});var zb={};m("input,select,option,textarea,button,form".split(","),function(b){zb[la(b)]=!0});m({data:ub,inheritedData:Da,scope:function(b){return Da(b,
+"$scope")},controller:xb,injector:function(b){return Da(b,"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:Ca,css:function(b,a,c){a=rb(a);if(v(c))b.style[a]=c;else{var d;aa<=8&&(d=b.currentStyle&&b.currentStyle[a],d===""&&(d="auto"));d=d||b.style[a];aa<=8&&(d=d===""?p:d);return d}},attr:function(b,a,c){var d=E(a);if(Ea[d])if(v(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||D).specified?d:p;else if(v(c))b.setAttribute(a,
+c);else if(b.getAttribute)return b=b.getAttribute(a,2),b===null?p:b},prop:function(b,a,c){if(v(c))b[a]=c;else return b[a]},text:x(aa<9?function(b,a){if(b.nodeType==1){if(t(a))return b.innerText;b.innerText=a}else{if(t(a))return b.nodeValue;b.nodeValue=a}}:function(b,a){if(t(a))return b.textContent;b.textContent=a},{$dv:""}),val:function(b,a){if(t(a))return b.value;b.value=a},html:function(b,a){if(t(a))return b.innerHTML;for(var c=0,d=b.childNodes;c":function(a,c,d,e){return d(a,c)>e(a,c)},"<=":function(a,c,d,e){return d(a,c)<=e(a,c)},">=":function(a,c,d,e){return d(a,c)>=e(a,
+c)},"&&":function(a,c,d,e){return d(a,c)&&e(a,c)},"||":function(a,c,d,e){return d(a,c)||e(a,c)},"&":function(a,c,d,e){return d(a,c)&e(a,c)},"|":function(a,c,d,e){return e(a,c)(a,c,d(a,c))},"!":function(a,c,d){return!d(a,c)}},Lc={n:"\n",f:"\u000c",r:"\r",t:"\t",v:"\u000b","'":"'",'"':'"'},hb={},Yc=U.XMLHttpRequest||function(){try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(a){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(c){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(d){}throw new B("This browser does not support XMLHttpRequest.");
+};Pb.$inject=["$provide"];Qb.$inject=["$locale"];Sb.$inject=["$locale"];var Vb=".",hd={yyyy:P("FullYear",4),yy:P("FullYear",2,0,!0),y:P("FullYear",1),MMMM:La("Month"),MMM:La("Month",!0),MM:P("Month",2,1),M:P("Month",1,1),dd:P("Date",2),d:P("Date",1),HH:P("Hours",2),H:P("Hours",1),hh:P("Hours",2,-12),h:P("Hours",1,-12),mm:P("Minutes",2),m:P("Minutes",1),ss:P("Seconds",2),s:P("Seconds",1),EEEE:La("Day"),EEE:La("Day",!0),a:function(a,c){return a.getHours()<12?c.AMPMS[0]:c.AMPMS[1]},Z:function(a){a=a.getTimezoneOffset();
+return ib(a/60,2)+ib(Math.abs(a%60),2)}},gd=/((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,fd=/^\d+$/;Rb.$inject=["$locale"];var dd=I(E),ed=I(la);Tb.$inject=["$parse"];var jd=I({restrict:"E",compile:function(a,c){c.href||c.$set("href","");return function(a,c){c.bind("click",function(a){if(!c.attr("href"))return a.preventDefault(),!1})}}}),kb={};m(Ea,function(a,c){var d=fa("ng-"+c);kb[d]=function(){return{priority:100,compile:function(){return function(a,g,i){a.$watch(i[d],
+function(a){i.$set(c,!!a)})}}}}});m(["src","href"],function(a){var c=fa("ng-"+a);kb[c]=function(){return{priority:99,link:function(d,e,g){g.$observe(c,function(c){c&&(g.$set(a,c),aa&&e.prop(a,c))})}}}});var Oa={$addControl:D,$removeControl:D,$setValidity:D,$setDirty:D};Wb.$inject=["$element","$attrs","$scope"];var Ra=function(a){return["$timeout",function(c){var d={name:"form",restrict:"E",controller:Wb,compile:function(){return{pre:function(a,d,i,f){if(!i.action){var h=function(a){a.preventDefault?
+a.preventDefault():a.returnValue=!1};Zb(d[0],"submit",h);d.bind("$destroy",function(){c(function(){db(d[0],"submit",h)},0,!1)})}var k=d.parent().controller("form"),j=i.name||i.ngForm;j&&(a[j]=f);k&&d.bind("$destroy",function(){k.$removeControl(f);j&&(a[j]=p);x(f,Oa)})}}}};return a?x(V(d),{restrict:"EAC"}):d}]},kd=Ra(),ld=Ra(!0),md=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,nd=/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/,od=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,
+ac={text:Qa,number:function(a,c,d,e,g,i){Qa(a,c,d,e,g,i);e.$parsers.push(function(a){var c=T(a);return c||od.test(a)?(e.$setValidity("number",!0),a===""?null:c?a:parseFloat(a)):(e.$setValidity("number",!1),p)});e.$formatters.push(function(a){return T(a)?"":""+a});if(d.min){var f=parseFloat(d.min),a=function(a){return!T(a)&&ah?(e.$setValidity("max",
+!1),p):(e.$setValidity("max",!0),a)};e.$parsers.push(d);e.$formatters.push(d)}e.$formatters.push(function(a){return T(a)||wa(a)?(e.$setValidity("number",!0),a):(e.$setValidity("number",!1),p)})},url:function(a,c,d,e,g,i){Qa(a,c,d,e,g,i);a=function(a){return T(a)||md.test(a)?(e.$setValidity("url",!0),a):(e.$setValidity("url",!1),p)};e.$formatters.push(a);e.$parsers.push(a)},email:function(a,c,d,e,g,i){Qa(a,c,d,e,g,i);a=function(a){return T(a)||nd.test(a)?(e.$setValidity("email",!0),a):(e.$setValidity("email",
+!1),p)};e.$formatters.push(a);e.$parsers.push(a)},radio:function(a,c,d,e){t(d.name)&&c.attr("name",xa());c.bind("click",function(){c[0].checked&&a.$apply(function(){e.$setViewValue(d.value)})});e.$render=function(){c[0].checked=d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e){var g=d.ngTrueValue,i=d.ngFalseValue;F(g)||(g=!0);F(i)||(i=!1);c.bind("click",function(){a.$apply(function(){e.$setViewValue(c[0].checked)})});e.$render=function(){c[0].checked=e.$viewValue};e.$formatters.push(function(a){return a===
+g});e.$parsers.push(function(a){return a?g:i})},hidden:D,button:D,submit:D,reset:D},bc=["$browser","$sniffer",function(a,c){return{restrict:"E",require:"?ngModel",link:function(d,e,g,i){i&&(ac[E(g.type)]||ac.text)(d,e,g,i,c,a)}}}],Na="ng-valid",Ma="ng-invalid",Pa="ng-pristine",Xb="ng-dirty",pd=["$scope","$exceptionHandler","$attrs","$element","$parse",function(a,c,d,e,g){function i(a,c){c=c?"-"+$a(c,"-"):"";e.removeClass((a?Ma:Na)+c).addClass((a?Na:Ma)+c)}this.$modelValue=this.$viewValue=Number.NaN;
+this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$name=d.name;var f=g(d.ngModel),h=f.assign;if(!h)throw B(Db+d.ngModel+" ("+pa(e)+")");this.$render=D;var k=e.inheritedData("$formController")||Oa,j=0,l=this.$error={};e.addClass(Pa);i(!0);this.$setValidity=function(a,c){if(l[a]!==!c){if(c){if(l[a]&&j--,!j)i(!0),this.$valid=!0,this.$invalid=!1}else i(!1),this.$invalid=!0,this.$valid=!1,j++;l[a]=!c;i(c,a);k.$setValidity(a,
+c,this)}};this.$setViewValue=function(d){this.$viewValue=d;if(this.$pristine)this.$dirty=!0,this.$pristine=!1,e.removeClass(Pa).addClass(Xb),k.$setDirty();m(this.$parsers,function(a){d=a(d)});if(this.$modelValue!==d)this.$modelValue=d,h(a,d),m(this.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}})};var o=this;a.$watch(function(){var c=f(a);if(o.$modelValue!==c){var d=o.$formatters,e=d.length;for(o.$modelValue=c;e--;)c=d[e](c);if(o.$viewValue!==c)o.$viewValue=c,o.$render()}})}],qd=function(){return{require:["ngModel",
+"^?form"],controller:pd,link:function(a,c,d,e){var g=e[0],i=e[1]||Oa;i.$addControl(g);c.bind("$destroy",function(){i.$removeControl(g)})}}},rd=I({require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),cc=function(){return{require:"?ngModel",link:function(a,c,d,e){if(e){d.required=!0;var g=function(a){if(d.required&&(T(a)||a===!1))e.$setValidity("required",!1);else return e.$setValidity("required",!0),a};e.$formatters.push(g);e.$parsers.unshift(g);
+d.$observe("required",function(){g(e.$viewValue)})}}}},sd=function(){return{require:"ngModel",link:function(a,c,d,e){var g=(a=/\/(.*)\//.exec(d.ngList))&&RegExp(a[1])||d.ngList||",";e.$parsers.push(function(a){var c=[];a&&m(a.split(g),function(a){a&&c.push(R(a))});return c});e.$formatters.push(function(a){return J(a)?a.join(", "):p})}}},td=/^(true|false|\d+)$/,ud=function(){return{priority:100,compile:function(a,c){return td.test(c.ngValue)?function(a,c,g){g.$set("value",a.$eval(g.ngValue))}:function(a,
+c,g){a.$watch(g.ngValue,function(a){g.$set("value",a,!1)})}}}},vd=S(function(a,c,d){c.addClass("ng-binding").data("$binding",d.ngBind);a.$watch(d.ngBind,function(a){c.text(a==p?"":a)})}),wd=["$interpolate",function(a){return function(c,d,e){c=a(d.attr(e.$attr.ngBindTemplate));d.addClass("ng-binding").data("$binding",c);e.$observe("ngBindTemplate",function(a){d.text(a)})}}],xd=[function(){return function(a,c,d){c.addClass("ng-binding").data("$binding",d.ngBindHtmlUnsafe);a.$watch(d.ngBindHtmlUnsafe,
+function(a){c.html(a||"")})}}],yd=jb("",!0),zd=jb("Odd",0),Ad=jb("Even",1),Bd=S({compile:function(a,c){c.$set("ngCloak",p);a.removeClass("ng-cloak")}}),Cd=[function(){return{scope:!0,controller:"@"}}],Dd=["$sniffer",function(a){return{priority:1E3,compile:function(){a.csp=!0}}}],dc={};m("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave".split(" "),function(a){var c=fa("ng-"+a);dc[c]=["$parse",function(d){return function(e,g,i){var f=d(i[c]);g.bind(E(a),function(a){e.$apply(function(){f(e,
+{$event:a})})})}}]});var Ed=S(function(a,c,d){c.bind("submit",function(){a.$apply(d.ngSubmit)})}),Fd=["$http","$templateCache","$anchorScroll","$compile",function(a,c,d,e){return{restrict:"ECA",terminal:!0,compile:function(g,i){var f=i.ngInclude||i.src,h=i.onload||"",k=i.autoscroll;return function(g,i){var o=0,m,n=function(){m&&(m.$destroy(),m=null);i.html("")};g.$watch(f,function(f){var p=++o;f?a.get(f,{cache:c}).success(function(a){p===o&&(m&&m.$destroy(),m=g.$new(),i.html(a),e(i.contents())(m),
+v(k)&&(!k||g.$eval(k))&&d(),m.$emit("$includeContentLoaded"),g.$eval(h))}).error(function(){p===o&&n()}):n()})}}}}],Gd=S({compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),Hd=S({terminal:!0,priority:1E3}),Id=["$locale","$interpolate",function(a,c){var d=/{}/g;return{restrict:"EA",link:function(e,g,i){var f=i.count,h=g.attr(i.$attr.when),k=i.offset||0,j=e.$eval(h),l={},o=c.startSymbol(),r=c.endSymbol();m(j,function(a,e){l[e]=c(a.replace(d,o+f+"-"+k+r))});e.$watch(function(){var c=
+parseFloat(e.$eval(f));return isNaN(c)?"":(j[c]||(c=a.pluralCat(c-k)),l[c](e,g,!0))},function(a){g.text(a)})}}}],Jd=S({transclude:"element",priority:1E3,terminal:!0,compile:function(a,c,d){return function(a,c,i){var f=i.ngRepeat,i=f.match(/^\s*(.+)\s+in\s+(.*)\s*$/),h,k,j;if(!i)throw B("Expected ngRepeat in form of '_item_ in _collection_' but got '"+f+"'.");f=i[1];h=i[2];i=f.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);if(!i)throw B("'item' in 'item in collection' should be identifier or (key, value) but got '"+
+f+"'.");k=i[3]||i[1];j=i[2];var l=new eb;a.$watch(function(a){var e,f,i=a.$eval(h),m=gc(i,!0),p,u=new eb,C,A,v,t,y=c;if(J(i))v=i||[];else{v=[];for(C in i)i.hasOwnProperty(C)&&C.charAt(0)!="$"&&v.push(C);v.sort()}e=0;for(f=v.length;ex;)t.pop().element.remove()}for(;v.length>w;)v.pop()[0].element.remove()}var i;if(!(i=w.match(d)))throw B("Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_' but got '"+w+"'.");var j=c(i[2]||i[1]),k=i[4]||
+i[6],l=i[5],m=c(i[3]||""),o=c(i[2]?i[1]:k),r=c(i[7]),v=[[{element:f,label:""}]];q&&(a(q)(e),q.removeClass("ng-scope"),q.remove());f.html("");f.bind("change",function(){e.$apply(function(){var a,c=r(e)||[],d={},h,i,j,m,q,s;if(n){i=[];m=0;for(s=v.length;m@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak{display:none;}ng\\:form{display:block;}');
diff -r 8e546d108658 -r b42911b78a16 dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/app.js
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/app.js Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,224 @@
+// 'use strict';
+
+// Declare app level module which depends on filters, and services
+angular.module('bck2brwsr', []).
+ directive('uiCodemirror', ['$timeout', function($timeout) {
+ 'use strict';
+
+ var events = ["cursorActivity", "viewportChange", "gutterClick", "focus", "blur", "scroll", "update"];
+ return {
+ restrict: 'A',
+ require: 'ngModel',
+ link: function(scope, elm, attrs, ngModel) {
+ var options, opts, onChange, deferCodeMirror, codeMirror, timeoutId, val;
+
+ if (elm[0].type !== 'textarea') {
+ throw new Error('uiCodemirror3 can only be applied to a textarea element');
+ }
+
+ options = /* uiConfig.codemirror || */ {};
+ opts = angular.extend({}, options, scope.$eval(attrs.uiCodemirror));
+
+ onChange = function(instance, changeObj) {
+ val = instance.getValue();
+ $timeout.cancel(timeoutId);
+ timeoutId = $timeout(function() {
+ ngModel.$setViewValue(val);
+ }, 500);
+ };
+
+ deferCodeMirror = function() {
+ codeMirror = CodeMirror.fromTextArea(elm[0], opts);
+ elm[0].codeMirror = codeMirror;
+ // codeMirror.on("change", onChange(opts.onChange));
+ codeMirror.on("change", onChange);
+
+ for (var i = 0, n = events.length, aEvent; i < n; ++i) {
+ aEvent = opts["on" + events[i].charAt(0).toUpperCase() + events[i].slice(1)];
+ if (aEvent === void 0)
+ continue;
+ if (typeof aEvent !== "function")
+ continue;
+
+ var bound = _.bind( aEvent, scope );
+
+ codeMirror.on(events[i], bound);
+ }
+
+ // CodeMirror expects a string, so make sure it gets one.
+ // This does not change the model.
+ ngModel.$formatters.push(function(value) {
+ if (angular.isUndefined(value) || value === null) {
+ return '';
+ }
+ else if (angular.isObject(value) || angular.isArray(value)) {
+ throw new Error('ui-codemirror cannot use an object or an array as a model');
+ }
+ return value;
+ });
+
+ // Override the ngModelController $render method, which is what gets called when the model is updated.
+ // This takes care of the synchronizing the codeMirror element with the underlying model, in the case that it is changed by something else.
+ ngModel.$render = function() {
+ codeMirror.setValue(ngModel.$viewValue);
+ };
+
+ };
+
+ $timeout(deferCodeMirror);
+
+ }
+ };
+}]);
+
+function DevCtrl( $scope, $http ) {
+ var templateHtml =
+"\n" +
+" \n" +
+" \n" +
+" * 0 \n" +
+" = 0\n" +
+" \n" +
+" \n" +
+" " +
+" \n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+"\n" +
+" \n" +
+" \n" +
+"";
+ var templateJava =
+"package bck2brwsr.demo;\n" +
+"import org.apidesign.bck2brwsr.htmlpage.api.*;\n" +
+"import static org.apidesign.bck2brwsr.htmlpage.api.OnEvent.*;\n" +
+"\n" +
+"@Page(xhtml=\"index.html\", className=\"Index\", properties={\n" +
+" @Property(name=\"value\", type=int.class)\n" +
+"})\n" +
+"class YourFirstHTML5PageInRealLanguage {\n" +
+" static { new Index().applyBindings(); }\n" +
+" @On(event=CLICK, id=\"dupl\") static void duplicateValue(Index m) {\n" +
+" m.setValue(m.getValue() * 2);\n" +
+" }\n" +
+" @On(event=CLICK, id=\"clear\") static void zeroTheValue(Index m) {\n" +
+" m.setValue(0);;\n" +
+" }\n" +
+" @ComputedProperty static int powerValue(int value) {\n" +
+" return value * value;\n" +
+" }\n" +
+"}";
+
+
+ $scope.makeMarker = function( editor, line ) {
+ var marker = document.createElement("div");
+ marker.innerHTML = " ";
+ marker.className = "issue";
+
+ var info = editor.lineInfo(line);
+ editor.setGutterMarker(line, "issues", info.markers ? null : marker);
+
+ return marker;
+ };
+
+
+ // Returns a function, that, as long as it continues to be invoked, will not
+ // be triggered. The function will be called after it stops being called for
+ // N milliseconds. If `immediate` is passed, trigger the function on the
+ // leading edge, instead of the trailing.
+ $scope.debounce = function(func, wait, immediate) {
+ var timeout, result;
+ return function() {
+ var context = this, args = arguments;
+ var later = function() {
+ timeout = null;
+ if (!immediate) result = func.apply(context, args);
+ };
+ var callNow = immediate && !timeout;
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ if (callNow) result = func.apply(context, args);
+ return result;
+ };
+ };
+
+ $scope.reload = function() {
+ $scope.errors = null;
+ var frame = document.getElementById("result");
+ frame.src = "result.html";
+ frame.contentDocument.location.reload(true);
+ frame.contentWindow.location.reload();
+ document.getElementById("editorJava").codeMirror.clearGutter("issues");
+ };
+
+ $scope.fail = function( data ) {
+ $scope.errors = eval( data );
+ var editor = document.getElementById("editorJava").codeMirror;
+ editor.clearGutter( "issues" );
+
+ for( var i = 0; i < $scope.errors.length; i ++ ) {
+ $scope.makeMarker( editor, $scope.errors[i].line - 1 );
+ }
+
+ };
+
+ $scope.post = function() {
+ return $http({url: ".",
+ method: "POST",
+ //headers: this.headers,
+ data: { html : $scope.html, java : $scope.java}
+ }).success( $scope.reload ).error( $scope.fail );
+ };
+
+ $scope.errorClass = function( kind ) {
+ switch( kind ) {
+ case "ERROR" :
+ return "error";
+ default :
+ return "warning";
+ }
+ };
+
+ $scope.gotoError = function( line, col ) {
+ var editor = document.getElementById("editorJava").codeMirror;
+ editor.setCursor({ line: line - 1, ch : col - 1 });
+ editor.focus();
+ };
+
+ $scope.tab = "html";
+ $scope.html= templateHtml;
+ $scope.java = templateJava;
+
+ $scope.$watch( "html", $scope.debounce( $scope.post, 2000 ) );
+ $scope.$watch( "java", $scope.debounce( $scope.post, 2000 ) );
+ $scope.post();
+
+}
diff -r 8e546d108658 -r b42911b78a16 dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/codemirror.css
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/codemirror.css Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,239 @@
+/* BASICS */
+
+.CodeMirror {
+ /* Set height, width, borders, and global font properties here */
+ font-family: monospace;
+ height: 300px;
+}
+.CodeMirror-scroll {
+ /* Set scrolling behaviour here */
+ overflow: auto;
+}
+
+/* PADDING */
+
+.CodeMirror-lines {
+ padding: 4px 0; /* Vertical padding around content */
+}
+.CodeMirror pre {
+ padding: 0 4px; /* Horizontal padding of content */
+}
+
+.CodeMirror-scrollbar-filler {
+ background-color: white; /* The little square between H and V scrollbars */
+}
+
+/* GUTTER */
+
+.CodeMirror-gutters {
+ border-right: 1px solid #ddd;
+ background-color: #f7f7f7;
+}
+.CodeMirror-linenumbers {}
+.CodeMirror-linenumber {
+ padding: 0 3px 0 5px;
+ min-width: 20px;
+ text-align: right;
+ color: #999;
+}
+
+/* CURSOR */
+
+.CodeMirror pre.CodeMirror-cursor {
+ border-left: 1px solid black;
+}
+/* Shown when moving in bi-directional text */
+.CodeMirror pre.CodeMirror-secondarycursor {
+ border-left: 1px solid silver;
+}
+.cm-keymap-fat-cursor pre.CodeMirror-cursor {
+ width: auto;
+ border: 0;
+ background: transparent;
+ background: rgba(0, 200, 0, .4);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#6600c800, endColorstr=#4c00c800);
+}
+/* Kludge to turn off filter in ie9+, which also accepts rgba */
+.cm-keymap-fat-cursor pre.CodeMirror-cursor:not(#nonsense_id) {
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
+}
+/* Can style cursor different in overwrite (non-insert) mode */
+.CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {}
+
+/* DEFAULT THEME */
+
+.cm-s-default .cm-keyword {color: #708;}
+.cm-s-default .cm-atom {color: #219;}
+.cm-s-default .cm-number {color: #164;}
+.cm-s-default .cm-def {color: #00f;}
+.cm-s-default .cm-variable {color: black;}
+.cm-s-default .cm-variable-2 {color: #05a;}
+.cm-s-default .cm-variable-3 {color: #085;}
+.cm-s-default .cm-property {color: black;}
+.cm-s-default .cm-operator {color: black;}
+.cm-s-default .cm-comment {color: #a50;}
+.cm-s-default .cm-string {color: #a11;}
+.cm-s-default .cm-string-2 {color: #f50;}
+.cm-s-default .cm-meta {color: #555;}
+.cm-s-default .cm-error {color: #f00;}
+.cm-s-default .cm-qualifier {color: #555;}
+.cm-s-default .cm-builtin {color: #30a;}
+.cm-s-default .cm-bracket {color: #997;}
+.cm-s-default .cm-tag {color: #170;}
+.cm-s-default .cm-attribute {color: #00c;}
+.cm-s-default .cm-header {color: blue;}
+.cm-s-default .cm-quote {color: #090;}
+.cm-s-default .cm-hr {color: #999;}
+.cm-s-default .cm-link {color: #00c;}
+
+.cm-negative {color: #d44;}
+.cm-positive {color: #292;}
+.cm-header, .cm-strong {font-weight: bold;}
+.cm-em {font-style: italic;}
+.cm-emstrong {font-style: italic; font-weight: bold;}
+.cm-link {text-decoration: underline;}
+
+.cm-invalidchar {color: #f00;}
+
+div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
+div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
+
+/* STOP */
+
+/* The rest of this file contains styles related to the mechanics of
+ the editor. You probably shouldn't touch them. */
+
+.CodeMirror {
+ line-height: 1;
+ position: relative;
+ overflow: hidden;
+}
+
+.CodeMirror-scroll {
+ /* 30px is the magic margin used to hide the element's real scrollbars */
+ /* See overflow: hidden in .CodeMirror, and the paddings in .CodeMirror-sizer */
+ margin-bottom: -30px; margin-right: -30px;
+ padding-bottom: 30px; padding-right: 30px;
+ height: 100%;
+ outline: none; /* Prevent dragging from highlighting the element */
+ position: relative;
+}
+.CodeMirror-sizer {
+ position: relative;
+}
+
+/* The fake, visible scrollbars. Used to force redraw during scrolling
+ before actuall scrolling happens, thus preventing shaking and
+ flickering artifacts. */
+.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler {
+ position: absolute;
+ z-index: 6;
+ display: none;
+}
+.CodeMirror-vscrollbar {
+ right: 0; top: 0;
+ overflow-x: hidden;
+ overflow-y: scroll;
+}
+.CodeMirror-hscrollbar {
+ bottom: 0; left: 0;
+ overflow-y: hidden;
+ overflow-x: scroll;
+}
+.CodeMirror-scrollbar-filler {
+ right: 0; bottom: 0;
+ z-index: 6;
+}
+
+.CodeMirror-gutters {
+ position: absolute; left: 0; top: 0;
+ height: 100%;
+ z-index: 3;
+}
+.CodeMirror-gutter {
+ height: 100%;
+ display: inline-block;
+ /* Hack to make IE7 behave */
+ *zoom:1;
+ *display:inline;
+}
+.CodeMirror-gutter-elt {
+ position: absolute;
+ cursor: default;
+ z-index: 4;
+}
+
+.CodeMirror-lines {
+ cursor: text;
+}
+.CodeMirror pre {
+ /* Reset some styles that the rest of the page might have set */
+ -moz-border-radius: 0; -webkit-border-radius: 0; -o-border-radius: 0; border-radius: 0;
+ border-width: 0;
+ background: transparent;
+ font-family: inherit;
+ font-size: inherit;
+ margin: 0;
+ white-space: pre;
+ word-wrap: normal;
+ line-height: inherit;
+ color: inherit;
+ z-index: 2;
+ position: relative;
+ overflow: visible;
+}
+.CodeMirror-wrap pre {
+ word-wrap: break-word;
+ white-space: pre-wrap;
+ word-break: normal;
+}
+.CodeMirror-linebackground {
+ position: absolute;
+ left: 0; right: 0; top: 0; bottom: 0;
+ z-index: 0;
+}
+
+.CodeMirror-linewidget {
+ position: relative;
+ z-index: 2;
+}
+
+.CodeMirror-wrap .CodeMirror-scroll {
+ overflow-x: hidden;
+}
+
+.CodeMirror-measure {
+ position: absolute;
+ width: 100%; height: 0px;
+ overflow: hidden;
+ visibility: hidden;
+}
+.CodeMirror-measure pre { position: static; }
+
+.CodeMirror pre.CodeMirror-cursor {
+ position: absolute;
+ visibility: hidden;
+ border-right: none;
+ width: 0;
+}
+.CodeMirror-focused pre.CodeMirror-cursor {
+ visibility: visible;
+}
+
+.CodeMirror-selected { background: #d9d9d9; }
+.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
+
+.CodeMirror-searching {
+ background: #ffa;
+ background: rgba(255, 255, 0, .4);
+}
+
+/* IE7 hack to prevent it from returning funny offsetTops on the spans */
+.CodeMirror span { *vertical-align: text-bottom; }
+
+@media print {
+ /* Hide the cursor when printing */
+ .CodeMirror pre.CodeMirror-cursor {
+ visibility: hidden;
+ }
+}
diff -r 8e546d108658 -r b42911b78a16 dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/codemirror.js
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/codemirror.js Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,4553 @@
+// CodeMirror version 3.0
+//
+// CodeMirror is the only global var we claim
+window.CodeMirror = (function() {
+ "use strict";
+
+ // BROWSER SNIFFING
+
+ // Crude, but necessary to handle a number of hard-to-feature-detect
+ // bugs and behavior differences.
+ var gecko = /gecko\/\d/i.test(navigator.userAgent);
+ var ie = /MSIE \d/.test(navigator.userAgent);
+ var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
+ var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
+ var webkit = /WebKit\//.test(navigator.userAgent);
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
+ var chrome = /Chrome\//.test(navigator.userAgent);
+ var opera = /Opera\//.test(navigator.userAgent);
+ var safari = /Apple Computer/.test(navigator.vendor);
+ var khtml = /KHTML\//.test(navigator.userAgent);
+ var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
+ var phantom = /PhantomJS/.test(navigator.userAgent);
+
+ var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
+ var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|IEMobile/i.test(navigator.userAgent);
+ var mac = ios || /Mac/.test(navigator.platform);
+
+ // Optimize some code when these features are not used
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
+
+ // CONSTRUCTOR
+
+ function CodeMirror(place, options) {
+ if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
+
+ this.options = options = options || {};
+ // Determine effective options based on given values and defaults.
+ for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
+ options[opt] = defaults[opt];
+ setGuttersForLineNumbers(options);
+
+ var display = this.display = makeDisplay(place);
+ display.wrapper.CodeMirror = this;
+ updateGutters(this);
+ if (options.autofocus && !mobile) focusInput(this);
+
+ this.view = makeView(new BranchChunk([new LeafChunk([makeLine("", null, textHeight(display))])]));
+ this.nextOpId = 0;
+ loadMode(this);
+ themeChanged(this);
+ if (options.lineWrapping)
+ this.display.wrapper.className += " CodeMirror-wrap";
+
+ // Initialize the content.
+ this.setValue(options.value || "");
+ // Override magic textarea content restore that IE sometimes does
+ // on our hidden textarea on reload
+ if (ie) setTimeout(bind(resetInput, this, true), 20);
+ this.view.history = makeHistory();
+
+ registerEventHandlers(this);
+ // IE throws unspecified error in certain cases, when
+ // trying to access activeElement before onload
+ var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
+ if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
+ else onBlur(this);
+
+ operation(this, function() {
+ for (var opt in optionHandlers)
+ if (optionHandlers.propertyIsEnumerable(opt))
+ optionHandlers[opt](this, options[opt], Init);
+ for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
+ })();
+ }
+
+ // DISPLAY CONSTRUCTOR
+
+ function makeDisplay(place) {
+ var d = {};
+ var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;");
+ input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off");
+ // Wraps and hides input textarea
+ d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
+ // The actual fake scrollbars.
+ d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
+ d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
+ // DIVs containing the selection and the actual code
+ d.lineDiv = elt("div");
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
+ // Blinky cursor, and element used to ensure cursor fits at the end of a line
+ d.cursor = elt("pre", "\u00a0", "CodeMirror-cursor");
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
+ d.otherCursor = elt("pre", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
+ // Used to measure text size
+ d.measure = elt("div", null, "CodeMirror-measure");
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
+ d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
+ null, "position: relative; outline: none");
+ // Moved around its parent to cover visible view
+ d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
+ // Set to the height of the text, causes scrolling
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
+ // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
+ d.heightForcer = elt("div", "\u00a0", null, "position: absolute; height: " + scrollerCutOff + "px");
+ // Will contain the gutters, if any
+ d.gutters = elt("div", null, "CodeMirror-gutters");
+ d.lineGutter = null;
+ // Helper element to properly size the gutter backgrounds
+ var scrollerInner = elt("div", [d.sizer, d.heightForcer, d.gutters], null, "position: relative; min-height: 100%");
+ // Provides scrolling
+ d.scroller = elt("div", [scrollerInner], "CodeMirror-scroll");
+ d.scroller.setAttribute("tabIndex", "-1");
+ // The element in which the editor lives.
+ d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
+ d.scrollbarFiller, d.scroller], "CodeMirror");
+ // Work around IE7 z-index bug
+ if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
+ if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
+
+ // Needed to hide big blue blinking cursor on Mobile Safari
+ if (ios) input.style.width = "0px";
+ if (!webkit) d.scroller.draggable = true;
+ // Needed to handle Tab key in KHTML
+ if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
+ else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
+
+ // Current visible range (may be bigger than the view window).
+ d.viewOffset = d.showingFrom = d.showingTo = d.lastSizeC = 0;
+
+ // Used to only resize the line number gutter when necessary (when
+ // the amount of lines crosses a boundary that makes its width change)
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
+ // See readInput and resetInput
+ d.prevInput = "";
+ // Set to true when a non-horizontal-scrolling widget is added. As
+ // an optimization, widget aligning is skipped when d is false.
+ d.alignWidgets = false;
+ // Flag that indicates whether we currently expect input to appear
+ // (after some event like 'keypress' or 'input') and are polling
+ // intensively.
+ d.pollingFast = false;
+ // Self-resetting timeout for the poller
+ d.poll = new Delayed();
+ // True when a drag from the editor is active
+ d.draggingText = false;
+
+ d.cachedCharWidth = d.cachedTextHeight = null;
+ d.measureLineCache = [];
+ d.measureLineCachePos = 0;
+
+ // Tracks when resetInput has punted to just putting a short
+ // string instead of the (large) selection.
+ d.inaccurateSelection = false;
+
+ // Used to adjust overwrite behaviour when a paste has been
+ // detected
+ d.pasteIncoming = false;
+
+ return d;
+ }
+
+ // VIEW CONSTRUCTOR
+
+ function makeView(doc) {
+ var selPos = {line: 0, ch: 0};
+ return {
+ doc: doc,
+ // frontier is the point up to which the content has been parsed,
+ frontier: 0, highlight: new Delayed(),
+ sel: {from: selPos, to: selPos, head: selPos, anchor: selPos, shift: false, extend: false},
+ scrollTop: 0, scrollLeft: 0,
+ overwrite: false, focused: false,
+ // Tracks the maximum line length so that
+ // the horizontal scrollbar can be kept
+ // static when scrolling.
+ maxLine: getLine(doc, 0),
+ maxLineLength: 0,
+ maxLineChanged: false,
+ suppressEdits: false,
+ goalColumn: null,
+ cantEdit: false,
+ keyMaps: []
+ };
+ }
+
+ // STATE UPDATES
+
+ // Used to get the editor into a consistent state again when options change.
+
+ function loadMode(cm) {
+ var doc = cm.view.doc;
+ cm.view.mode = CodeMirror.getMode(cm.options, cm.options.mode);
+ doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
+ cm.view.frontier = 0;
+ startWorker(cm, 100);
+ }
+
+ function wrappingChanged(cm) {
+ var doc = cm.view.doc, th = textHeight(cm.display);
+ if (cm.options.lineWrapping) {
+ cm.display.wrapper.className += " CodeMirror-wrap";
+ var perLine = cm.display.scroller.clientWidth / charWidth(cm.display) - 3;
+ doc.iter(0, doc.size, function(line) {
+ if (line.height == 0) return;
+ var guess = Math.ceil(line.text.length / perLine) || 1;
+ if (guess != 1) updateLineHeight(line, guess * th);
+ });
+ cm.display.sizer.style.minWidth = "";
+ } else {
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
+ computeMaxLength(cm.view);
+ doc.iter(0, doc.size, function(line) {
+ if (line.height != 0) updateLineHeight(line, th);
+ });
+ }
+ regChange(cm, 0, doc.size);
+ clearCaches(cm);
+ setTimeout(function(){updateScrollbars(cm.display, cm.view.doc.height);}, 100);
+ }
+
+ function keyMapChanged(cm) {
+ var style = keyMap[cm.options.keyMap].style;
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
+ (style ? " cm-keymap-" + style : "");
+ }
+
+ function themeChanged(cm) {
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
+ clearCaches(cm);
+ }
+
+ function guttersChanged(cm) {
+ updateGutters(cm);
+ updateDisplay(cm, true);
+ }
+
+ function updateGutters(cm) {
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
+ removeChildren(gutters);
+ for (var i = 0; i < specs.length; ++i) {
+ var gutterClass = specs[i];
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
+ if (gutterClass == "CodeMirror-linenumbers") {
+ cm.display.lineGutter = gElt;
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
+ }
+ }
+ gutters.style.display = i ? "" : "none";
+ }
+
+ function lineLength(doc, line) {
+ if (line.height == 0) return 0;
+ var len = line.text.length, merged, cur = line;
+ while (merged = collapsedSpanAtStart(cur)) {
+ var found = merged.find();
+ cur = getLine(doc, found.from.line);
+ len += found.from.ch - found.to.ch;
+ }
+ cur = line;
+ while (merged = collapsedSpanAtEnd(cur)) {
+ var found = merged.find();
+ len -= cur.text.length - found.from.ch;
+ cur = getLine(doc, found.to.line);
+ len += cur.text.length - found.to.ch;
+ }
+ return len;
+ }
+
+ function computeMaxLength(view) {
+ view.maxLine = getLine(view.doc, 0);
+ view.maxLineLength = lineLength(view.doc, view.maxLine);
+ view.maxLineChanged = true;
+ view.doc.iter(1, view.doc.size, function(line) {
+ var len = lineLength(view.doc, line);
+ if (len > view.maxLineLength) {
+ view.maxLineLength = len;
+ view.maxLine = line;
+ }
+ });
+ }
+
+ // Make sure the gutters options contains the element
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
+ function setGuttersForLineNumbers(options) {
+ var found = false;
+ for (var i = 0; i < options.gutters.length; ++i) {
+ if (options.gutters[i] == "CodeMirror-linenumbers") {
+ if (options.lineNumbers) found = true;
+ else options.gutters.splice(i--, 1);
+ }
+ }
+ if (!found && options.lineNumbers)
+ options.gutters.push("CodeMirror-linenumbers");
+ }
+
+ // SCROLLBARS
+
+ // Re-synchronize the fake scrollbars with the actual size of the
+ // content. Optionally force a scrollTop.
+ function updateScrollbars(d /* display */, docHeight) {
+ var totalHeight = docHeight + 2 * paddingTop(d);
+ d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
+ var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
+ var needsH = d.scroller.scrollWidth > d.scroller.clientWidth;
+ var needsV = scrollHeight > d.scroller.clientHeight;
+ if (needsV) {
+ d.scrollbarV.style.display = "block";
+ d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
+ d.scrollbarV.firstChild.style.height =
+ (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
+ } else d.scrollbarV.style.display = "";
+ if (needsH) {
+ d.scrollbarH.style.display = "block";
+ d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
+ d.scrollbarH.firstChild.style.width =
+ (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
+ } else d.scrollbarH.style.display = "";
+ if (needsH && needsV) {
+ d.scrollbarFiller.style.display = "block";
+ d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
+ } else d.scrollbarFiller.style.display = "";
+
+ if (mac_geLion && scrollbarWidth(d.measure) === 0)
+ d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
+ }
+
+ function visibleLines(display, doc, viewPort) {
+ var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
+ if (typeof viewPort == "number") top = viewPort;
+ else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
+ top = Math.floor(top - paddingTop(display));
+ var bottom = Math.ceil(top + height);
+ return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
+ }
+
+ // LINE NUMBERS
+
+ function alignHorizontally(cm) {
+ var display = cm.display;
+ if (!display.alignWidgets && !display.gutters.firstChild) return;
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.view.scrollLeft;
+ var gutterW = display.gutters.offsetWidth, l = comp + "px";
+ for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
+ for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
+ }
+ display.gutters.style.left = (comp + gutterW) + "px";
+ }
+
+ function maybeUpdateLineNumberWidth(cm) {
+ if (!cm.options.lineNumbers) return false;
+ var doc = cm.view.doc, last = lineNumberFor(cm.options, doc.size - 1), display = cm.display;
+ if (last.length != display.lineNumChars) {
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
+ display.lineGutter.style.width = "";
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
+ display.lineGutter.style.width = display.lineNumWidth + "px";
+ return true;
+ }
+ return false;
+ }
+
+ function lineNumberFor(options, i) {
+ return String(options.lineNumberFormatter(i + options.firstLineNumber));
+ }
+ function compensateForHScroll(display) {
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
+ }
+
+ // DISPLAY DRAWING
+
+ function updateDisplay(cm, changes, viewPort) {
+ var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo;
+ var updated = updateDisplayInner(cm, changes, viewPort);
+ if (updated) {
+ signalLater(cm, cm, "update", cm);
+ if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
+ signalLater(cm, cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
+ }
+ updateSelection(cm);
+ updateScrollbars(cm.display, cm.view.doc.height);
+
+ return updated;
+ }
+
+ // Uses a set of changes plus the current scroll position to
+ // determine which DOM updates have to be made, and makes the
+ // updates.
+ function updateDisplayInner(cm, changes, viewPort) {
+ var display = cm.display, doc = cm.view.doc;
+ if (!display.wrapper.clientWidth) {
+ display.showingFrom = display.showingTo = display.viewOffset = 0;
+ return;
+ }
+
+ // Compute the new visible window
+ // If scrollTop is specified, use that to determine which lines
+ // to render instead of the current scrollbar position.
+ var visible = visibleLines(display, doc, viewPort);
+ // Bail out if the visible area is already rendered and nothing changed.
+ if (changes !== true && changes.length == 0 &&
+ visible.from > display.showingFrom && visible.to < display.showingTo)
+ return;
+
+ if (changes && maybeUpdateLineNumberWidth(cm))
+ changes = true;
+ display.sizer.style.marginLeft = display.scrollbarH.style.left = display.gutters.offsetWidth + "px";
+
+ // When merged lines are present, the line that needs to be
+ // redrawn might not be the one that was changed.
+ if (changes !== true && sawCollapsedSpans)
+ for (var i = 0; i < changes.length; ++i) {
+ var ch = changes[i], merged;
+ while (merged = collapsedSpanAtStart(getLine(doc, ch.from))) {
+ var from = merged.find().from.line;
+ if (ch.diff) ch.diff -= ch.from - from;
+ ch.from = from;
+ }
+ }
+
+ // Used to determine which lines need their line numbers updated
+ var positionsChangedFrom = changes === true ? 0 : Infinity;
+ if (cm.options.lineNumbers && changes && changes !== true)
+ for (var i = 0; i < changes.length; ++i)
+ if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; }
+
+ var from = Math.max(visible.from - cm.options.viewportMargin, 0);
+ var to = Math.min(doc.size, visible.to + cm.options.viewportMargin);
+ if (display.showingFrom < from && from - display.showingFrom < 20) from = display.showingFrom;
+ if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(doc.size, display.showingTo);
+ if (sawCollapsedSpans) {
+ from = lineNo(visualLine(doc, getLine(doc, from)));
+ while (to < doc.size && lineIsHidden(getLine(doc, to))) ++to;
+ }
+
+ // Create a range of theoretically intact lines, and punch holes
+ // in that using the change info.
+ var intact = changes === true ? [] :
+ computeIntact([{from: display.showingFrom, to: display.showingTo}], changes);
+ // Clip off the parts that won't be visible
+ var intactLines = 0;
+ for (var i = 0; i < intact.length; ++i) {
+ var range = intact[i];
+ if (range.from < from) range.from = from;
+ if (range.to > to) range.to = to;
+ if (range.from >= range.to) intact.splice(i--, 1);
+ else intactLines += range.to - range.from;
+ }
+ if (intactLines == to - from && from == display.showingFrom && to == display.showingTo)
+ return;
+ intact.sort(function(a, b) {return a.from - b.from;});
+
+ if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
+ patchDisplay(cm, from, to, intact, positionsChangedFrom);
+ display.lineDiv.style.display = "";
+
+ var different = from != display.showingFrom || to != display.showingTo ||
+ display.lastSizeC != display.wrapper.clientHeight;
+ // This is just a bogus formula that detects when the editor is
+ // resized or the font size changes.
+ if (different) display.lastSizeC = display.wrapper.clientHeight;
+ display.showingFrom = from; display.showingTo = to;
+ startWorker(cm, 100);
+
+ var prevBottom = display.lineDiv.offsetTop;
+ for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
+ if (ie_lt8) {
+ var bot = node.offsetTop + node.offsetHeight;
+ height = bot - prevBottom;
+ prevBottom = bot;
+ } else {
+ var box = node.getBoundingClientRect();
+ height = box.bottom - box.top;
+ }
+ var diff = node.lineObj.height - height;
+ if (height < 2) height = textHeight(display);
+ if (diff > .001 || diff < -.001)
+ updateLineHeight(node.lineObj, height);
+ }
+ display.viewOffset = heightAtLine(cm, getLine(doc, from));
+ // Position the mover div to align with the current virtual scroll position
+ display.mover.style.top = display.viewOffset + "px";
+ return true;
+ }
+
+ function computeIntact(intact, changes) {
+ for (var i = 0, l = changes.length || 0; i < l; ++i) {
+ var change = changes[i], intact2 = [], diff = change.diff || 0;
+ for (var j = 0, l2 = intact.length; j < l2; ++j) {
+ var range = intact[j];
+ if (change.to <= range.from && change.diff) {
+ intact2.push({from: range.from + diff, to: range.to + diff});
+ } else if (change.to <= range.from || change.from >= range.to) {
+ intact2.push(range);
+ } else {
+ if (change.from > range.from)
+ intact2.push({from: range.from, to: change.from});
+ if (change.to < range.to)
+ intact2.push({from: change.to + diff, to: range.to + diff});
+ }
+ }
+ intact = intact2;
+ }
+ return intact;
+ }
+
+ function getDimensions(cm) {
+ var d = cm.display, left = {}, width = {};
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
+ left[cm.options.gutters[i]] = n.offsetLeft;
+ width[cm.options.gutters[i]] = n.offsetWidth;
+ }
+ return {fixedPos: compensateForHScroll(d),
+ gutterTotalWidth: d.gutters.offsetWidth,
+ gutterLeft: left,
+ gutterWidth: width,
+ wrapperWidth: d.wrapper.clientWidth};
+ }
+
+ function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
+ var dims = getDimensions(cm);
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
+ // IE does bad things to nodes when .innerHTML = "" is used on a parent
+ // we still need widgets and markers intact to add back to the new content later
+ if (!intact.length && !ie && (!webkit || !cm.display.currentWheelTarget))
+ removeChildren(display.lineDiv);
+ var container = display.lineDiv, cur = container.firstChild;
+
+ function rm(node) {
+ var next = node.nextSibling;
+ if (webkit && mac && cm.display.currentWheelTarget == node) {
+ node.style.display = "none";
+ node.lineObj = null;
+ } else {
+ container.removeChild(node);
+ }
+ return next;
+ }
+
+ var nextIntact = intact.shift(), lineNo = from;
+ cm.view.doc.iter(from, to, function(line) {
+ if (nextIntact && nextIntact.to == lineNo) nextIntact = intact.shift();
+ if (lineIsHidden(line)) {
+ if (line.height != 0) updateLineHeight(line, 0);
+ } else if (nextIntact && nextIntact.from <= lineNo && nextIntact.to > lineNo) {
+ // This line is intact. Skip to the actual node. Update its
+ // line number if needed.
+ while (cur.lineObj != line) cur = rm(cur);
+ if (lineNumbers && updateNumbersFrom <= lineNo && cur.lineNumber)
+ setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineNo));
+ cur = cur.nextSibling;
+ } else {
+ // This line needs to be generated.
+ var lineNode = buildLineElement(cm, line, lineNo, dims);
+ container.insertBefore(lineNode, cur);
+ lineNode.lineObj = line;
+ }
+ ++lineNo;
+ });
+ while (cur) cur = rm(cur);
+ }
+
+ function buildLineElement(cm, line, lineNo, dims) {
+ var lineElement = lineContent(cm, line);
+ var markers = line.gutterMarkers, display = cm.display;
+
+ if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass &&
+ (!line.widgets || !line.widgets.length)) return lineElement;
+
+ // Lines with gutter elements or a background class need
+ // to be wrapped again, and have the extra elements added
+ // to the wrapper div
+
+ var wrap = elt("div", null, line.wrapClass, "position: relative");
+ if (cm.options.lineNumbers || markers) {
+ var gutterWrap = wrap.appendChild(elt("div", null, null, "position: absolute; left: " +
+ dims.fixedPos + "px"));
+ wrap.alignable = [gutterWrap];
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
+ wrap.lineNumber = gutterWrap.appendChild(
+ elt("div", lineNumberFor(cm.options, lineNo),
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
+ "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
+ + display.lineNumInnerWidth + "px"));
+ if (markers)
+ for (var k = 0; k < cm.options.gutters.length; ++k) {
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
+ if (found)
+ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
+ dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
+ }
+ }
+ // Kludge to make sure the styled element lies behind the selection (by z-index)
+ if (line.bgClass)
+ wrap.appendChild(elt("div", "\u00a0", line.bgClass + " CodeMirror-linebackground"));
+ wrap.appendChild(lineElement);
+ if (line.widgets)
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
+ node.widget = widget;
+ if (widget.noHScroll) {
+ (wrap.alignable || (wrap.alignable = [])).push(node);
+ var width = dims.wrapperWidth;
+ node.style.left = dims.fixedPos + "px";
+ if (!widget.coverGutter) {
+ width -= dims.gutterTotalWidth;
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
+ }
+ node.style.width = width + "px";
+ }
+ if (widget.coverGutter) {
+ node.style.zIndex = 5;
+ node.style.position = "relative";
+ if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
+ }
+ if (widget.above)
+ wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
+ else
+ wrap.appendChild(node);
+ }
+
+ if (ie_lt8) wrap.style.zIndex = 2;
+ return wrap;
+ }
+
+ // SELECTION / CURSOR
+
+ function updateSelection(cm) {
+ var display = cm.display;
+ var collapsed = posEq(cm.view.sel.from, cm.view.sel.to);
+ if (collapsed || cm.options.showCursorWhenSelecting)
+ updateSelectionCursor(cm);
+ else
+ display.cursor.style.display = display.otherCursor.style.display = "none";
+ if (!collapsed)
+ updateSelectionRange(cm);
+ else
+ display.selectionDiv.style.display = "none";
+
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
+ var headPos = cursorCoords(cm, cm.view.sel.head, "div");
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
+ display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
+ headPos.top + lineOff.top - wrapOff.top)) + "px";
+ display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
+ headPos.left + lineOff.left - wrapOff.left)) + "px";
+ }
+
+ // No selection, plain cursor
+ function updateSelectionCursor(cm) {
+ var display = cm.display, pos = cursorCoords(cm, cm.view.sel.head, "div");
+ display.cursor.style.left = pos.left + "px";
+ display.cursor.style.top = pos.top + "px";
+ display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
+ display.cursor.style.display = "";
+
+ if (pos.other) {
+ display.otherCursor.style.display = "";
+ display.otherCursor.style.left = pos.other.left + "px";
+ display.otherCursor.style.top = pos.other.top + "px";
+ display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
+ } else { display.otherCursor.style.display = "none"; }
+ }
+
+ // Highlight selection
+ function updateSelectionRange(cm) {
+ var display = cm.display, doc = cm.view.doc, sel = cm.view.sel;
+ var fragment = document.createDocumentFragment();
+ var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
+
+ function add(left, top, width, bottom) {
+ if (top < 0) top = 0;
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
+ "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
+ "px; height: " + (bottom - top) + "px"));
+ }
+
+ function drawForLine(line, fromArg, toArg, retTop) {
+ var lineObj = getLine(doc, line);
+ var lineLen = lineObj.text.length, rVal = retTop ? Infinity : -Infinity;
+ function coords(ch) {
+ return charCoords(cm, {line: line, ch: ch}, "div", lineObj);
+ }
+
+ iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
+ var leftPos = coords(dir == "rtl" ? to - 1 : from);
+ var rightPos = coords(dir == "rtl" ? from : to - 1);
+ var left = leftPos.left, right = rightPos.right;
+ if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
+ add(left, leftPos.top, null, leftPos.bottom);
+ left = pl;
+ if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
+ }
+ if (toArg == null && to == lineLen) right = clientWidth;
+ if (fromArg == null && from == 0) left = pl;
+ rVal = retTop ? Math.min(rightPos.top, rVal) : Math.max(rightPos.bottom, rVal);
+ if (left < pl + 1) left = pl;
+ add(left, rightPos.top, right - left, rightPos.bottom);
+ });
+ return rVal;
+ }
+
+ if (sel.from.line == sel.to.line) {
+ drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
+ } else {
+ var fromObj = getLine(doc, sel.from.line);
+ var cur = fromObj, merged, path = [sel.from.line, sel.from.ch], singleLine;
+ while (merged = collapsedSpanAtEnd(cur)) {
+ var found = merged.find();
+ path.push(found.from.ch, found.to.line, found.to.ch);
+ if (found.to.line == sel.to.line) {
+ path.push(sel.to.ch);
+ singleLine = true;
+ break;
+ }
+ cur = getLine(doc, found.to.line);
+ }
+
+ // This is a single, merged line
+ if (singleLine) {
+ for (var i = 0; i < path.length; i += 3)
+ drawForLine(path[i], path[i+1], path[i+2]);
+ } else {
+ var middleTop, middleBot, toObj = getLine(doc, sel.to.line);
+ if (sel.from.ch)
+ // Draw the first line of selection.
+ middleTop = drawForLine(sel.from.line, sel.from.ch, null, false);
+ else
+ // Simply include it in the middle block.
+ middleTop = heightAtLine(cm, fromObj) - display.viewOffset;
+
+ if (!sel.to.ch)
+ middleBot = heightAtLine(cm, toObj) - display.viewOffset;
+ else
+ middleBot = drawForLine(sel.to.line, collapsedSpanAtStart(toObj) ? null : 0, sel.to.ch, true);
+
+ if (middleTop < middleBot) add(pl, middleTop, null, middleBot);
+ }
+ }
+
+ removeChildrenAndAdd(display.selectionDiv, fragment);
+ display.selectionDiv.style.display = "";
+ }
+
+ // Cursor-blinking
+ function restartBlink(cm) {
+ var display = cm.display;
+ clearInterval(display.blinker);
+ var on = true;
+ display.cursor.style.visibility = display.otherCursor.style.visibility = "";
+ display.blinker = setInterval(function() {
+ if (!display.cursor.offsetHeight) return;
+ display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
+ }, cm.options.cursorBlinkRate);
+ }
+
+ // HIGHLIGHT WORKER
+
+ function startWorker(cm, time) {
+ if (cm.view.frontier < cm.display.showingTo)
+ cm.view.highlight.set(time, bind(highlightWorker, cm));
+ }
+
+ function highlightWorker(cm) {
+ var view = cm.view, doc = view.doc;
+ if (view.frontier >= cm.display.showingTo) return;
+ var end = +new Date + cm.options.workTime;
+ var state = copyState(view.mode, getStateBefore(cm, view.frontier));
+ var changed = [], prevChange;
+ doc.iter(view.frontier, Math.min(doc.size, cm.display.showingTo + 500), function(line) {
+ if (view.frontier >= cm.display.showingFrom) { // Visible
+ if (highlightLine(cm, line, state) && view.frontier >= cm.display.showingFrom) {
+ if (prevChange && prevChange.end == view.frontier) prevChange.end++;
+ else changed.push(prevChange = {start: view.frontier, end: view.frontier + 1});
+ }
+ line.stateAfter = copyState(view.mode, state);
+ } else {
+ processLine(cm, line, state);
+ line.stateAfter = view.frontier % 5 == 0 ? copyState(view.mode, state) : null;
+ }
+ ++view.frontier;
+ if (+new Date > end) {
+ startWorker(cm, cm.options.workDelay);
+ return true;
+ }
+ });
+ if (changed.length)
+ operation(cm, function() {
+ for (var i = 0; i < changed.length; ++i)
+ regChange(this, changed[i].start, changed[i].end);
+ })();
+ }
+
+ // Finds the line to start with when starting a parse. Tries to
+ // find a line with a stateAfter, so that it can start with a
+ // valid state. If that fails, it returns the line with the
+ // smallest indentation, which tends to need the least context to
+ // parse correctly.
+ function findStartLine(cm, n) {
+ var minindent, minline, doc = cm.view.doc;
+ for (var search = n, lim = n - 100; search > lim; --search) {
+ if (search == 0) return 0;
+ var line = getLine(doc, search-1);
+ if (line.stateAfter) return search;
+ var indented = countColumn(line.text, null, cm.options.tabSize);
+ if (minline == null || minindent > indented) {
+ minline = search - 1;
+ minindent = indented;
+ }
+ }
+ return minline;
+ }
+
+ function getStateBefore(cm, n) {
+ var view = cm.view;
+ var pos = findStartLine(cm, n), state = pos && getLine(view.doc, pos-1).stateAfter;
+ if (!state) state = startState(view.mode);
+ else state = copyState(view.mode, state);
+ view.doc.iter(pos, n, function(line) {
+ processLine(cm, line, state);
+ var save = pos == n - 1 || pos % 5 == 0 || pos >= view.showingFrom && pos < view.showingTo;
+ line.stateAfter = save ? copyState(view.mode, state) : null;
+ ++pos;
+ });
+ return state;
+ }
+
+ // POSITION MEASUREMENT
+
+ function paddingTop(display) {return display.lineSpace.offsetTop;}
+ function paddingLeft(display) {
+ var e = removeChildrenAndAdd(display.measure, elt("pre")).appendChild(elt("span", "x"));
+ return e.offsetLeft;
+ }
+
+ function measureChar(cm, line, ch, data) {
+ var data = data || measureLine(cm, line), dir = -1;
+ for (var pos = ch;; pos += dir) {
+ var r = data[pos];
+ if (r) break;
+ if (dir < 0 && pos == 0) dir = 1;
+ }
+ return {left: pos < ch ? r.right : r.left,
+ right: pos > ch ? r.left : r.right,
+ top: r.top, bottom: r.bottom};
+ }
+
+ function measureLine(cm, line) {
+ // First look in the cache
+ var display = cm.display, cache = cm.display.measureLineCache;
+ for (var i = 0; i < cache.length; ++i) {
+ var memo = cache[i];
+ if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
+ display.scroller.clientWidth == memo.width)
+ return memo.measure;
+ }
+
+ var measure = measureLineInner(cm, line);
+ // Store result in the cache
+ var memo = {text: line.text, width: display.scroller.clientWidth,
+ markedSpans: line.markedSpans, measure: measure};
+ if (cache.length == 16) cache[++display.measureLineCachePos % 16] = memo;
+ else cache.push(memo);
+ return measure;
+ }
+
+ function measureLineInner(cm, line) {
+ var display = cm.display, measure = emptyArray(line.text.length);
+ var pre = lineContent(cm, line, measure);
+
+ // IE does not cache element positions of inline elements between
+ // calls to getBoundingClientRect. This makes the loop below,
+ // which gathers the positions of all the characters on the line,
+ // do an amount of layout work quadratic to the number of
+ // characters. When line wrapping is off, we try to improve things
+ // by first subdividing the line into a bunch of inline blocks, so
+ // that IE can reuse most of the layout information from caches
+ // for those blocks. This does interfere with line wrapping, so it
+ // doesn't work when wrapping is on, but in that case the
+ // situation is slightly better, since IE does cache line-wrapping
+ // information and only recomputes per-line.
+ if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
+ var fragment = document.createDocumentFragment();
+ var chunk = 10, n = pre.childNodes.length;
+ for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
+ var wrap = elt("div", null, null, "display: inline-block");
+ for (var j = 0; j < chunk && n; ++j) {
+ wrap.appendChild(pre.firstChild);
+ --n;
+ }
+ fragment.appendChild(wrap);
+ }
+ pre.appendChild(fragment);
+ }
+
+ removeChildrenAndAdd(display.measure, pre);
+
+ var outer = display.lineDiv.getBoundingClientRect();
+ var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
+ for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
+ var size = cur.getBoundingClientRect();
+ var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot);
+ for (var j = 0; j < vranges.length; j += 2) {
+ var rtop = vranges[j], rbot = vranges[j+1];
+ if (rtop > bot || rbot < top) continue;
+ if (rtop <= top && rbot >= bot ||
+ top <= rtop && bot >= rbot ||
+ Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
+ vranges[j] = Math.min(top, rtop);
+ vranges[j+1] = Math.max(bot, rbot);
+ break;
+ }
+ }
+ if (j == vranges.length) vranges.push(top, bot);
+ data[i] = {left: size.left - outer.left, right: size.right - outer.left, top: j};
+ }
+ for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
+ var vr = cur.top;
+ cur.top = vranges[vr]; cur.bottom = vranges[vr+1];
+ }
+ return data;
+ }
+
+ function clearCaches(cm) {
+ cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
+ cm.view.maxLineChanged = true;
+ }
+
+ // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
+ function intoCoordSystem(cm, lineObj, rect, context) {
+ if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
+ var size = lineObj.widgets[i].node.offsetHeight;
+ rect.top += size; rect.bottom += size;
+ }
+ if (context == "line") return rect;
+ if (!context) context = "local";
+ var yOff = heightAtLine(cm, lineObj);
+ if (context != "local") yOff -= cm.display.viewOffset;
+ if (context == "page") {
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
+ yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop);
+ var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft);
+ rect.left += xOff; rect.right += xOff;
+ }
+ rect.top += yOff; rect.bottom += yOff;
+ return rect;
+ }
+
+ function charCoords(cm, pos, context, lineObj) {
+ if (!lineObj) lineObj = getLine(cm.view.doc, pos.line);
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch), context);
+ }
+
+ function cursorCoords(cm, pos, context, lineObj, measurement) {
+ lineObj = lineObj || getLine(cm.view.doc, pos.line);
+ if (!measurement) measurement = measureLine(cm, lineObj);
+ function get(ch, right) {
+ var m = measureChar(cm, lineObj, ch, measurement);
+ if (right) m.left = m.right; else m.right = m.left;
+ return intoCoordSystem(cm, lineObj, m, context);
+ }
+ var order = getOrder(lineObj), ch = pos.ch;
+ if (!order) return get(ch);
+ var main, other, linedir = order[0].level;
+ for (var i = 0; i < order.length; ++i) {
+ var part = order[i], rtl = part.level % 2, nb, here;
+ if (part.from < ch && part.to > ch) return get(ch, rtl);
+ var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to;
+ if (left == ch) {
+ // Opera and IE return bogus offsets and widths for edges
+ // where the direction flips, but only for the side with the
+ // lower level. So we try to use the side with the higher
+ // level.
+ if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true);
+ else here = get(rtl && part.from != part.to ? ch - 1 : ch);
+ if (rtl == linedir) main = here; else other = here;
+ } else if (right == ch) {
+ var nb = i < order.length - 1 && order[i+1];
+ if (!rtl && nb && nb.from == nb.to) continue;
+ if (nb && part.level < nb.level) here = get(nb.level % 2 ? nb.to - 1 : nb.from);
+ else here = get(rtl ? ch : ch - 1, true);
+ if (rtl == linedir) main = here; else other = here;
+ }
+ }
+ if (linedir && !ch) other = get(order[0].to - 1);
+ if (!main) return other;
+ if (other) main.other = other;
+ return main;
+ }
+
+ // Coords must be lineSpace-local
+ function coordsChar(cm, x, y) {
+ var doc = cm.view.doc;
+ y += cm.display.viewOffset;
+ if (y < 0) return {line: 0, ch: 0, outside: true};
+ var lineNo = lineAtHeight(doc, y);
+ if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length};
+ if (x < 0) x = 0;
+
+ for (;;) {
+ var lineObj = getLine(doc, lineNo);
+ var found = coordsCharInner(cm, lineObj, lineNo, x, y);
+ var merged = collapsedSpanAtEnd(lineObj);
+ if (merged && found.ch == lineRight(lineObj))
+ lineNo = merged.find().to.line;
+ else
+ return found;
+ }
+ }
+
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
+ var innerOff = y - heightAtLine(cm, lineObj);
+ var wrongLine = false, cWidth = cm.display.wrapper.clientWidth;
+ var measurement = measureLine(cm, lineObj);
+
+ function getX(ch) {
+ var sp = cursorCoords(cm, {line: lineNo, ch: ch}, "line",
+ lineObj, measurement);
+ wrongLine = true;
+ if (innerOff > sp.bottom) return Math.max(0, sp.left - cWidth);
+ else if (innerOff < sp.top) return sp.left + cWidth;
+ else wrongLine = false;
+ return sp.left;
+ }
+
+ var bidi = getOrder(lineObj), dist = lineObj.text.length;
+ var from = lineLeft(lineObj), to = lineRight(lineObj);
+ var fromX = paddingLeft(cm.display), toX = getX(to);
+
+ if (x > toX) return {line: lineNo, ch: to, outside: wrongLine};
+ // Do a binary search between these bounds.
+ for (;;) {
+ if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
+ var after = x - fromX < toX - x, ch = after ? from : to;
+ while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
+ return {line: lineNo, ch: ch, after: after, outside: wrongLine};
+ }
+ var step = Math.ceil(dist / 2), middle = from + step;
+ if (bidi) {
+ middle = from;
+ for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
+ }
+ var middleX = getX(middle);
+ if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; dist -= step;}
+ else {from = middle; fromX = middleX; dist = step;}
+ }
+ }
+
+ var measureText;
+ function textHeight(display) {
+ if (display.cachedTextHeight != null) return display.cachedTextHeight;
+ if (measureText == null) {
+ measureText = elt("pre");
+ // Measure a bunch of lines, for browsers that compute
+ // fractional heights.
+ for (var i = 0; i < 49; ++i) {
+ measureText.appendChild(document.createTextNode("x"));
+ measureText.appendChild(elt("br"));
+ }
+ measureText.appendChild(document.createTextNode("x"));
+ }
+ removeChildrenAndAdd(display.measure, measureText);
+ var height = measureText.offsetHeight / 50;
+ if (height > 3) display.cachedTextHeight = height;
+ removeChildren(display.measure);
+ return height || 1;
+ }
+
+ function charWidth(display) {
+ if (display.cachedCharWidth != null) return display.cachedCharWidth;
+ var anchor = elt("span", "x");
+ var pre = elt("pre", [anchor]);
+ removeChildrenAndAdd(display.measure, pre);
+ var width = anchor.offsetWidth;
+ if (width > 2) display.cachedCharWidth = width;
+ return width || 10;
+ }
+
+ // OPERATIONS
+
+ // Operations are used to wrap changes in such a way that each
+ // change won't have to update the cursor and display (which would
+ // be awkward, slow, and error-prone), but instead updates are
+ // batched and then all combined and executed at once.
+
+ function startOperation(cm) {
+ if (cm.curOp) ++cm.curOp.depth;
+ else cm.curOp = {
+ // Nested operations delay update until the outermost one
+ // finishes.
+ depth: 1,
+ // An array of ranges of lines that have to be updated. See
+ // updateDisplay.
+ changes: [],
+ delayedCallbacks: [],
+ updateInput: null,
+ userSelChange: null,
+ textChanged: null,
+ selectionChanged: false,
+ updateMaxLine: false,
+ id: ++cm.nextOpId
+ };
+ }
+
+ function endOperation(cm) {
+ var op = cm.curOp;
+ if (--op.depth) return;
+ cm.curOp = null;
+ var view = cm.view, display = cm.display;
+ if (op.updateMaxLine) computeMaxLength(view);
+ if (view.maxLineChanged && !cm.options.lineWrapping) {
+ var width = measureChar(cm, view.maxLine, view.maxLine.text.length).right;
+ display.sizer.style.minWidth = (width + 3 + scrollerCutOff) + "px";
+ view.maxLineChanged = false;
+ }
+ var newScrollPos, updated;
+ if (op.selectionChanged) {
+ var coords = cursorCoords(cm, view.sel.head);
+ newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
+ }
+ if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null)
+ updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop);
+ if (!updated && op.selectionChanged) updateSelection(cm);
+ if (newScrollPos) scrollCursorIntoView(cm);
+ if (op.selectionChanged) restartBlink(cm);
+
+ if (view.focused && op.updateInput)
+ resetInput(cm, op.userSelChange);
+
+ if (op.textChanged)
+ signal(cm, "change", cm, op.textChanged);
+ if (op.selectionChanged) signal(cm, "cursorActivity", cm);
+ for (var i = 0; i < op.delayedCallbacks.length; ++i) op.delayedCallbacks[i](cm);
+ }
+
+ // Wraps a function in an operation. Returns the wrapped function.
+ function operation(cm1, f) {
+ return function() {
+ var cm = cm1 || this;
+ startOperation(cm);
+ try {var result = f.apply(cm, arguments);}
+ finally {endOperation(cm);}
+ return result;
+ };
+ }
+
+ function regChange(cm, from, to, lendiff) {
+ cm.curOp.changes.push({from: from, to: to, diff: lendiff});
+ }
+
+ // INPUT HANDLING
+
+ function slowPoll(cm) {
+ if (cm.view.pollingFast) return;
+ cm.display.poll.set(cm.options.pollInterval, function() {
+ readInput(cm);
+ if (cm.view.focused) slowPoll(cm);
+ });
+ }
+
+ function fastPoll(cm) {
+ var missed = false;
+ cm.display.pollingFast = true;
+ function p() {
+ var changed = readInput(cm);
+ if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
+ else {cm.display.pollingFast = false; slowPoll(cm);}
+ }
+ cm.display.poll.set(20, p);
+ }
+
+ // prevInput is a hack to work with IME. If we reset the textarea
+ // on every change, that breaks IME. So we look for changes
+ // compared to the previous content instead. (Modern browsers have
+ // events that indicate IME taking place, but these are not widely
+ // supported or compatible enough yet to rely on.)
+ function readInput(cm) {
+ var input = cm.display.input, prevInput = cm.display.prevInput, view = cm.view, sel = view.sel;
+ if (!view.focused || hasSelection(input) || isReadOnly(cm)) return false;
+ var text = input.value;
+ if (text == prevInput && posEq(sel.from, sel.to)) return false;
+ startOperation(cm);
+ view.sel.shift = false;
+ var same = 0, l = Math.min(prevInput.length, text.length);
+ while (same < l && prevInput[same] == text[same]) ++same;
+ var from = sel.from, to = sel.to;
+ if (same < prevInput.length)
+ from = {line: from.line, ch: from.ch - (prevInput.length - same)};
+ else if (view.overwrite && posEq(from, to) && !cm.display.pasteIncoming)
+ to = {line: to.line, ch: Math.min(getLine(cm.view.doc, to.line).text.length, to.ch + (text.length - same))};
+ var updateInput = cm.curOp.updateInput;
+ updateDoc(cm, from, to, splitLines(text.slice(same)), "end",
+ cm.display.pasteIncoming ? "paste" : "input", {from: from, to: to});
+ cm.curOp.updateInput = updateInput;
+ if (text.length > 1000) input.value = cm.display.prevInput = "";
+ else cm.display.prevInput = text;
+ endOperation(cm);
+ cm.display.pasteIncoming = false;
+ return true;
+ }
+
+ function resetInput(cm, user) {
+ var view = cm.view, minimal, selected;
+ if (!posEq(view.sel.from, view.sel.to)) {
+ cm.display.prevInput = "";
+ minimal = hasCopyEvent &&
+ (view.sel.to.line - view.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
+ if (minimal) cm.display.input.value = "-";
+ else cm.display.input.value = selected || cm.getSelection();
+ if (view.focused) selectInput(cm.display.input);
+ } else if (user) cm.display.prevInput = cm.display.input.value = "";
+ cm.display.inaccurateSelection = minimal;
+ }
+
+ function focusInput(cm) {
+ if (cm.options.readOnly != "nocursor" && (ie || document.activeElement != cm.display.input))
+ cm.display.input.focus();
+ }
+
+ function isReadOnly(cm) {
+ return cm.options.readOnly || cm.view.cantEdit;
+ }
+
+ // EVENT HANDLERS
+
+ function registerEventHandlers(cm) {
+ var d = cm.display;
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
+ on(d.scroller, "dblclick", operation(cm, e_preventDefault));
+ on(d.lineSpace, "selectstart", function(e) {
+ if (!mouseEventInWidget(d, e)) e_preventDefault(e);
+ });
+ // Gecko browsers fire contextmenu *after* opening the menu, at
+ // which point we can't mess with it anymore. Context menu is
+ // handled in onMouseDown for Gecko.
+ if (!gecko) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
+
+ on(d.scroller, "scroll", function() {
+ setScrollTop(cm, d.scroller.scrollTop);
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
+ signal(cm, "scroll", cm);
+ });
+ on(d.scrollbarV, "scroll", function() {
+ setScrollTop(cm, d.scrollbarV.scrollTop);
+ });
+ on(d.scrollbarH, "scroll", function() {
+ setScrollLeft(cm, d.scrollbarH.scrollLeft);
+ });
+
+ on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
+ on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
+
+ function reFocus() { if (cm.view.focused) setTimeout(bind(focusInput, cm), 0); }
+ on(d.scrollbarH, "mousedown", reFocus);
+ on(d.scrollbarV, "mousedown", reFocus);
+ // Prevent wrapper from ever scrolling
+ on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
+ on(window, "resize", function resizeHandler() {
+ // Might be a text scaling operation, clear size caches.
+ d.cachedCharWidth = d.cachedTextHeight = null;
+ clearCaches(cm);
+ if (d.wrapper.parentNode) updateDisplay(cm, true);
+ else off(window, "resize", resizeHandler);
+ });
+
+ on(d.input, "keyup", operation(cm, function(e) {
+ if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
+ if (e_prop(e, "keyCode") == 16) cm.view.sel.shift = false;
+ }));
+ on(d.input, "input", bind(fastPoll, cm));
+ on(d.input, "keydown", operation(cm, onKeyDown));
+ on(d.input, "keypress", operation(cm, onKeyPress));
+ on(d.input, "focus", bind(onFocus, cm));
+ on(d.input, "blur", bind(onBlur, cm));
+
+ function drag_(e) {
+ if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
+ e_stop(e);
+ }
+ if (cm.options.dragDrop) {
+ on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
+ on(d.scroller, "dragenter", drag_);
+ on(d.scroller, "dragover", drag_);
+ on(d.scroller, "drop", operation(cm, onDrop));
+ }
+ on(d.scroller, "paste", function(){focusInput(cm); fastPoll(cm);});
+ on(d.input, "paste", function() {
+ d.pasteIncoming = true;
+ fastPoll(cm);
+ });
+
+ function prepareCopy() {
+ if (d.inaccurateSelection) {
+ d.prevInput = "";
+ d.inaccurateSelection = false;
+ d.input.value = cm.getSelection();
+ selectInput(d.input);
+ }
+ }
+ on(d.input, "cut", prepareCopy);
+ on(d.input, "copy", prepareCopy);
+
+ // Needed to handle Tab key in KHTML
+ if (khtml) on(d.sizer, "mouseup", function() {
+ if (document.activeElement == d.input) d.input.blur();
+ focusInput(cm);
+ });
+ }
+
+ function mouseEventInWidget(display, e) {
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode)
+ if (/\bCodeMirror-(?:line)?widget\b/.test(n.className) ||
+ n.parentNode == display.sizer && n != display.mover) return true;
+ }
+
+ function posFromMouse(cm, e, liberal) {
+ var display = cm.display;
+ if (!liberal) {
+ var target = e_target(e);
+ if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
+ target == display.scrollbarV || target == display.scrollbarV.firstChild ||
+ target == display.scrollbarFiller) return null;
+ }
+ var x, y, space = display.lineSpace.getBoundingClientRect();
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
+ try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
+ return coordsChar(cm, x - space.left, y - space.top);
+ }
+
+ var lastClick, lastDoubleClick;
+ function onMouseDown(e) {
+ var cm = this, display = cm.display, view = cm.view, sel = view.sel, doc = view.doc;
+ sel.shift = e_prop(e, "shiftKey");
+
+ if (mouseEventInWidget(display, e)) {
+ if (!webkit) {
+ display.scroller.draggable = false;
+ setTimeout(function(){display.scroller.draggable = true;}, 100);
+ }
+ return;
+ }
+ if (clickInGutter(cm, e)) return;
+ var start = posFromMouse(cm, e);
+
+ switch (e_button(e)) {
+ case 3:
+ if (gecko) onContextMenu.call(cm, cm, e);
+ return;
+ case 2:
+ if (start) extendSelection(cm, start);
+ setTimeout(bind(focusInput, cm), 20);
+ e_preventDefault(e);
+ return;
+ }
+ // For button 1, if it was clicked inside the editor
+ // (posFromMouse returning non-null), we have to adjust the
+ // selection.
+ if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
+
+ if (!view.focused) onFocus(cm);
+
+ var now = +new Date, type = "single";
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
+ type = "triple";
+ e_preventDefault(e);
+ setTimeout(bind(focusInput, cm), 20);
+ selectLine(cm, start.line);
+ } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
+ type = "double";
+ lastDoubleClick = {time: now, pos: start};
+ e_preventDefault(e);
+ var word = findWordAt(getLine(doc, start.line).text, start);
+ extendSelection(cm, word.from, word.to);
+ } else { lastClick = {time: now, pos: start}; }
+
+ var last = start;
+ if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
+ !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
+ var dragEnd = operation(cm, function(e2) {
+ if (webkit) display.scroller.draggable = false;
+ view.draggingText = false;
+ off(document, "mouseup", dragEnd);
+ off(display.scroller, "drop", dragEnd);
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
+ e_preventDefault(e2);
+ extendSelection(cm, start);
+ focusInput(cm);
+ }
+ });
+ // Let the drag handler handle this.
+ if (webkit) display.scroller.draggable = true;
+ view.draggingText = dragEnd;
+ // IE's approach to draggable
+ if (display.scroller.dragDrop) display.scroller.dragDrop();
+ on(document, "mouseup", dragEnd);
+ on(display.scroller, "drop", dragEnd);
+ return;
+ }
+ e_preventDefault(e);
+ if (type == "single") extendSelection(cm, clipPos(doc, start));
+
+ var startstart = sel.from, startend = sel.to;
+
+ function doSelect(cur) {
+ if (type == "single") {
+ extendSelection(cm, clipPos(doc, start), cur);
+ return;
+ }
+
+ startstart = clipPos(doc, startstart);
+ startend = clipPos(doc, startend);
+ if (type == "double") {
+ var word = findWordAt(getLine(doc, cur.line).text, cur);
+ if (posLess(cur, startstart)) extendSelection(cm, word.from, startend);
+ else extendSelection(cm, startstart, word.to);
+ } else if (type == "triple") {
+ if (posLess(cur, startstart)) extendSelection(cm, startend, clipPos(doc, {line: cur.line, ch: 0}));
+ else extendSelection(cm, startstart, clipPos(doc, {line: cur.line + 1, ch: 0}));
+ }
+ }
+
+ var editorSize = display.wrapper.getBoundingClientRect();
+ // Used to ensure timeout re-tries don't fire when another extend
+ // happened in the meantime (clearTimeout isn't reliable -- at
+ // least on Chrome, the timeouts still happen even when cleared,
+ // if the clear happens after their scheduled firing time).
+ var counter = 0;
+
+ function extend(e) {
+ var curCount = ++counter;
+ var cur = posFromMouse(cm, e, true);
+ if (!cur) return;
+ if (!posEq(cur, last)) {
+ if (!view.focused) onFocus(cm);
+ last = cur;
+ doSelect(cur);
+ var visible = visibleLines(display, doc);
+ if (cur.line >= visible.to || cur.line < visible.from)
+ setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
+ } else {
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
+ if (outside) setTimeout(operation(cm, function() {
+ if (counter != curCount) return;
+ display.scroller.scrollTop += outside;
+ extend(e);
+ }), 50);
+ }
+ }
+
+ function done(e) {
+ counter = Infinity;
+ var cur = posFromMouse(cm, e);
+ if (cur) doSelect(cur);
+ e_preventDefault(e);
+ focusInput(cm);
+ off(document, "mousemove", move);
+ off(document, "mouseup", up);
+ }
+
+ var move = operation(cm, function(e) {
+ if (!ie && !e_button(e)) done(e);
+ else extend(e);
+ });
+ var up = operation(cm, done);
+ on(document, "mousemove", move);
+ on(document, "mouseup", up);
+ }
+
+ function onDrop(e) {
+ var cm = this;
+ if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
+ e_preventDefault(e);
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
+ if (!pos || isReadOnly(cm)) return;
+ if (files && files.length && window.FileReader && window.File) {
+ var n = files.length, text = Array(n), read = 0;
+ var loadFile = function(file, i) {
+ var reader = new FileReader;
+ reader.onload = function() {
+ text[i] = reader.result;
+ if (++read == n) {
+ pos = clipPos(cm.view.doc, pos);
+ operation(cm, function() {
+ var end = replaceRange(cm, text.join(""), pos, pos, "paste");
+ setSelection(cm, pos, end);
+ })();
+ }
+ };
+ reader.readAsText(file);
+ };
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
+ } else {
+ // Don't do a replace if the drop happened inside of the selected text.
+ if (cm.view.draggingText && !(posLess(pos, cm.view.sel.from) || posLess(cm.view.sel.to, pos))) {
+ cm.view.draggingText(e);
+ if (ie) setTimeout(bind(focusInput, cm), 50);
+ return;
+ }
+ try {
+ var text = e.dataTransfer.getData("Text");
+ if (text) {
+ var curFrom = cm.view.sel.from, curTo = cm.view.sel.to;
+ setSelection(cm, pos, pos);
+ if (cm.view.draggingText) replaceRange(cm, "", curFrom, curTo, "paste");
+ cm.replaceSelection(text, null, "paste");
+ focusInput(cm);
+ onFocus(cm);
+ }
+ }
+ catch(e){}
+ }
+ }
+
+ function clickInGutter(cm, e) {
+ var display = cm.display;
+ try { var mX = e.clientX, mY = e.clientY; }
+ catch(e) { return false; }
+
+ if (mX >= Math.floor(display.gutters.getBoundingClientRect().right)) return false;
+ e_preventDefault(e);
+ if (!hasHandler(cm, "gutterClick")) return true;
+
+ var lineBox = display.lineDiv.getBoundingClientRect();
+ if (mY > lineBox.bottom) return true;
+ mY -= lineBox.top - display.viewOffset;
+
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
+ var g = display.gutters.childNodes[i];
+ if (g && g.getBoundingClientRect().right >= mX) {
+ var line = lineAtHeight(cm.view.doc, mY);
+ var gutter = cm.options.gutters[i];
+ signalLater(cm, cm, "gutterClick", cm, line, gutter, e);
+ break;
+ }
+ }
+ return true;
+ }
+
+ function onDragStart(cm, e) {
+ var txt = cm.getSelection();
+ e.dataTransfer.setData("Text", txt);
+
+ // Use dummy image instead of default browsers image.
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
+ if (e.dataTransfer.setDragImage && !safari)
+ e.dataTransfer.setDragImage(elt('img'), 0, 0);
+ }
+
+ function setScrollTop(cm, val) {
+ if (Math.abs(cm.view.scrollTop - val) < 2) return;
+ cm.view.scrollTop = val;
+ if (!gecko) updateDisplay(cm, [], val);
+ if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
+ if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
+ if (gecko) updateDisplay(cm, []);
+ }
+ function setScrollLeft(cm, val, isScroller) {
+ if (isScroller ? val == cm.view.scrollLeft : Math.abs(cm.view.scrollLeft - val) < 2) return;
+ cm.view.scrollLeft = val;
+ alignHorizontally(cm);
+ if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
+ if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
+ }
+
+ // Since the delta values reported on mouse wheel events are
+ // unstandardized between browsers and even browser versions, and
+ // generally horribly unpredictable, this code starts by measuring
+ // the scroll effect that the first few mouse wheel events have,
+ // and, from that, detects the way it can convert deltas to pixel
+ // offsets afterwards.
+ //
+ // The reason we want to know the amount a wheel event will scroll
+ // is that it gives us a chance to update the display before the
+ // actual scrolling happens, reducing flickering.
+
+ var wheelSamples = 0, wheelDX, wheelDY, wheelStartX, wheelStartY, wheelPixelsPerUnit = null;
+ // Fill in a browser-detected starting value on browsers where we
+ // know one. These don't have to be accurate -- the result of them
+ // being wrong would just be a slight flicker on the first wheel
+ // scroll (if it is large enough).
+ if (ie) wheelPixelsPerUnit = -.53;
+ else if (gecko) wheelPixelsPerUnit = 15;
+ else if (chrome) wheelPixelsPerUnit = -.7;
+ else if (safari) wheelPixelsPerUnit = -1/3;
+
+ function onScrollWheel(cm, e) {
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
+ else if (dy == null) dy = e.wheelDelta;
+
+ // Webkit browsers on OS X abort momentum scrolls when the target
+ // of the scroll event is removed from the scrollable element.
+ // This hack (see related code in patchDisplay) makes sure the
+ // element is kept around.
+ if (dy && mac && webkit) {
+ for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
+ if (cur.lineObj) {
+ cm.display.currentWheelTarget = cur;
+ break;
+ }
+ }
+ }
+
+ var scroll = cm.display.scroller;
+ // On some browsers, horizontal scrolling will cause redraws to
+ // happen before the gutter has been realigned, causing it to
+ // wriggle around in a most unseemly way. When we have an
+ // estimated pixels/delta value, we just handle horizontal
+ // scrolling entirely here. It'll be slightly off from native, but
+ // better than glitching out.
+ if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
+ if (dy)
+ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
+ setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
+ e_preventDefault(e);
+ wheelStartX = null; // Abort measurement, if in progress
+ return;
+ }
+
+ if (dy && wheelPixelsPerUnit != null) {
+ var pixels = dy * wheelPixelsPerUnit;
+ var top = cm.view.scrollTop, bot = top + cm.display.wrapper.clientHeight;
+ if (pixels < 0) top = Math.max(0, top + pixels - 50);
+ else bot = Math.min(cm.view.doc.height, bot + pixels + 50);
+ updateDisplay(cm, [], {top: top, bottom: bot});
+ }
+
+ if (wheelSamples < 20) {
+ if (wheelStartX == null) {
+ wheelStartX = scroll.scrollLeft; wheelStartY = scroll.scrollTop;
+ wheelDX = dx; wheelDY = dy;
+ setTimeout(function() {
+ if (wheelStartX == null) return;
+ var movedX = scroll.scrollLeft - wheelStartX;
+ var movedY = scroll.scrollTop - wheelStartY;
+ var sample = (movedY && wheelDY && movedY / wheelDY) ||
+ (movedX && wheelDX && movedX / wheelDX);
+ wheelStartX = wheelStartY = null;
+ if (!sample) return;
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
+ ++wheelSamples;
+ }, 200);
+ } else {
+ wheelDX += dx; wheelDY += dy;
+ }
+ }
+ }
+
+ function doHandleBinding(cm, bound, dropShift) {
+ if (typeof bound == "string") {
+ bound = commands[bound];
+ if (!bound) return false;
+ }
+ // Ensure previous input has been read, so that the handler sees a
+ // consistent view of the document
+ if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
+ var view = cm.view, prevShift = view.sel.shift;
+ try {
+ if (isReadOnly(cm)) view.suppressEdits = true;
+ if (dropShift) view.sel.shift = false;
+ bound(cm);
+ } catch(e) {
+ if (e != Pass) throw e;
+ return false;
+ } finally {
+ view.sel.shift = prevShift;
+ view.suppressEdits = false;
+ }
+ return true;
+ }
+
+ function allKeyMaps(cm) {
+ var maps = cm.view.keyMaps.slice(0);
+ maps.push(cm.options.keyMap);
+ if (cm.options.extraKeys) maps.unshift(cm.options.extraKeys);
+ return maps;
+ }
+
+ var maybeTransition;
+ function handleKeyBinding(cm, e) {
+ // Handle auto keymap transitions
+ var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
+ clearTimeout(maybeTransition);
+ if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
+ if (getKeyMap(cm.options.keyMap) == startMap)
+ cm.options.keyMap = (next.call ? next.call(null, cm) : next);
+ }, 50);
+
+ var name = keyNames[e_prop(e, "keyCode")], handled = false;
+ var flipCtrlCmd = mac && (opera || qtwebkit);
+ if (name == null || e.altGraphKey) return false;
+ if (e_prop(e, "altKey")) name = "Alt-" + name;
+ if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name;
+ if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name;
+
+ var stopped = false;
+ function stop() { stopped = true; }
+ var keymaps = allKeyMaps(cm);
+
+ if (e_prop(e, "shiftKey")) {
+ handled = lookupKey("Shift-" + name, keymaps,
+ function(b) {return doHandleBinding(cm, b, true);}, stop)
+ || lookupKey(name, keymaps, function(b) {
+ if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(cm, b);
+ }, stop);
+ } else {
+ handled = lookupKey(name, keymaps,
+ function(b) { return doHandleBinding(cm, b); }, stop);
+ }
+ if (stopped) handled = false;
+ if (handled) {
+ e_preventDefault(e);
+ restartBlink(cm);
+ if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
+ }
+ return handled;
+ }
+
+ function handleCharBinding(cm, e, ch) {
+ var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
+ function(b) { return doHandleBinding(cm, b, true); });
+ if (handled) {
+ e_preventDefault(e);
+ restartBlink(cm);
+ }
+ return handled;
+ }
+
+ var lastStoppedKey = null;
+ function onKeyDown(e) {
+ var cm = this;
+ if (!cm.view.focused) onFocus(cm);
+ if (ie && e.keyCode == 27) { e.returnValue = false; }
+ if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
+ var code = e_prop(e, "keyCode");
+ // IE does strange things with escape.
+ cm.view.sel.shift = code == 16 || e_prop(e, "shiftKey");
+ // First give onKeyEvent option a chance to handle this.
+ var handled = handleKeyBinding(cm, e);
+ if (opera) {
+ lastStoppedKey = handled ? code : null;
+ // Opera has no cut event... we try to at least catch the key combo
+ if (!handled && code == 88 && !hasCopyEvent && e_prop(e, mac ? "metaKey" : "ctrlKey"))
+ cm.replaceSelection("");
+ }
+ }
+
+ function onKeyPress(e) {
+ var cm = this;
+ if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
+ var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
+ if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
+ if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
+ if (this.options.electricChars && this.view.mode.electricChars &&
+ this.options.smartIndent && !isReadOnly(this) &&
+ this.view.mode.electricChars.indexOf(ch) > -1)
+ setTimeout(operation(cm, function() {indentLine(cm, cm.view.sel.to.line, "smart");}), 75);
+ if (handleCharBinding(cm, e, ch)) return;
+ fastPoll(cm);
+ }
+
+ function onFocus(cm) {
+ if (cm.options.readOnly == "nocursor") return;
+ if (!cm.view.focused) {
+ signal(cm, "focus", cm);
+ cm.view.focused = true;
+ if (cm.display.scroller.className.search(/\bCodeMirror-focused\b/) == -1)
+ cm.display.scroller.className += " CodeMirror-focused";
+ resetInput(cm, true);
+ }
+ slowPoll(cm);
+ restartBlink(cm);
+ }
+ function onBlur(cm) {
+ if (cm.view.focused) {
+ signal(cm, "blur", cm);
+ cm.view.focused = false;
+ cm.display.scroller.className = cm.display.scroller.className.replace(" CodeMirror-focused", "");
+ }
+ clearInterval(cm.display.blinker);
+ setTimeout(function() {if (!cm.view.focused) cm.view.sel.shift = false;}, 150);
+ }
+
+ var detectingSelectAll;
+ function onContextMenu(cm, e) {
+ var display = cm.display, sel = cm.view.sel;
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
+ if (!pos || opera) return; // Opera is difficult.
+ if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
+ operation(cm, setSelection)(cm, pos, pos);
+
+ var oldCSS = display.input.style.cssText;
+ display.inputDiv.style.position = "absolute";
+ display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
+ "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
+ focusInput(cm);
+ resetInput(cm, true);
+ // Adds "Select all" to context menu in FF
+ if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
+
+ function rehide() {
+ display.inputDiv.style.position = "relative";
+ display.input.style.cssText = oldCSS;
+ if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
+ slowPoll(cm);
+
+ // Try to detect the user choosing select-all
+ if (display.input.selectionStart != null) {
+ clearTimeout(detectingSelectAll);
+ var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value), i = 0;
+ display.prevInput = " ";
+ display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
+ detectingSelectAll = setTimeout(function poll(){
+ if (display.prevInput == " " && display.input.selectionStart == 0)
+ operation(cm, commands.selectAll)(cm);
+ else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
+ else resetInput(cm);
+ }, 200);
+ }
+ }
+
+ if (gecko) {
+ e_stop(e);
+ on(window, "mouseup", function mouseup() {
+ off(window, "mouseup", mouseup);
+ setTimeout(rehide, 20);
+ });
+ } else {
+ setTimeout(rehide, 50);
+ }
+ }
+
+ // UPDATING
+
+ // Replace the range from from to to by the strings in newText.
+ // Afterwards, set the selection to selFrom, selTo.
+ function updateDoc(cm, from, to, newText, selUpdate, origin) {
+ // Possibly split or suppress the update based on the presence
+ // of read-only spans in its range.
+ var split = sawReadOnlySpans &&
+ removeReadOnlyRanges(cm.view.doc, from, to);
+ if (split) {
+ for (var i = split.length - 1; i >= 1; --i)
+ updateDocInner(cm, split[i].from, split[i].to, [""], origin);
+ if (split.length)
+ return updateDocInner(cm, split[0].from, split[0].to, newText, selUpdate, origin);
+ } else {
+ return updateDocInner(cm, from, to, newText, selUpdate, origin);
+ }
+ }
+
+ function updateDocInner(cm, from, to, newText, selUpdate, origin) {
+ if (cm.view.suppressEdits) return;
+
+ var view = cm.view, doc = view.doc, old = [];
+ doc.iter(from.line, to.line + 1, function(line) {
+ old.push(newHL(line.text, line.markedSpans));
+ });
+ var startSelFrom = view.sel.from, startSelTo = view.sel.to;
+ var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText);
+ var retval = updateDocNoUndo(cm, from, to, lines, selUpdate, origin);
+ if (view.history) addChange(cm, from.line, newText.length, old, origin,
+ startSelFrom, startSelTo, view.sel.from, view.sel.to);
+ return retval;
+ }
+
+ function unredoHelper(cm, type) {
+ var doc = cm.view.doc, hist = cm.view.history;
+ var set = (type == "undo" ? hist.done : hist.undone).pop();
+ if (!set) return;
+ var anti = {events: [], fromBefore: set.fromAfter, toBefore: set.toAfter,
+ fromAfter: set.fromBefore, toAfter: set.toBefore};
+ for (var i = set.events.length - 1; i >= 0; i -= 1) {
+ hist.dirtyCounter += type == "undo" ? -1 : 1;
+ var change = set.events[i];
+ var replaced = [], end = change.start + change.added;
+ doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); });
+ anti.events.push({start: change.start, added: change.old.length, old: replaced});
+ var selPos = i ? null : {from: set.fromBefore, to: set.toBefore};
+ updateDocNoUndo(cm, {line: change.start, ch: 0}, {line: end - 1, ch: getLine(doc, end-1).text.length},
+ change.old, selPos, type);
+ }
+ (type == "undo" ? hist.undone : hist.done).push(anti);
+ }
+
+ function updateDocNoUndo(cm, from, to, lines, selUpdate, origin) {
+ var view = cm.view, doc = view.doc, display = cm.display;
+ if (view.suppressEdits) return;
+
+ var nlines = to.line - from.line, firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
+ var recomputeMaxLength = false, checkWidthStart = from.line;
+ if (!cm.options.lineWrapping) {
+ checkWidthStart = lineNo(visualLine(doc, firstLine));
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
+ if (lineLength(doc, line) == view.maxLineLength) {
+ recomputeMaxLength = true;
+ return true;
+ }
+ });
+ }
+
+ var lastHL = lst(lines), th = textHeight(display);
+
+ // First adjust the line structure
+ if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") {
+ // This is a whole-line replace. Treated specially to make
+ // sure line objects move the way they are supposed to.
+ var added = [];
+ for (var i = 0, e = lines.length - 1; i < e; ++i)
+ added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
+ updateLine(cm, lastLine, lastLine.text, hlSpans(lastHL));
+ if (nlines) doc.remove(from.line, nlines, cm);
+ if (added.length) doc.insert(from.line, added);
+ } else if (firstLine == lastLine) {
+ if (lines.length == 1) {
+ updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) +
+ firstLine.text.slice(to.ch), hlSpans(lines[0]));
+ } else {
+ for (var added = [], i = 1, e = lines.length - 1; i < e; ++i)
+ added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
+ added.push(makeLine(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL), th));
+ updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
+ doc.insert(from.line + 1, added);
+ }
+ } else if (lines.length == 1) {
+ updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) +
+ lastLine.text.slice(to.ch), hlSpans(lines[0]));
+ doc.remove(from.line + 1, nlines, cm);
+ } else {
+ var added = [];
+ updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
+ updateLine(cm, lastLine, hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL));
+ for (var i = 1, e = lines.length - 1; i < e; ++i)
+ added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1, cm);
+ doc.insert(from.line + 1, added);
+ }
+
+ if (cm.options.lineWrapping) {
+ var perLine = Math.max(5, display.scroller.clientWidth / charWidth(display) - 3);
+ doc.iter(from.line, from.line + lines.length, function(line) {
+ if (line.height == 0) return;
+ var guess = (Math.ceil(line.text.length / perLine) || 1) * th;
+ if (guess != line.height) updateLineHeight(line, guess);
+ });
+ } else {
+ doc.iter(checkWidthStart, from.line + lines.length, function(line) {
+ var len = lineLength(doc, line);
+ if (len > view.maxLineLength) {
+ view.maxLine = line;
+ view.maxLineLength = len;
+ view.maxLineChanged = true;
+ recomputeMaxLength = false;
+ }
+ });
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
+ }
+
+ // Adjust frontier, schedule worker
+ view.frontier = Math.min(view.frontier, from.line);
+ startWorker(cm, 400);
+
+ var lendiff = lines.length - nlines - 1;
+ // Remember that these lines changed, for updating the display
+ regChange(cm, from.line, to.line + 1, lendiff);
+ if (hasHandler(cm, "change")) {
+ // Normalize lines to contain only strings, since that's what
+ // the change event handler expects
+ for (var i = 0; i < lines.length; ++i)
+ if (typeof lines[i] != "string") lines[i] = lines[i].text;
+ var changeObj = {from: from, to: to, text: lines, origin: origin};
+ if (cm.curOp.textChanged) {
+ for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
+ cur.next = changeObj;
+ } else cm.curOp.textChanged = changeObj;
+ }
+
+ // Update the selection
+ var newSelFrom, newSelTo, end = {line: from.line + lines.length - 1,
+ ch: hlText(lastHL).length + (lines.length == 1 ? from.ch : 0)};
+ if (selUpdate && typeof selUpdate != "string") {
+ if (selUpdate.from) { newSelFrom = selUpdate.from; newSelTo = selUpdate.to; }
+ else newSelFrom = newSelTo = selUpdate;
+ } else if (selUpdate == "end") {
+ newSelFrom = newSelTo = end;
+ } else if (selUpdate == "start") {
+ newSelFrom = newSelTo = from;
+ } else if (selUpdate == "around") {
+ newSelFrom = from; newSelTo = end;
+ } else {
+ var adjustPos = function(pos) {
+ if (posLess(pos, from)) return pos;
+ if (!posLess(to, pos)) return end;
+ var line = pos.line + lendiff;
+ var ch = pos.ch;
+ if (pos.line == to.line)
+ ch += hlText(lastHL).length - (to.ch - (to.line == from.line ? from.ch : 0));
+ return {line: line, ch: ch};
+ };
+ newSelFrom = adjustPos(view.sel.from);
+ newSelTo = adjustPos(view.sel.to);
+ }
+ setSelection(cm, newSelFrom, newSelTo, null, true);
+ return end;
+ }
+
+ function replaceRange(cm, code, from, to, origin) {
+ if (!to) to = from;
+ if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
+ return updateDoc(cm, from, to, splitLines(code), null, origin);
+ }
+
+ // SELECTION
+
+ function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
+ function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
+ function copyPos(x) {return {line: x.line, ch: x.ch};}
+
+ function clipLine(doc, n) {return Math.max(0, Math.min(n, doc.size-1));}
+ function clipPos(doc, pos) {
+ if (pos.line < 0) return {line: 0, ch: 0};
+ if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc, doc.size-1).text.length};
+ var ch = pos.ch, linelen = getLine(doc, pos.line).text.length;
+ if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
+ else if (ch < 0) return {line: pos.line, ch: 0};
+ else return pos;
+ }
+ function isLine(doc, l) {return l >= 0 && l < doc.size;}
+
+ // If shift is held, this will move the selection anchor. Otherwise,
+ // it'll set the whole selection.
+ function extendSelection(cm, pos, other, bias) {
+ var sel = cm.view.sel;
+ if (sel.shift || sel.extend) {
+ var anchor = sel.anchor;
+ if (other) {
+ var posBefore = posLess(pos, anchor);
+ if (posBefore != posLess(other, anchor)) {
+ anchor = pos;
+ pos = other;
+ } else if (posBefore != posLess(pos, other)) {
+ pos = other;
+ }
+ }
+ setSelection(cm, anchor, pos, bias);
+ } else {
+ setSelection(cm, pos, other || pos, bias);
+ }
+ cm.curOp.userSelChange = true;
+ }
+
+ // Update the selection. Last two args are only used by
+ // updateDoc, since they have to be expressed in the line
+ // numbers before the update.
+ function setSelection(cm, anchor, head, bias, checkAtomic) {
+ cm.view.goalColumn = null;
+ var sel = cm.view.sel;
+ // Skip over atomic spans.
+ if (checkAtomic || !posEq(anchor, sel.anchor))
+ anchor = skipAtomic(cm, anchor, bias, checkAtomic != "push");
+ if (checkAtomic || !posEq(head, sel.head))
+ head = skipAtomic(cm, head, bias, checkAtomic != "push");
+
+ if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
+
+ sel.anchor = anchor; sel.head = head;
+ var inv = posLess(head, anchor);
+ sel.from = inv ? head : anchor;
+ sel.to = inv ? anchor : head;
+
+ cm.curOp.updateInput = true;
+ cm.curOp.selectionChanged = true;
+ }
+
+ function reCheckSelection(cm) {
+ setSelection(cm, cm.view.sel.from, cm.view.sel.to, null, "push");
+ }
+
+ function skipAtomic(cm, pos, bias, mayClear) {
+ var doc = cm.view.doc, flipped = false, curPos = pos;
+ var dir = bias || 1;
+ cm.view.cantEdit = false;
+ search: for (;;) {
+ var line = getLine(doc, curPos.line), toClear;
+ if (line.markedSpans) {
+ for (var i = 0; i < line.markedSpans.length; ++i) {
+ var sp = line.markedSpans[i], m = sp.marker;
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
+ (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
+ if (mayClear && m.clearOnEnter) {
+ (toClear || (toClear = [])).push(m);
+ continue;
+ } else if (!m.atomic) continue;
+ var newPos = m.find()[dir < 0 ? "from" : "to"];
+ if (posEq(newPos, curPos)) {
+ newPos.ch += dir;
+ if (newPos.ch < 0) {
+ if (newPos.line) newPos = clipPos(doc, {line: newPos.line - 1});
+ else newPos = null;
+ } else if (newPos.ch > line.text.length) {
+ if (newPos.line < doc.size - 1) newPos = {line: newPos.line + 1, ch: 0};
+ else newPos = null;
+ }
+ if (!newPos) {
+ if (flipped) {
+ // Driven in a corner -- no valid cursor position found at all
+ // -- try again *with* clearing, if we didn't already
+ if (!mayClear) return skipAtomic(cm, pos, bias, true);
+ // Otherwise, turn off editing until further notice, and return the start of the doc
+ cm.view.cantEdit = true;
+ return {line: 0, ch: 0};
+ }
+ flipped = true; newPos = pos; dir = -dir;
+ }
+ }
+ curPos = newPos;
+ continue search;
+ }
+ }
+ if (toClear) for (var i = 0; i < toClear.length; ++i) toClear[i].clear();
+ }
+ return curPos;
+ }
+ }
+
+ // SCROLLING
+
+ function scrollCursorIntoView(cm) {
+ var view = cm.view;
+ var coords = scrollPosIntoView(cm, view.sel.head);
+ if (!view.focused) return;
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
+ if (coords.top + box.top < 0) doScroll = true;
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
+ if (doScroll != null && !phantom) {
+ var hidden = display.cursor.style.display == "none";
+ if (hidden) {
+ display.cursor.style.display = "";
+ display.cursor.style.left = coords.left + "px";
+ display.cursor.style.top = (coords.top - display.viewOffset) + "px";
+ }
+ display.cursor.scrollIntoView(doScroll);
+ if (hidden) display.cursor.style.display = "none";
+ }
+ }
+
+ function scrollPosIntoView(cm, pos) {
+ for (;;) {
+ var changed = false, coords = cursorCoords(cm, pos);
+ var scrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
+ var startTop = cm.view.scrollTop, startLeft = cm.view.scrollLeft;
+ if (scrollPos.scrollTop != null) {
+ setScrollTop(cm, scrollPos.scrollTop);
+ if (Math.abs(cm.view.scrollTop - startTop) > 1) changed = true;
+ }
+ if (scrollPos.scrollLeft != null) {
+ setScrollLeft(cm, scrollPos.scrollLeft);
+ if (Math.abs(cm.view.scrollLeft - startLeft) > 1) changed = true;
+ }
+ if (!changed) return coords;
+ }
+ }
+
+ function scrollIntoView(cm, x1, y1, x2, y2) {
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
+ }
+
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
+ var display = cm.display, pt = paddingTop(display);
+ y1 += pt; y2 += pt;
+ var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
+ var docBottom = cm.view.doc.height + 2 * pt;
+ var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;
+ if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
+ else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen;
+
+ var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
+ x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
+ var gutterw = display.gutters.offsetWidth;
+ var atLeft = x1 < gutterw + 10;
+ if (x1 < screenleft + gutterw || atLeft) {
+ if (atLeft) x1 = 0;
+ result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
+ } else if (x2 > screenw + screenleft - 3) {
+ result.scrollLeft = x2 + 10 - screenw;
+ }
+ return result;
+ }
+
+ // API UTILITIES
+
+ function indentLine(cm, n, how, aggressive) {
+ var doc = cm.view.doc;
+ if (!how) how = "add";
+ if (how == "smart") {
+ if (!cm.view.mode.indent) how = "prev";
+ else var state = getStateBefore(cm, n);
+ }
+
+ var tabSize = cm.options.tabSize;
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
+ if (how == "smart") {
+ indentation = cm.view.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
+ if (indentation == Pass) {
+ if (!aggressive) return;
+ how = "prev";
+ }
+ }
+ if (how == "prev") {
+ if (n) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
+ else indentation = 0;
+ }
+ else if (how == "add") indentation = curSpace + cm.options.indentUnit;
+ else if (how == "subtract") indentation = curSpace - cm.options.indentUnit;
+ indentation = Math.max(0, indentation);
+
+ var indentString = "", pos = 0;
+ if (cm.options.indentWithTabs)
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
+
+ if (indentString != curSpaceString)
+ replaceRange(cm, indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}, "input");
+ line.stateAfter = null;
+ }
+
+ function changeLine(cm, handle, op) {
+ var no = handle, line = handle, doc = cm.view.doc;
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
+ else no = lineNo(handle);
+ if (no == null) return null;
+ if (op(line, no)) regChange(cm, no, no + 1);
+ else return null;
+ return line;
+ }
+
+ function findPosH(cm, dir, unit, visually) {
+ var doc = cm.view.doc, end = cm.view.sel.head, line = end.line, ch = end.ch;
+ var lineObj = getLine(doc, line);
+ function findNextLine() {
+ var l = line + dir;
+ if (l < 0 || l == doc.size) return false;
+ line = l;
+ return lineObj = getLine(doc, l);
+ }
+ function moveOnce(boundToLine) {
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
+ if (next == null) {
+ if (!boundToLine && findNextLine()) {
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
+ else ch = dir < 0 ? lineObj.text.length : 0;
+ } else return false;
+ } else ch = next;
+ return true;
+ }
+ if (unit == "char") moveOnce();
+ else if (unit == "column") moveOnce(true);
+ else if (unit == "word") {
+ var sawWord = false;
+ for (;;) {
+ if (dir < 0) if (!moveOnce()) break;
+ if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
+ else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
+ if (dir > 0) if (!moveOnce()) break;
+ }
+ }
+ return skipAtomic(cm, {line: line, ch: ch}, dir, true);
+ }
+
+ function findWordAt(line, pos) {
+ var start = pos.ch, end = pos.ch;
+ if (line) {
+ if (pos.after === false || end == line.length) --start; else ++end;
+ var startChar = line.charAt(start);
+ var check = isWordChar(startChar) ? isWordChar :
+ /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} :
+ function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
+ while (start > 0 && check(line.charAt(start - 1))) --start;
+ while (end < line.length && check(line.charAt(end))) ++end;
+ }
+ return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}};
+ }
+
+ function selectLine(cm, line) {
+ extendSelection(cm, {line: line, ch: 0}, clipPos(cm.view.doc, {line: line + 1, ch: 0}));
+ }
+
+ // PROTOTYPE
+
+ // The publicly visible API. Note that operation(null, f) means
+ // 'wrap f in an operation, performed on its `this` parameter'
+
+ CodeMirror.prototype = {
+ getValue: function(lineSep) {
+ var text = [], doc = this.view.doc;
+ doc.iter(0, doc.size, function(line) { text.push(line.text); });
+ return text.join(lineSep || "\n");
+ },
+
+ setValue: operation(null, function(code) {
+ var doc = this.view.doc, top = {line: 0, ch: 0}, lastLen = getLine(doc, doc.size-1).text.length;
+ updateDocInner(this, top, {line: doc.size - 1, ch: lastLen}, splitLines(code), top, top, "setValue");
+ }),
+
+ getSelection: function(lineSep) { return this.getRange(this.view.sel.from, this.view.sel.to, lineSep); },
+
+ replaceSelection: operation(null, function(code, collapse, origin) {
+ var sel = this.view.sel;
+ updateDoc(this, sel.from, sel.to, splitLines(code), collapse || "around", origin);
+ }),
+
+ focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
+
+ setOption: function(option, value) {
+ var options = this.options, old = options[option];
+ if (options[option] == value && option != "mode") return;
+ options[option] = value;
+ if (optionHandlers.hasOwnProperty(option))
+ operation(this, optionHandlers[option])(this, value, old);
+ },
+
+ getOption: function(option) {return this.options[option];},
+
+ getMode: function() {return this.view.mode;},
+
+ addKeyMap: function(map) {
+ this.view.keyMaps.push(map);
+ },
+
+ removeKeyMap: function(map) {
+ var maps = this.view.keyMaps;
+ for (var i = 0; i < maps.length; ++i)
+ if ((typeof map == "string" ? maps[i].name : maps[i]) == map) {
+ maps.splice(i, 1);
+ return true;
+ }
+ },
+
+ undo: operation(null, function() {unredoHelper(this, "undo");}),
+ redo: operation(null, function() {unredoHelper(this, "redo");}),
+
+ indentLine: operation(null, function(n, dir, aggressive) {
+ if (typeof dir != "string") {
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
+ else dir = dir ? "add" : "subtract";
+ }
+ if (isLine(this.view.doc, n)) indentLine(this, n, dir, aggressive);
+ }),
+
+ indentSelection: operation(null, function(how) {
+ var sel = this.view.sel;
+ if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
+ var e = sel.to.line - (sel.to.ch ? 0 : 1);
+ for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
+ }),
+
+ historySize: function() {
+ var hist = this.view.history;
+ return {undo: hist.done.length, redo: hist.undone.length};
+ },
+
+ clearHistory: function() {this.view.history = makeHistory();},
+
+ markClean: function() {
+ this.view.history.dirtyCounter = 0;
+ this.view.history.lastOp = this.view.history.lastOrigin = null;
+ },
+
+ isClean: function () {return this.view.history.dirtyCounter == 0;},
+
+ getHistory: function() {
+ var hist = this.view.history;
+ function cp(arr) {
+ for (var i = 0, nw = [], nwelt; i < arr.length; ++i) {
+ var set = arr[i];
+ nw.push({events: nwelt = [], fromBefore: set.fromBefore, toBefore: set.toBefore,
+ fromAfter: set.fromAfter, toAfter: set.toAfter});
+ for (var j = 0, elt = set.events; j < elt.length; ++j) {
+ var old = [], cur = elt[j];
+ nwelt.push({start: cur.start, added: cur.added, old: old});
+ for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k]));
+ }
+ }
+ return nw;
+ }
+ return {done: cp(hist.done), undone: cp(hist.undone)};
+ },
+
+ setHistory: function(histData) {
+ var hist = this.view.history = makeHistory();
+ hist.done = histData.done;
+ hist.undone = histData.undone;
+ },
+
+ // Fetch the parser token for a given character. Useful for hacks
+ // that want to inspect the mode state (say, for completion).
+ getTokenAt: function(pos) {
+ var doc = this.view.doc;
+ pos = clipPos(doc, pos);
+ var state = getStateBefore(this, pos.line), mode = this.view.mode;
+ var line = getLine(doc, pos.line);
+ var stream = new StringStream(line.text, this.options.tabSize);
+ while (stream.pos < pos.ch && !stream.eol()) {
+ stream.start = stream.pos;
+ var style = mode.token(stream, state);
+ }
+ return {start: stream.start,
+ end: stream.pos,
+ string: stream.current(),
+ className: style || null, // Deprecated, use 'type' instead
+ type: style || null,
+ state: state};
+ },
+
+ getStateAfter: function(line) {
+ var doc = this.view.doc;
+ line = clipLine(doc, line == null ? doc.size - 1: line);
+ return getStateBefore(this, line + 1);
+ },
+
+ cursorCoords: function(start, mode) {
+ var pos, sel = this.view.sel;
+ if (start == null) pos = sel.head;
+ else if (typeof start == "object") pos = clipPos(this.view.doc, start);
+ else pos = start ? sel.from : sel.to;
+ return cursorCoords(this, pos, mode || "page");
+ },
+
+ charCoords: function(pos, mode) {
+ return charCoords(this, clipPos(this.view.doc, pos), mode || "page");
+ },
+
+ coordsChar: function(coords) {
+ var off = this.display.lineSpace.getBoundingClientRect();
+ return coordsChar(this, coords.left - off.left, coords.top - off.top);
+ },
+
+ defaultTextHeight: function() { return textHeight(this.display); },
+
+ markText: operation(null, function(from, to, options) {
+ return markText(this, clipPos(this.view.doc, from), clipPos(this.view.doc, to),
+ options, "range");
+ }),
+
+ setBookmark: operation(null, function(pos, widget) {
+ pos = clipPos(this.view.doc, pos);
+ return markText(this, pos, pos, widget ? {replacedWith: widget} : {}, "bookmark");
+ }),
+
+ findMarksAt: function(pos) {
+ var doc = this.view.doc;
+ pos = clipPos(doc, pos);
+ var markers = [], spans = getLine(doc, pos.line).markedSpans;
+ if (spans) for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if ((span.from == null || span.from <= pos.ch) &&
+ (span.to == null || span.to >= pos.ch))
+ markers.push(span.marker);
+ }
+ return markers;
+ },
+
+ setGutterMarker: operation(null, function(line, gutterID, value) {
+ return changeLine(this, line, function(line) {
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
+ markers[gutterID] = value;
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
+ return true;
+ });
+ }),
+
+ clearGutter: operation(null, function(gutterID) {
+ var i = 0, cm = this, doc = cm.view.doc;
+ doc.iter(0, doc.size, function(line) {
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
+ line.gutterMarkers[gutterID] = null;
+ regChange(cm, i, i + 1);
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
+ }
+ ++i;
+ });
+ }),
+
+ addLineClass: operation(null, function(handle, where, cls) {
+ return changeLine(this, handle, function(line) {
+ var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
+ if (!line[prop]) line[prop] = cls;
+ else if (new RegExp("\\b" + cls + "\\b").test(line[prop])) return false;
+ else line[prop] += " " + cls;
+ return true;
+ });
+ }),
+
+ removeLineClass: operation(null, function(handle, where, cls) {
+ return changeLine(this, handle, function(line) {
+ var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
+ var cur = line[prop];
+ if (!cur) return false;
+ else if (cls == null) line[prop] = null;
+ else {
+ var upd = cur.replace(new RegExp("^" + cls + "\\b\\s*|\\s*\\b" + cls + "\\b"), "");
+ if (upd == cur) return false;
+ line[prop] = upd || null;
+ }
+ return true;
+ });
+ }),
+
+ addLineWidget: operation(null, function(handle, node, options) {
+ var widget = options || {};
+ widget.node = node;
+ if (widget.noHScroll) this.display.alignWidgets = true;
+ changeLine(this, handle, function(line) {
+ (line.widgets || (line.widgets = [])).push(widget);
+ widget.line = line;
+ return true;
+ });
+ return widget;
+ }),
+
+ removeLineWidget: operation(null, function(widget) {
+ var ws = widget.line.widgets, no = lineNo(widget.line);
+ if (no == null) return;
+ for (var i = 0; i < ws.length; ++i) if (ws[i] == widget) ws.splice(i--, 1);
+ regChange(this, no, no + 1);
+ }),
+
+ lineInfo: function(line) {
+ if (typeof line == "number") {
+ if (!isLine(this.view.doc, line)) return null;
+ var n = line;
+ line = getLine(this.view.doc, line);
+ if (!line) return null;
+ } else {
+ var n = lineNo(line);
+ if (n == null) return null;
+ }
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
+ widgets: line.widgets};
+ },
+
+ getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
+
+ addWidget: function(pos, node, scroll, vert, horiz) {
+ var display = this.display;
+ pos = cursorCoords(this, clipPos(this.view.doc, pos));
+ var top = pos.top, left = pos.left;
+ node.style.position = "absolute";
+ display.sizer.appendChild(node);
+ if (vert == "over") top = pos.top;
+ else if (vert == "near") {
+ var vspace = Math.max(display.wrapper.clientHeight, this.view.doc.height),
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
+ if (pos.bottom + node.offsetHeight > vspace && pos.top > node.offsetHeight)
+ top = pos.top - node.offsetHeight;
+ if (left + node.offsetWidth > hspace)
+ left = hspace - node.offsetWidth;
+ }
+ node.style.top = (top + paddingTop(display)) + "px";
+ node.style.left = node.style.right = "";
+ if (horiz == "right") {
+ left = display.sizer.clientWidth - node.offsetWidth;
+ node.style.right = "0px";
+ } else {
+ if (horiz == "left") left = 0;
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
+ node.style.left = left + "px";
+ }
+ if (scroll)
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
+ },
+
+ lineCount: function() {return this.view.doc.size;},
+
+ clipPos: function(pos) {return clipPos(this.view.doc, pos);},
+
+ getCursor: function(start) {
+ var sel = this.view.sel, pos;
+ if (start == null || start == "head") pos = sel.head;
+ else if (start == "anchor") pos = sel.anchor;
+ else if (start == "end" || start === false) pos = sel.to;
+ else pos = sel.from;
+ return copyPos(pos);
+ },
+
+ somethingSelected: function() {return !posEq(this.view.sel.from, this.view.sel.to);},
+
+ setCursor: operation(null, function(line, ch, extend) {
+ var pos = clipPos(this.view.doc, typeof line == "number" ? {line: line, ch: ch || 0} : line);
+ if (extend) extendSelection(this, pos);
+ else setSelection(this, pos, pos);
+ }),
+
+ setSelection: operation(null, function(anchor, head) {
+ var doc = this.view.doc;
+ setSelection(this, clipPos(doc, anchor), clipPos(doc, head || anchor));
+ }),
+
+ extendSelection: operation(null, function(from, to) {
+ var doc = this.view.doc;
+ extendSelection(this, clipPos(doc, from), to && clipPos(doc, to));
+ }),
+
+ setExtending: function(val) {this.view.sel.extend = val;},
+
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
+
+ getLineHandle: function(line) {
+ var doc = this.view.doc;
+ if (isLine(doc, line)) return getLine(doc, line);
+ },
+
+ getLineNumber: function(line) {return lineNo(line);},
+
+ setLine: operation(null, function(line, text) {
+ if (isLine(this.view.doc, line))
+ replaceRange(this, text, {line: line, ch: 0}, {line: line, ch: getLine(this.view.doc, line).text.length});
+ }),
+
+ removeLine: operation(null, function(line) {
+ if (isLine(this.view.doc, line))
+ replaceRange(this, "", {line: line, ch: 0}, clipPos(this.view.doc, {line: line+1, ch: 0}));
+ }),
+
+ replaceRange: operation(null, function(code, from, to) {
+ var doc = this.view.doc;
+ from = clipPos(doc, from);
+ to = to ? clipPos(doc, to) : from;
+ return replaceRange(this, code, from, to);
+ }),
+
+ getRange: function(from, to, lineSep) {
+ var doc = this.view.doc;
+ from = clipPos(doc, from); to = clipPos(doc, to);
+ var l1 = from.line, l2 = to.line;
+ if (l1 == l2) return getLine(doc, l1).text.slice(from.ch, to.ch);
+ var code = [getLine(doc, l1).text.slice(from.ch)];
+ doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
+ code.push(getLine(doc, l2).text.slice(0, to.ch));
+ return code.join(lineSep || "\n");
+ },
+
+ triggerOnKeyDown: operation(null, onKeyDown),
+
+ execCommand: function(cmd) {return commands[cmd](this);},
+
+ // Stuff used by commands, probably not much use to outside code.
+ moveH: operation(null, function(dir, unit) {
+ var sel = this.view.sel, pos = dir < 0 ? sel.from : sel.to;
+ if (sel.shift || sel.extend || posEq(sel.from, sel.to)) pos = findPosH(this, dir, unit, true);
+ extendSelection(this, pos, pos, dir);
+ }),
+
+ deleteH: operation(null, function(dir, unit) {
+ var sel = this.view.sel;
+ if (!posEq(sel.from, sel.to)) replaceRange(this, "", sel.from, sel.to, "delete");
+ else replaceRange(this, "", sel.from, findPosH(this, dir, unit, false), "delete");
+ this.curOp.userSelChange = true;
+ }),
+
+ moveV: operation(null, function(dir, unit) {
+ var view = this.view, doc = view.doc, display = this.display;
+ var cur = view.sel.head, pos = cursorCoords(this, cur, "div");
+ var x = pos.left, y;
+ if (view.goalColumn != null) x = view.goalColumn;
+ if (unit == "page") {
+ var pageSize = Math.min(display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
+ y = pos.top + dir * pageSize;
+ } else if (unit == "line") {
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
+ }
+ do {
+ var target = coordsChar(this, x, y);
+ y += dir * 5;
+ } while (target.outside && (dir < 0 ? y > 0 : y < doc.height));
+
+ if (unit == "page") display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top;
+ extendSelection(this, target, target, dir);
+ view.goalColumn = x;
+ }),
+
+ toggleOverwrite: function() {
+ if (this.view.overwrite = !this.view.overwrite)
+ this.display.cursor.className += " CodeMirror-overwrite";
+ else
+ this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
+ },
+
+ posFromIndex: function(off) {
+ var lineNo = 0, ch, doc = this.view.doc;
+ doc.iter(0, doc.size, function(line) {
+ var sz = line.text.length + 1;
+ if (sz > off) { ch = off; return true; }
+ off -= sz;
+ ++lineNo;
+ });
+ return clipPos(doc, {line: lineNo, ch: ch});
+ },
+ indexFromPos: function (coords) {
+ if (coords.line < 0 || coords.ch < 0) return 0;
+ var index = coords.ch;
+ this.view.doc.iter(0, coords.line, function (line) {
+ index += line.text.length + 1;
+ });
+ return index;
+ },
+
+ scrollTo: function(x, y) {
+ if (x != null) this.display.scrollbarH.scrollLeft = this.display.scroller.scrollLeft = x;
+ if (y != null) this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = y;
+ updateDisplay(this, []);
+ },
+ getScrollInfo: function() {
+ var scroller = this.display.scroller, co = scrollerCutOff;
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
+ height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
+ clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
+ },
+
+ scrollIntoView: function(pos) {
+ if (typeof pos == "number") pos = {line: pos, ch: 0};
+ pos = pos ? clipPos(this.view.doc, pos) : this.view.sel.head;
+ scrollPosIntoView(this, pos);
+ },
+
+ setSize: function(width, height) {
+ function interpret(val) {
+ return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
+ }
+ if (width != null) this.display.wrapper.style.width = interpret(width);
+ if (height != null) this.display.wrapper.style.height = interpret(height);
+ this.refresh();
+ },
+
+ on: function(type, f) {on(this, type, f);},
+ off: function(type, f) {off(this, type, f);},
+
+ operation: function(f){return operation(this, f)();},
+
+ refresh: function() {
+ clearCaches(this);
+ if (this.display.scroller.scrollHeight > this.view.scrollTop)
+ this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = this.view.scrollTop;
+ updateDisplay(this, true);
+ },
+
+ getInputField: function(){return this.display.input;},
+ getWrapperElement: function(){return this.display.wrapper;},
+ getScrollerElement: function(){return this.display.scroller;},
+ getGutterElement: function(){return this.display.gutters;}
+ };
+
+ // OPTION DEFAULTS
+
+ var optionHandlers = CodeMirror.optionHandlers = {};
+
+ // The default configuration options.
+ var defaults = CodeMirror.defaults = {};
+
+ function option(name, deflt, handle, notOnInit) {
+ CodeMirror.defaults[name] = deflt;
+ if (handle) optionHandlers[name] =
+ notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
+ }
+
+ var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
+
+ // These two are, on init, called from the constructor because they
+ // have to be initialized before the editor can start at all.
+ option("value", "", function(cm, val) {cm.setValue(val);}, true);
+ option("mode", null, loadMode, true);
+
+ option("indentUnit", 2, loadMode, true);
+ option("indentWithTabs", false);
+ option("smartIndent", true);
+ option("tabSize", 4, function(cm) {
+ loadMode(cm);
+ clearCaches(cm);
+ updateDisplay(cm, true);
+ }, true);
+ option("electricChars", true);
+
+ option("theme", "default", function(cm) {
+ themeChanged(cm);
+ guttersChanged(cm);
+ }, true);
+ option("keyMap", "default", keyMapChanged);
+ option("extraKeys", null);
+
+ option("onKeyEvent", null);
+ option("onDragEvent", null);
+
+ option("lineWrapping", false, wrappingChanged, true);
+ option("gutters", [], function(cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("lineNumbers", false, function(cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("firstLineNumber", 1, guttersChanged, true);
+ option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
+ option("showCursorWhenSelecting", false, updateSelection, true);
+
+ option("readOnly", false, function(cm, val) {
+ if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
+ else if (!val) resetInput(cm, true);
+ });
+ option("dragDrop", true);
+
+ option("cursorBlinkRate", 530);
+ option("cursorHeight", 1);
+ option("workTime", 100);
+ option("workDelay", 100);
+ option("flattenSpans", true);
+ option("pollInterval", 100);
+ option("undoDepth", 40);
+ option("viewportMargin", 10, function(cm){cm.refresh();}, true);
+
+ option("tabindex", null, function(cm, val) {
+ cm.display.input.tabIndex = val || "";
+ });
+ option("autofocus", null);
+
+ // MODE DEFINITION AND QUERYING
+
+ // Known modes, by name and by MIME
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
+
+ CodeMirror.defineMode = function(name, mode) {
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
+ if (arguments.length > 2) {
+ mode.dependencies = [];
+ for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
+ }
+ modes[name] = mode;
+ };
+
+ CodeMirror.defineMIME = function(mime, spec) {
+ mimeModes[mime] = spec;
+ };
+
+ CodeMirror.resolveMode = function(spec) {
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
+ spec = mimeModes[spec];
+ else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
+ return CodeMirror.resolveMode("application/xml");
+ if (typeof spec == "string") return {name: spec};
+ else return spec || {name: "null"};
+ };
+
+ CodeMirror.getMode = function(options, spec) {
+ var spec = CodeMirror.resolveMode(spec);
+ var mfactory = modes[spec.name];
+ if (!mfactory) return CodeMirror.getMode(options, "text/plain");
+ var modeObj = mfactory(options, spec);
+ if (modeExtensions.hasOwnProperty(spec.name)) {
+ var exts = modeExtensions[spec.name];
+ for (var prop in exts) {
+ if (!exts.hasOwnProperty(prop)) continue;
+ if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
+ modeObj[prop] = exts[prop];
+ }
+ }
+ modeObj.name = spec.name;
+ return modeObj;
+ };
+
+ CodeMirror.defineMode("null", function() {
+ return {token: function(stream) {stream.skipToEnd();}};
+ });
+ CodeMirror.defineMIME("text/plain", "null");
+
+ var modeExtensions = CodeMirror.modeExtensions = {};
+ CodeMirror.extendMode = function(mode, properties) {
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
+ for (var prop in properties) if (properties.hasOwnProperty(prop))
+ exts[prop] = properties[prop];
+ };
+
+ // EXTENSIONS
+
+ CodeMirror.defineExtension = function(name, func) {
+ CodeMirror.prototype[name] = func;
+ };
+
+ CodeMirror.defineOption = option;
+
+ var initHooks = [];
+ CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
+
+ // MODE STATE HANDLING
+
+ // Utility functions for working with state. Exported because modes
+ // sometimes need to do this.
+ function copyState(mode, state) {
+ if (state === true) return state;
+ if (mode.copyState) return mode.copyState(state);
+ var nstate = {};
+ for (var n in state) {
+ var val = state[n];
+ if (val instanceof Array) val = val.concat([]);
+ nstate[n] = val;
+ }
+ return nstate;
+ }
+ CodeMirror.copyState = copyState;
+
+ function startState(mode, a1, a2) {
+ return mode.startState ? mode.startState(a1, a2) : true;
+ }
+ CodeMirror.startState = startState;
+
+ CodeMirror.innerMode = function(mode, state) {
+ while (mode.innerMode) {
+ var info = mode.innerMode(state);
+ state = info.state;
+ mode = info.mode;
+ }
+ return info || {mode: mode, state: state};
+ };
+
+ // STANDARD COMMANDS
+
+ var commands = CodeMirror.commands = {
+ selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
+ killLine: function(cm) {
+ var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
+ if (!sel && cm.getLine(from.line).length == from.ch)
+ cm.replaceRange("", from, {line: from.line + 1, ch: 0}, "delete");
+ else cm.replaceRange("", from, sel ? to : {line: from.line}, "delete");
+ },
+ deleteLine: function(cm) {
+ var l = cm.getCursor().line;
+ cm.replaceRange("", {line: l, ch: 0}, {line: l}, "delete");
+ },
+ undo: function(cm) {cm.undo();},
+ redo: function(cm) {cm.redo();},
+ goDocStart: function(cm) {cm.extendSelection({line: 0, ch: 0});},
+ goDocEnd: function(cm) {cm.extendSelection({line: cm.lineCount() - 1});},
+ goLineStart: function(cm) {
+ cm.extendSelection(lineStart(cm, cm.getCursor().line));
+ },
+ goLineStartSmart: function(cm) {
+ var cur = cm.getCursor(), start = lineStart(cm, cur.line);
+ var line = cm.getLineHandle(start.line);
+ var order = getOrder(line);
+ if (!order || order[0].level == 0) {
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
+ var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
+ cm.extendSelection({line: start.line, ch: inWS ? 0 : firstNonWS});
+ } else cm.extendSelection(start);
+ },
+ goLineEnd: function(cm) {
+ cm.extendSelection(lineEnd(cm, cm.getCursor().line));
+ },
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
+ goLineDown: function(cm) {cm.moveV(1, "line");},
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
+ goPageDown: function(cm) {cm.moveV(1, "page");},
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
+ goCharRight: function(cm) {cm.moveH(1, "char");},
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
+ goWordRight: function(cm) {cm.moveH(1, "word");},
+ delCharBefore: function(cm) {cm.deleteH(-1, "char");},
+ delCharAfter: function(cm) {cm.deleteH(1, "char");},
+ delWordBefore: function(cm) {cm.deleteH(-1, "word");},
+ delWordAfter: function(cm) {cm.deleteH(1, "word");},
+ indentAuto: function(cm) {cm.indentSelection("smart");},
+ indentMore: function(cm) {cm.indentSelection("add");},
+ indentLess: function(cm) {cm.indentSelection("subtract");},
+ insertTab: function(cm) {cm.replaceSelection("\t", "end", "input");},
+ defaultTab: function(cm) {
+ if (cm.somethingSelected()) cm.indentSelection("add");
+ else cm.replaceSelection("\t", "end", "input");
+ },
+ transposeChars: function(cm) {
+ var cur = cm.getCursor(), line = cm.getLine(cur.line);
+ if (cur.ch > 0 && cur.ch < line.length - 1)
+ cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
+ {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
+ },
+ newlineAndIndent: function(cm) {
+ operation(cm, function() {
+ cm.replaceSelection("\n", "end", "input");
+ cm.indentLine(cm.getCursor().line, null, true);
+ })();
+ },
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
+ };
+
+ // STANDARD KEYMAPS
+
+ var keyMap = CodeMirror.keyMap = {};
+ keyMap.basic = {
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
+ };
+ // Note that the save and find-related commands aren't defined by
+ // default. Unknown commands are simply ignored.
+ keyMap.pcDefault = {
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
+ "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
+ "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
+ "Ctrl-Backspace": "delWordBefore", "Ctrl-Delete": "delWordAfter", "Ctrl-S": "save", "Ctrl-F": "find",
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
+ fallthrough: "basic"
+ };
+ keyMap.macDefault = {
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
+ "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
+ "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordBefore",
+ "Ctrl-Alt-Backspace": "delWordAfter", "Alt-Delete": "delWordAfter", "Cmd-S": "save", "Cmd-F": "find",
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore",
+ fallthrough: ["basic", "emacsy"]
+ };
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
+ keyMap.emacsy = {
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
+ };
+
+ // KEYMAP DISPATCH
+
+ function getKeyMap(val) {
+ if (typeof val == "string") return keyMap[val];
+ else return val;
+ }
+
+ function lookupKey(name, maps, handle, stop) {
+ function lookup(map) {
+ map = getKeyMap(map);
+ var found = map[name];
+ if (found === false) {
+ if (stop) stop();
+ return true;
+ }
+ if (found != null && handle(found)) return true;
+ if (map.nofallthrough) {
+ if (stop) stop();
+ return true;
+ }
+ var fallthrough = map.fallthrough;
+ if (fallthrough == null) return false;
+ if (Object.prototype.toString.call(fallthrough) != "[object Array]")
+ return lookup(fallthrough);
+ for (var i = 0, e = fallthrough.length; i < e; ++i) {
+ if (lookup(fallthrough[i])) return true;
+ }
+ return false;
+ }
+
+ for (var i = 0; i < maps.length; ++i)
+ if (lookup(maps[i])) return true;
+ }
+ function isModifierKey(event) {
+ var name = keyNames[e_prop(event, "keyCode")];
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
+ }
+ CodeMirror.isModifierKey = isModifierKey;
+
+ // FROMTEXTAREA
+
+ CodeMirror.fromTextArea = function(textarea, options) {
+ if (!options) options = {};
+ options.value = textarea.value;
+ if (!options.tabindex && textarea.tabindex)
+ options.tabindex = textarea.tabindex;
+ // Set autofocus to true if this textarea is focused, or if it has
+ // autofocus and no other element is focused.
+ if (options.autofocus == null) {
+ var hasFocus = document.body;
+ // doc.activeElement occasionally throws on IE
+ try { hasFocus = document.activeElement; } catch(e) {}
+ options.autofocus = hasFocus == textarea ||
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
+ }
+
+ function save() {textarea.value = cm.getValue();}
+ if (textarea.form) {
+ // Deplorable hack to make the submit method do the right thing.
+ on(textarea.form, "submit", save);
+ var form = textarea.form, realSubmit = form.submit;
+ try {
+ form.submit = function wrappedSubmit() {
+ save();
+ form.submit = realSubmit;
+ form.submit();
+ form.submit = wrappedSubmit;
+ };
+ } catch(e) {}
+ }
+
+ textarea.style.display = "none";
+ var cm = CodeMirror(function(node) {
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
+ }, options);
+ cm.save = save;
+ cm.getTextArea = function() { return textarea; };
+ cm.toTextArea = function() {
+ save();
+ textarea.parentNode.removeChild(cm.getWrapperElement());
+ textarea.style.display = "";
+ if (textarea.form) {
+ off(textarea.form, "submit", save);
+ if (typeof textarea.form.submit == "function")
+ textarea.form.submit = realSubmit;
+ }
+ };
+ return cm;
+ };
+
+ // STRING STREAM
+
+ // Fed to the mode parsers, provides helper functions to make
+ // parsers more succinct.
+
+ // The character stream used by a mode's parser.
+ function StringStream(string, tabSize) {
+ this.pos = this.start = 0;
+ this.string = string;
+ this.tabSize = tabSize || 8;
+ }
+
+ StringStream.prototype = {
+ eol: function() {return this.pos >= this.string.length;},
+ sol: function() {return this.pos == 0;},
+ peek: function() {return this.string.charAt(this.pos) || undefined;},
+ next: function() {
+ if (this.pos < this.string.length)
+ return this.string.charAt(this.pos++);
+ },
+ eat: function(match) {
+ var ch = this.string.charAt(this.pos);
+ if (typeof match == "string") var ok = ch == match;
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
+ if (ok) {++this.pos; return ch;}
+ },
+ eatWhile: function(match) {
+ var start = this.pos;
+ while (this.eat(match)){}
+ return this.pos > start;
+ },
+ eatSpace: function() {
+ var start = this.pos;
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
+ return this.pos > start;
+ },
+ skipToEnd: function() {this.pos = this.string.length;},
+ skipTo: function(ch) {
+ var found = this.string.indexOf(ch, this.pos);
+ if (found > -1) {this.pos = found; return true;}
+ },
+ backUp: function(n) {this.pos -= n;},
+ column: function() {return countColumn(this.string, this.start, this.tabSize);},
+ indentation: function() {return countColumn(this.string, null, this.tabSize);},
+ match: function(pattern, consume, caseInsensitive) {
+ if (typeof pattern == "string") {
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
+ if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
+ if (consume !== false) this.pos += pattern.length;
+ return true;
+ }
+ } else {
+ var match = this.string.slice(this.pos).match(pattern);
+ if (match && match.index > 0) return null;
+ if (match && consume !== false) this.pos += match[0].length;
+ return match;
+ }
+ },
+ current: function(){return this.string.slice(this.start, this.pos);}
+ };
+ CodeMirror.StringStream = StringStream;
+
+ // TEXTMARKERS
+
+ function TextMarker(cm, type) {
+ this.lines = [];
+ this.type = type;
+ this.cm = cm;
+ }
+
+ TextMarker.prototype.clear = function() {
+ if (this.explicitlyCleared) return;
+ startOperation(this.cm);
+ var min = null, max = null;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this);
+ if (span.to != null) max = lineNo(line);
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
+ if (span.from != null)
+ min = lineNo(line);
+ else if (this.collapsed && !lineIsHidden(line))
+ updateLineHeight(line, textHeight(this.cm.display));
+ }
+ if (min != null) regChange(this.cm, min, max + 1);
+ this.lines.length = 0;
+ this.explicitlyCleared = true;
+ if (this.collapsed && this.cm.view.cantEdit) {
+ this.cm.view.cantEdit = false;
+ reCheckSelection(this.cm);
+ }
+ endOperation(this.cm);
+ signalLater(this.cm, this, "clear");
+ };
+
+ TextMarker.prototype.find = function() {
+ var from, to;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this);
+ if (span.from != null || span.to != null) {
+ var found = lineNo(line);
+ if (span.from != null) from = {line: found, ch: span.from};
+ if (span.to != null) to = {line: found, ch: span.to};
+ }
+ }
+ if (this.type == "bookmark") return from;
+ return from && {from: from, to: to};
+ };
+
+ function markText(cm, from, to, options, type) {
+ var doc = cm.view.doc;
+ var marker = new TextMarker(cm, type);
+ if (type == "range" && !posLess(from, to)) return marker;
+ if (options) for (var opt in options) if (options.hasOwnProperty(opt))
+ marker[opt] = options[opt];
+ if (marker.replacedWith) {
+ marker.collapsed = true;
+ marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
+ }
+ if (marker.collapsed) sawCollapsedSpans = true;
+
+ var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd;
+ doc.iter(curLine, to.line + 1, function(line) {
+ var span = {from: null, to: null, marker: marker};
+ size += line.text.length;
+ if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
+ if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
+ if (marker.collapsed) {
+ if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
+ if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
+ else updateLineHeight(line, 0);
+ }
+ addMarkedSpan(line, span);
+ if (marker.collapsed && curLine == from.line && lineIsHidden(line))
+ updateLineHeight(line, 0);
+ ++curLine;
+ });
+
+ if (marker.readOnly) {
+ sawReadOnlySpans = true;
+ if (cm.view.history.done.length || cm.view.history.undone.length)
+ cm.clearHistory();
+ }
+ if (marker.collapsed) {
+ if (collapsedAtStart != collapsedAtEnd)
+ throw new Error("Inserting collapsed marker overlapping an existing one");
+ marker.size = size;
+ marker.atomic = true;
+ }
+ if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed)
+ regChange(cm, from.line, to.line + 1);
+ if (marker.atomic) reCheckSelection(cm);
+ return marker;
+ }
+
+ // TEXTMARKER SPANS
+
+ function getMarkedSpanFor(spans, marker) {
+ if (spans) for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.marker == marker) return span;
+ }
+ }
+ function removeMarkedSpan(spans, span) {
+ for (var r, i = 0; i < spans.length; ++i)
+ if (spans[i] != span) (r || (r = [])).push(spans[i]);
+ return r;
+ }
+ function addMarkedSpan(line, span) {
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
+ span.marker.lines.push(line);
+ }
+
+ function markedSpansBefore(old, startCh) {
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
+ if (startsBefore || marker.type == "bookmark" && span.from == startCh) {
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
+ (nw || (nw = [])).push({from: span.from,
+ to: endsAfter ? null : span.to,
+ marker: marker});
+ }
+ }
+ return nw;
+ }
+
+ function markedSpansAfter(old, startCh, endCh) {
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
+ if (endsAfter || marker.type == "bookmark" && span.from == endCh && span.from != startCh) {
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
+ (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
+ to: span.to == null ? null : span.to - endCh,
+ marker: marker});
+ }
+ }
+ return nw;
+ }
+
+ function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) {
+ if (!oldFirst && !oldLast) return newText;
+ // Get the spans that 'stick out' on both sides
+ var first = markedSpansBefore(oldFirst, startCh);
+ var last = markedSpansAfter(oldLast, startCh, endCh);
+
+ // Next, merge those two ends
+ var sameLine = newText.length == 1, offset = lst(newText).length + (sameLine ? startCh : 0);
+ if (first) {
+ // Fix up .to properties of first
+ for (var i = 0; i < first.length; ++i) {
+ var span = first[i];
+ if (span.to == null) {
+ var found = getMarkedSpanFor(last, span.marker);
+ if (!found) span.to = startCh;
+ else if (sameLine) span.to = found.to == null ? null : found.to + offset;
+ }
+ }
+ }
+ if (last) {
+ // Fix up .from in last (or move them into first in case of sameLine)
+ for (var i = 0; i < last.length; ++i) {
+ var span = last[i];
+ if (span.to != null) span.to += offset;
+ if (span.from == null) {
+ var found = getMarkedSpanFor(first, span.marker);
+ if (!found) {
+ span.from = offset;
+ if (sameLine) (first || (first = [])).push(span);
+ }
+ } else {
+ span.from += offset;
+ if (sameLine) (first || (first = [])).push(span);
+ }
+ }
+ }
+
+ var newMarkers = [newHL(newText[0], first)];
+ if (!sameLine) {
+ // Fill gap with whole-line-spans
+ var gap = newText.length - 2, gapMarkers;
+ if (gap > 0 && first)
+ for (var i = 0; i < first.length; ++i)
+ if (first[i].to == null)
+ (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
+ for (var i = 0; i < gap; ++i)
+ newMarkers.push(newHL(newText[i+1], gapMarkers));
+ newMarkers.push(newHL(lst(newText), last));
+ }
+ return newMarkers;
+ }
+
+ function removeReadOnlyRanges(doc, from, to) {
+ var markers = null;
+ doc.iter(from.line, to.line + 1, function(line) {
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
+ var mark = line.markedSpans[i].marker;
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
+ (markers || (markers = [])).push(mark);
+ }
+ });
+ if (!markers) return null;
+ var parts = [{from: from, to: to}];
+ for (var i = 0; i < markers.length; ++i) {
+ var m = markers[i].find();
+ for (var j = 0; j < parts.length; ++j) {
+ var p = parts[j];
+ if (!posLess(m.from, p.to) || posLess(m.to, p.from)) continue;
+ var newParts = [j, 1];
+ if (posLess(p.from, m.from)) newParts.push({from: p.from, to: m.from});
+ if (posLess(m.to, p.to)) newParts.push({from: m.to, to: p.to});
+ parts.splice.apply(parts, newParts);
+ j += newParts.length - 1;
+ }
+ }
+ return parts;
+ }
+
+ function collapsedSpanAt(line, ch) {
+ var sps = sawCollapsedSpans && line.markedSpans, found;
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (!sp.marker.collapsed) continue;
+ if ((sp.from == null || sp.from < ch) &&
+ (sp.to == null || sp.to > ch) &&
+ (!found || found.width < sp.marker.width))
+ found = sp.marker;
+ }
+ return found;
+ }
+ function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
+ function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
+
+ function visualLine(doc, line) {
+ var merged;
+ while (merged = collapsedSpanAtStart(line))
+ line = getLine(doc, merged.find().from.line);
+ return line;
+ }
+
+ function lineIsHidden(line) {
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (!sp.marker.collapsed) continue;
+ if (sp.from == null) return true;
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(line, sp))
+ return true;
+ }
+ }
+ window.lineIsHidden = lineIsHidden;
+ function lineIsHiddenInner(line, span) {
+ if (span.to == null || span.marker.inclusiveRight && span.to == line.text.length)
+ return true;
+ for (var sp, i = 0; i < line.markedSpans.length; ++i) {
+ sp = line.markedSpans[i];
+ if (sp.marker.collapsed && sp.from == span.to &&
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
+ lineIsHiddenInner(line, sp)) return true;
+ }
+ }
+
+ // hl stands for history-line, a data structure that can be either a
+ // string (line without markers) or a {text, markedSpans} object.
+ function hlText(val) { return typeof val == "string" ? val : val.text; }
+ function hlSpans(val) {
+ if (typeof val == "string") return null;
+ var spans = val.markedSpans, out = null;
+ for (var i = 0; i < spans.length; ++i) {
+ if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
+ else if (out) out.push(spans[i]);
+ }
+ return !out ? spans : out.length ? out : null;
+ }
+ function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; }
+
+ function detachMarkedSpans(line) {
+ var spans = line.markedSpans;
+ if (!spans) return;
+ for (var i = 0; i < spans.length; ++i) {
+ var lines = spans[i].marker.lines;
+ var ix = indexOf(lines, line);
+ lines.splice(ix, 1);
+ }
+ line.markedSpans = null;
+ }
+
+ function attachMarkedSpans(line, spans) {
+ if (!spans) return;
+ for (var i = 0; i < spans.length; ++i)
+ spans[i].marker.lines.push(line);
+ line.markedSpans = spans;
+ }
+
+ // LINE DATA STRUCTURE
+
+ // Line objects. These hold state related to a line, including
+ // highlighting info (the styles array).
+ function makeLine(text, markedSpans, height) {
+ var line = {text: text, height: height};
+ attachMarkedSpans(line, markedSpans);
+ if (lineIsHidden(line)) line.height = 0;
+ return line;
+ }
+
+ function updateLine(cm, line, text, markedSpans) {
+ line.text = text;
+ line.stateAfter = line.styles = null;
+ if (line.order != null) line.order = null;
+ detachMarkedSpans(line);
+ attachMarkedSpans(line, markedSpans);
+ if (lineIsHidden(line)) line.height = 0;
+ else if (!line.height) line.height = textHeight(cm.display);
+ signalLater(cm, line, "change");
+ }
+
+ function cleanUpLine(line) {
+ line.parent = null;
+ detachMarkedSpans(line);
+ }
+
+ // Run the given mode's parser over a line, update the styles
+ // array, which contains alternating fragments of text and CSS
+ // classes.
+ function highlightLine(cm, line, state) {
+ var mode = cm.view.mode, flattenSpans = cm.options.flattenSpans;
+ var changed = !line.styles, pos = 0, curText = "", curStyle = null;
+ var stream = new StringStream(line.text, cm.options.tabSize), st = line.styles || (line.styles = []);
+ if (line.text == "" && mode.blankLine) mode.blankLine(state);
+ while (!stream.eol()) {
+ var style = mode.token(stream, state), substr = stream.current();
+ stream.start = stream.pos;
+ if (!flattenSpans || curStyle != style) {
+ if (curText) {
+ changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1];
+ st[pos++] = curText; st[pos++] = curStyle;
+ }
+ curText = substr; curStyle = style;
+ } else curText = curText + substr;
+ // Give up when line is ridiculously long
+ if (stream.pos > 5000) break;
+ }
+ if (curText) {
+ changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1];
+ st[pos++] = curText; st[pos++] = curStyle;
+ }
+ if (stream.pos > 5000) { st[pos++] = line.text.slice(stream.pos); st[pos++] = null; }
+ if (pos != st.length) { st.length = pos; changed = true; }
+ return changed;
+ }
+
+ // Lightweight form of highlight -- proceed over this line and
+ // update state, but don't save a style array.
+ function processLine(cm, line, state) {
+ var mode = cm.view.mode;
+ var stream = new StringStream(line.text, cm.options.tabSize);
+ if (line.text == "" && mode.blankLine) mode.blankLine(state);
+ while (!stream.eol() && stream.pos <= 5000) {
+ mode.token(stream, state);
+ stream.start = stream.pos;
+ }
+ }
+
+ var styleToClassCache = {};
+ function styleToClass(style) {
+ if (!style) return null;
+ return styleToClassCache[style] ||
+ (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
+ }
+
+ function lineContent(cm, realLine, measure) {
+ var merged, line = realLine, lineBefore, sawBefore, simple = true;
+ while (merged = collapsedSpanAtStart(line)) {
+ simple = false;
+ line = getLine(cm.view.doc, merged.find().from.line);
+ if (!lineBefore) lineBefore = line;
+ }
+
+ var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure,
+ measure: null, addedOne: false, cm: cm};
+ if (line.textClass) builder.pre.className = line.textClass;
+
+ do {
+ if (!line.styles)
+ highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
+ builder.measure = line == realLine && measure;
+ builder.pos = 0;
+ builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
+ if (measure && sawBefore && line != realLine && !builder.addedOne) {
+ measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
+ builder.addedOne = true;
+ }
+ var next = insertLineContent(line, builder);
+ sawBefore = line == lineBefore;
+ if (next) {
+ line = getLine(cm.view.doc, next.to.line);
+ simple = false;
+ }
+ } while (next);
+
+ if (measure && !builder.addedOne)
+ measure[0] = builder.pre.appendChild(simple ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
+ if (!builder.pre.firstChild && !lineIsHidden(realLine))
+ builder.pre.appendChild(document.createTextNode("\u00a0"));
+
+ return builder.pre;
+ }
+
+ var tokenSpecialChars = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g;
+ function buildToken(builder, text, style, startStyle, endStyle) {
+ if (!text) return;
+ if (!tokenSpecialChars.test(text)) {
+ builder.col += text.length;
+ var content = document.createTextNode(text);
+ } else {
+ var content = document.createDocumentFragment(), pos = 0;
+ while (true) {
+ tokenSpecialChars.lastIndex = pos;
+ var m = tokenSpecialChars.exec(text);
+ var skipped = m ? m.index - pos : text.length - pos;
+ if (skipped) {
+ content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
+ builder.col += skipped;
+ }
+ if (!m) break;
+ pos += skipped + 1;
+ if (m[0] == "\t") {
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
+ content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
+ builder.col += tabWidth;
+ } else {
+ var token = elt("span", "\u2022", "cm-invalidchar");
+ token.title = "\\u" + m[0].charCodeAt(0).toString(16);
+ content.appendChild(token);
+ builder.col += 1;
+ }
+ }
+ }
+ if (style || startStyle || endStyle || builder.measure) {
+ var fullStyle = style || "";
+ if (startStyle) fullStyle += startStyle;
+ if (endStyle) fullStyle += endStyle;
+ return builder.pre.appendChild(elt("span", [content], fullStyle));
+ }
+ builder.pre.appendChild(content);
+ }
+
+ function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
+ for (var i = 0; i < text.length; ++i) {
+ if (i && i < text.length - 1 &&
+ builder.cm.options.lineWrapping &&
+ spanAffectsWrapping.test(text.slice(i - 1, i + 1)))
+ builder.pre.appendChild(elt("wbr"));
+ builder.measure[builder.pos++] =
+ buildToken(builder, text.charAt(i), style,
+ i == 0 && startStyle, i == text.length - 1 && endStyle);
+ }
+ if (text.length) builder.addedOne = true;
+ }
+
+ function buildCollapsedSpan(builder, size, widget) {
+ if (widget) {
+ if (!builder.display) widget = widget.cloneNode(true);
+ builder.pre.appendChild(widget);
+ if (builder.measure && size) {
+ builder.measure[builder.pos] = widget;
+ builder.addedOne = true;
+ }
+ }
+ builder.pos += size;
+ }
+
+ // Outputs a number of spans to make up a line, taking highlighting
+ // and marked text into account.
+ function insertLineContent(line, builder) {
+ var st = line.styles, spans = line.markedSpans;
+ if (!spans) {
+ for (var i = 0; i < st.length; i+=2)
+ builder.addToken(builder, st[i], styleToClass(st[i+1]));
+ return;
+ }
+
+ var allText = line.text, len = allText.length;
+ var pos = 0, i = 0, text = "", style;
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed;
+ for (;;) {
+ if (nextChange == pos) { // Update current marker set
+ spanStyle = spanEndStyle = spanStartStyle = "";
+ collapsed = null; nextChange = Infinity;
+ var foundBookmark = null;
+ for (var j = 0; j < spans.length; ++j) {
+ var sp = spans[j], m = sp.marker;
+ if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
+ if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
+ if (m.className) spanStyle += " " + m.className;
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
+ if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
+ if (m.collapsed && (!collapsed || collapsed.marker.width < m.width))
+ collapsed = sp;
+ } else if (sp.from > pos && nextChange > sp.from) {
+ nextChange = sp.from;
+ }
+ if (m.type == "bookmark" && sp.from == pos && m.replacedWith)
+ foundBookmark = m.replacedWith;
+ }
+ if (collapsed && (collapsed.from || 0) == pos) {
+ buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
+ collapsed.from != null && collapsed.marker.replacedWith);
+ if (collapsed.to == null) return collapsed.marker.find();
+ }
+ if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
+ }
+ if (pos >= len) break;
+
+ var upto = Math.min(len, nextChange);
+ while (true) {
+ if (text) {
+ var end = pos + text.length;
+ if (!collapsed) {
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
+ builder.addToken(builder, tokenText, style + spanStyle,
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "");
+ }
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
+ pos = end;
+ spanStartStyle = "";
+ }
+ text = st[i++]; style = styleToClass(st[i++]);
+ }
+ }
+ }
+
+ // DOCUMENT DATA STRUCTURE
+
+ function LeafChunk(lines) {
+ this.lines = lines;
+ this.parent = null;
+ for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
+ lines[i].parent = this;
+ height += lines[i].height;
+ }
+ this.height = height;
+ }
+
+ LeafChunk.prototype = {
+ chunkSize: function() { return this.lines.length; },
+ remove: function(at, n, cm) {
+ for (var i = at, e = at + n; i < e; ++i) {
+ var line = this.lines[i];
+ this.height -= line.height;
+ cleanUpLine(line);
+ signalLater(cm, line, "delete");
+ }
+ this.lines.splice(at, n);
+ },
+ collapse: function(lines) {
+ lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
+ },
+ insertHeight: function(at, lines, height) {
+ this.height += height;
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
+ for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
+ },
+ iterN: function(at, n, op) {
+ for (var e = at + n; at < e; ++at)
+ if (op(this.lines[at])) return true;
+ }
+ };
+
+ function BranchChunk(children) {
+ this.children = children;
+ var size = 0, height = 0;
+ for (var i = 0, e = children.length; i < e; ++i) {
+ var ch = children[i];
+ size += ch.chunkSize(); height += ch.height;
+ ch.parent = this;
+ }
+ this.size = size;
+ this.height = height;
+ this.parent = null;
+ }
+
+ BranchChunk.prototype = {
+ chunkSize: function() { return this.size; },
+ remove: function(at, n, callbacks) {
+ this.size -= n;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
+ child.remove(at, rm, callbacks);
+ this.height -= oldHeight - child.height;
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
+ if ((n -= rm) == 0) break;
+ at = 0;
+ } else at -= sz;
+ }
+ if (this.size - n < 25) {
+ var lines = [];
+ this.collapse(lines);
+ this.children = [new LeafChunk(lines)];
+ this.children[0].parent = this;
+ }
+ },
+ collapse: function(lines) {
+ for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
+ },
+ insert: function(at, lines) {
+ var height = 0;
+ for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
+ this.insertHeight(at, lines, height);
+ },
+ insertHeight: function(at, lines, height) {
+ this.size += lines.length;
+ this.height += height;
+ for (var i = 0, e = this.children.length; i < e; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at <= sz) {
+ child.insertHeight(at, lines, height);
+ if (child.lines && child.lines.length > 50) {
+ while (child.lines.length > 50) {
+ var spilled = child.lines.splice(child.lines.length - 25, 25);
+ var newleaf = new LeafChunk(spilled);
+ child.height -= newleaf.height;
+ this.children.splice(i + 1, 0, newleaf);
+ newleaf.parent = this;
+ }
+ this.maybeSpill();
+ }
+ break;
+ }
+ at -= sz;
+ }
+ },
+ maybeSpill: function() {
+ if (this.children.length <= 10) return;
+ var me = this;
+ do {
+ var spilled = me.children.splice(me.children.length - 5, 5);
+ var sibling = new BranchChunk(spilled);
+ if (!me.parent) { // Become the parent node
+ var copy = new BranchChunk(me.children);
+ copy.parent = me;
+ me.children = [copy, sibling];
+ me = copy;
+ } else {
+ me.size -= sibling.size;
+ me.height -= sibling.height;
+ var myIndex = indexOf(me.parent.children, me);
+ me.parent.children.splice(myIndex + 1, 0, sibling);
+ }
+ sibling.parent = me.parent;
+ } while (me.children.length > 10);
+ me.parent.maybeSpill();
+ },
+ iter: function(from, to, op) { this.iterN(from, to - from, op); },
+ iterN: function(at, n, op) {
+ for (var i = 0, e = this.children.length; i < e; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var used = Math.min(n, sz - at);
+ if (child.iterN(at, used, op)) return true;
+ if ((n -= used) == 0) break;
+ at = 0;
+ } else at -= sz;
+ }
+ }
+ };
+
+ // LINE UTILITIES
+
+ function getLine(chunk, n) {
+ while (!chunk.lines) {
+ for (var i = 0;; ++i) {
+ var child = chunk.children[i], sz = child.chunkSize();
+ if (n < sz) { chunk = child; break; }
+ n -= sz;
+ }
+ }
+ return chunk.lines[n];
+ }
+
+ function updateLineHeight(line, height) {
+ var diff = height - line.height;
+ for (var n = line; n; n = n.parent) n.height += diff;
+ }
+
+ function lineNo(line) {
+ if (line.parent == null) return null;
+ var cur = line.parent, no = indexOf(cur.lines, line);
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
+ for (var i = 0;; ++i) {
+ if (chunk.children[i] == cur) break;
+ no += chunk.children[i].chunkSize();
+ }
+ }
+ return no;
+ }
+
+ function lineAtHeight(chunk, h) {
+ var n = 0;
+ outer: do {
+ for (var i = 0, e = chunk.children.length; i < e; ++i) {
+ var child = chunk.children[i], ch = child.height;
+ if (h < ch) { chunk = child; continue outer; }
+ h -= ch;
+ n += child.chunkSize();
+ }
+ return n;
+ } while (!chunk.lines);
+ for (var i = 0, e = chunk.lines.length; i < e; ++i) {
+ var line = chunk.lines[i], lh = line.height;
+ if (h < lh) break;
+ h -= lh;
+ }
+ return n + i;
+ }
+
+ function heightAtLine(cm, lineObj) {
+ lineObj = visualLine(cm.view.doc, lineObj);
+
+ var h = 0, chunk = lineObj.parent;
+ for (var i = 0; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i];
+ if (line == lineObj) break;
+ else h += line.height;
+ }
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
+ for (var i = 0; i < p.children.length; ++i) {
+ var cur = p.children[i];
+ if (cur == chunk) break;
+ else h += cur.height;
+ }
+ }
+ return h;
+ }
+
+ function getOrder(line) {
+ var order = line.order;
+ if (order == null) order = line.order = bidiOrdering(line.text);
+ return order;
+ }
+
+ // HISTORY
+
+ function makeHistory() {
+ return {
+ // Arrays of history events. Doing something adds an event to
+ // done and clears undo. Undoing moves events from done to
+ // undone, redoing moves them in the other direction.
+ done: [], undone: [],
+ // Used to track when changes can be merged into a single undo
+ // event
+ lastTime: 0, lastOp: null, lastOrigin: null,
+ // Used by the isClean() method
+ dirtyCounter: 0
+ };
+ }
+
+ function addChange(cm, start, added, old, origin, fromBefore, toBefore, fromAfter, toAfter) {
+ var history = cm.view.history;
+ history.undone.length = 0;
+ var time = +new Date, cur = lst(history.done);
+
+ if (cur &&
+ (history.lastOp == cm.curOp.id ||
+ history.lastOrigin == origin && (origin == "input" || origin == "delete") &&
+ history.lastTime > time - 600)) {
+ // Merge this change into the last event
+ var last = lst(cur.events);
+ if (last.start > start + old.length || last.start + last.added < start) {
+ // Doesn't intersect with last sub-event, add new sub-event
+ cur.events.push({start: start, added: added, old: old});
+ } else {
+ // Patch up the last sub-event
+ var startBefore = Math.max(0, last.start - start),
+ endAfter = Math.max(0, (start + old.length) - (last.start + last.added));
+ for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]);
+ for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]);
+ if (startBefore) last.start = start;
+ last.added += added - (old.length - startBefore - endAfter);
+ }
+ cur.fromAfter = fromAfter; cur.toAfter = toAfter;
+ } else {
+ // Can not be merged, start a new event.
+ cur = {events: [{start: start, added: added, old: old}],
+ fromBefore: fromBefore, toBefore: toBefore, fromAfter: fromAfter, toAfter: toAfter};
+ history.done.push(cur);
+ while (history.done.length > cm.options.undoDepth)
+ history.done.shift();
+ if (history.dirtyCounter < 0)
+ // The user has made a change after undoing past the last clean state.
+ // We can never get back to a clean state now until markClean() is called.
+ history.dirtyCounter = NaN;
+ else
+ history.dirtyCounter++;
+ }
+ history.lastTime = time;
+ history.lastOp = cm.curOp.id;
+ history.lastOrigin = origin;
+ }
+
+ // EVENT OPERATORS
+
+ function stopMethod() {e_stop(this);}
+ // Ensure an event has a stop method.
+ function addStop(event) {
+ if (!event.stop) event.stop = stopMethod;
+ return event;
+ }
+
+ function e_preventDefault(e) {
+ if (e.preventDefault) e.preventDefault();
+ else e.returnValue = false;
+ }
+ function e_stopPropagation(e) {
+ if (e.stopPropagation) e.stopPropagation();
+ else e.cancelBubble = true;
+ }
+ function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
+ CodeMirror.e_stop = e_stop;
+ CodeMirror.e_preventDefault = e_preventDefault;
+ CodeMirror.e_stopPropagation = e_stopPropagation;
+
+ function e_target(e) {return e.target || e.srcElement;}
+ function e_button(e) {
+ var b = e.which;
+ if (b == null) {
+ if (e.button & 1) b = 1;
+ else if (e.button & 2) b = 3;
+ else if (e.button & 4) b = 2;
+ }
+ if (mac && e.ctrlKey && b == 1) b = 3;
+ return b;
+ }
+
+ // Allow 3rd-party code to override event properties by adding an override
+ // object to an event object.
+ function e_prop(e, prop) {
+ var overridden = e.override && e.override.hasOwnProperty(prop);
+ return overridden ? e.override[prop] : e[prop];
+ }
+
+ // EVENT HANDLING
+
+ function on(emitter, type, f) {
+ if (emitter.addEventListener)
+ emitter.addEventListener(type, f, false);
+ else if (emitter.attachEvent)
+ emitter.attachEvent("on" + type, f);
+ else {
+ var map = emitter._handlers || (emitter._handlers = {});
+ var arr = map[type] || (map[type] = []);
+ arr.push(f);
+ }
+ }
+
+ function off(emitter, type, f) {
+ if (emitter.removeEventListener)
+ emitter.removeEventListener(type, f, false);
+ else if (emitter.detachEvent)
+ emitter.detachEvent("on" + type, f);
+ else {
+ var arr = emitter._handlers && emitter._handlers[type];
+ if (!arr) return;
+ for (var i = 0; i < arr.length; ++i)
+ if (arr[i] == f) { arr.splice(i, 1); break; }
+ }
+ }
+
+ function signal(emitter, type /*, values...*/) {
+ var arr = emitter._handlers && emitter._handlers[type];
+ if (!arr) return;
+ var args = Array.prototype.slice.call(arguments, 2);
+ for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
+ }
+
+ function signalLater(cm, emitter, type /*, values...*/) {
+ var arr = emitter._handlers && emitter._handlers[type];
+ if (!arr) return;
+ var args = Array.prototype.slice.call(arguments, 3), flist = cm.curOp && cm.curOp.delayedCallbacks;
+ function bnd(f) {return function(){f.apply(null, args);};};
+ for (var i = 0; i < arr.length; ++i)
+ if (flist) flist.push(bnd(arr[i]));
+ else arr[i].apply(null, args);
+ }
+
+ function hasHandler(emitter, type) {
+ var arr = emitter._handlers && emitter._handlers[type];
+ return arr && arr.length > 0;
+ }
+
+ CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
+
+ // MISC UTILITIES
+
+ // Number of pixels added to scroller and sizer to hide scrollbar
+ var scrollerCutOff = 30;
+
+ // Returned or thrown by various protocols to signal 'I'm not
+ // handling this'.
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
+
+ function Delayed() {this.id = null;}
+ Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
+
+ // Counts the column offset in a string, taking tabs into account.
+ // Used mostly to find indentation.
+ function countColumn(string, end, tabSize) {
+ if (end == null) {
+ end = string.search(/[^\s\u00a0]/);
+ if (end == -1) end = string.length;
+ }
+ for (var i = 0, n = 0; i < end; ++i) {
+ if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
+ else ++n;
+ }
+ return n;
+ }
+ CodeMirror.countColumn = countColumn;
+
+ var spaceStrs = [""];
+ function spaceStr(n) {
+ while (spaceStrs.length <= n)
+ spaceStrs.push(lst(spaceStrs) + " ");
+ return spaceStrs[n];
+ }
+
+ function lst(arr) { return arr[arr.length-1]; }
+
+ function selectInput(node) {
+ if (ios) { // Mobile Safari apparently has a bug where select() is broken.
+ node.selectionStart = 0;
+ node.selectionEnd = node.value.length;
+ } else node.select();
+ }
+
+ function indexOf(collection, elt) {
+ if (collection.indexOf) return collection.indexOf(elt);
+ for (var i = 0, e = collection.length; i < e; ++i)
+ if (collection[i] == elt) return i;
+ return -1;
+ }
+
+ function emptyArray(size) {
+ for (var a = [], i = 0; i < size; ++i) a.push(undefined);
+ return a;
+ }
+
+ function bind(f) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function(){return f.apply(null, args);};
+ }
+
+ var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/;
+ function isWordChar(ch) {
+ return /\w/.test(ch) || ch > "\x80" &&
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
+ }
+
+ function isEmpty(obj) {
+ var c = 0;
+ for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) ++c;
+ return !c;
+ }
+
+ var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F]/;
+
+ // DOM UTILITIES
+
+ function elt(tag, content, className, style) {
+ var e = document.createElement(tag);
+ if (className) e.className = className;
+ if (style) e.style.cssText = style;
+ if (typeof content == "string") setTextContent(e, content);
+ else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
+ return e;
+ }
+
+ function removeChildren(e) {
+ e.innerHTML = "";
+ return e;
+ }
+
+ function removeChildrenAndAdd(parent, e) {
+ return removeChildren(parent).appendChild(e);
+ }
+
+ function setTextContent(e, str) {
+ if (ie_lt9) {
+ e.innerHTML = "";
+ e.appendChild(document.createTextNode(str));
+ } else e.textContent = str;
+ }
+
+ // FEATURE DETECTION
+
+ // Detect drag-and-drop
+ var dragAndDrop = function() {
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
+ // couldn't get it to work yet.
+ if (ie_lt9) return false;
+ var div = elt('div');
+ return "draggable" in div || "dragDrop" in div;
+ }();
+
+ // For a reason I have yet to figure out, some browsers disallow
+ // word wrapping between certain characters *only* if a new inline
+ // element is started between them. This makes it hard to reliably
+ // measure the position of things, since that requires inserting an
+ // extra span. This terribly fragile set of regexps matches the
+ // character combinations that suffer from this phenomenon on the
+ // various browsers.
+ var spanAffectsWrapping = /^$/; // Won't match any two-character string
+ if (gecko) spanAffectsWrapping = /$'/;
+ else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/;
+ else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/;
+
+ var knownScrollbarWidth;
+ function scrollbarWidth(measure) {
+ if (knownScrollbarWidth != null) return knownScrollbarWidth;
+ var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
+ removeChildrenAndAdd(measure, test);
+ if (test.offsetWidth)
+ knownScrollbarWidth = test.offsetHeight - test.clientHeight;
+ return knownScrollbarWidth || 0;
+ }
+
+ var zwspSupported;
+ function zeroWidthElement(measure) {
+ if (zwspSupported == null) {
+ var test = elt("span", "\u200b");
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
+ if (measure.firstChild.offsetHeight != 0)
+ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
+ }
+ if (zwspSupported) return elt("span", "\u200b");
+ else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
+ }
+
+ // See if "".split is the broken IE version, if so, provide an
+ // alternative way to split lines.
+ var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
+ var pos = 0, result = [], l = string.length;
+ while (pos <= l) {
+ var nl = string.indexOf("\n", pos);
+ if (nl == -1) nl = string.length;
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
+ var rt = line.indexOf("\r");
+ if (rt != -1) {
+ result.push(line.slice(0, rt));
+ pos += rt + 1;
+ } else {
+ result.push(line);
+ pos = nl + 1;
+ }
+ }
+ return result;
+ } : function(string){return string.split(/\r\n?|\n/);};
+ CodeMirror.splitLines = splitLines;
+
+ var hasSelection = window.getSelection ? function(te) {
+ try { return te.selectionStart != te.selectionEnd; }
+ catch(e) { return false; }
+ } : function(te) {
+ try {var range = te.ownerDocument.selection.createRange();}
+ catch(e) {}
+ if (!range || range.parentElement() != te) return false;
+ return range.compareEndPoints("StartToEnd", range) != 0;
+ };
+
+ var hasCopyEvent = (function() {
+ var e = elt("div");
+ if ("oncopy" in e) return true;
+ e.setAttribute("oncopy", "return;");
+ return typeof e.oncopy == 'function';
+ })();
+
+ // KEY NAMING
+
+ var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
+ 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
+ 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
+ 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
+ 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
+ CodeMirror.keyNames = keyNames;
+ (function() {
+ // Number keys
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
+ // Alphabetic keys
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
+ // Function keys
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
+ })();
+
+ // BIDI HELPERS
+
+ function iterateBidiSections(order, from, to, f) {
+ if (!order) return f(from, to, "ltr");
+ for (var i = 0; i < order.length; ++i) {
+ var part = order[i];
+ if (part.from < to && part.to > from)
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
+ }
+ }
+
+ function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
+ function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
+
+ function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
+ function lineRight(line) {
+ var order = getOrder(line);
+ if (!order) return line.text.length;
+ return bidiRight(lst(order));
+ }
+
+ function lineStart(cm, lineN) {
+ var line = getLine(cm.view.doc, lineN);
+ var visual = visualLine(cm.view.doc, line);
+ if (visual != line) lineN = lineNo(visual);
+ var order = getOrder(visual);
+ var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
+ return {line: lineN, ch: ch};
+ }
+ function lineEnd(cm, lineNo) {
+ var merged, line;
+ while (merged = collapsedSpanAtEnd(line = getLine(cm.view.doc, lineNo)))
+ lineNo = merged.find().to.line;
+ var order = getOrder(line);
+ var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
+ return {line: lineNo, ch: ch};
+ }
+
+ // This is somewhat involved. It is needed in order to move
+ // 'visually' through bi-directional text -- i.e., pressing left
+ // should make the cursor go left, even when in RTL text. The
+ // tricky part is the 'jumps', where RTL and LTR text touch each
+ // other. This often requires the cursor offset to move more than
+ // one unit, in order to visually move one unit.
+ function moveVisually(line, start, dir, byUnit) {
+ var bidi = getOrder(line);
+ if (!bidi) return moveLogically(line, start, dir, byUnit);
+ var moveOneUnit = byUnit ? function(pos, dir) {
+ do pos += dir;
+ while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
+ return pos;
+ } : function(pos, dir) { return pos + dir; };
+ var linedir = bidi[0].level;
+ for (var i = 0; i < bidi.length; ++i) {
+ var part = bidi[i], sticky = part.level % 2 == linedir;
+ if ((part.from < start && part.to > start) ||
+ (sticky && (part.from == start || part.to == start))) break;
+ }
+ var target = moveOneUnit(start, part.level % 2 ? -dir : dir);
+
+ while (target != null) {
+ if (part.level % 2 == linedir) {
+ if (target < part.from || target > part.to) {
+ part = bidi[i += dir];
+ target = part && (dir > 0 == part.level % 2 ? moveOneUnit(part.to, -1) : moveOneUnit(part.from, 1));
+ } else break;
+ } else {
+ if (target == bidiLeft(part)) {
+ part = bidi[--i];
+ target = part && bidiRight(part);
+ } else if (target == bidiRight(part)) {
+ part = bidi[++i];
+ target = part && bidiLeft(part);
+ } else break;
+ }
+ }
+
+ return target < 0 || target > line.text.length ? null : target;
+ }
+
+ function moveLogically(line, start, dir, byUnit) {
+ var target = start + dir;
+ if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
+ return target < 0 || target > line.text.length ? null : target;
+ }
+
+ // Bidirectional ordering algorithm
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
+ // that this (partially) implements.
+
+ // One-char codes used for character types:
+ // L (L): Left-to-Right
+ // R (R): Right-to-Left
+ // r (AL): Right-to-Left Arabic
+ // 1 (EN): European Number
+ // + (ES): European Number Separator
+ // % (ET): European Number Terminator
+ // n (AN): Arabic Number
+ // , (CS): Common Number Separator
+ // m (NSM): Non-Spacing Mark
+ // b (BN): Boundary Neutral
+ // s (B): Paragraph Separator
+ // t (S): Segment Separator
+ // w (WS): Whitespace
+ // N (ON): Other Neutrals
+
+ // Returns null if characters are ordered as they appear
+ // (left-to-right), or an array of sections ({from, to, level}
+ // objects) in the order in which they occur visually.
+ var bidiOrdering = (function() {
+ // Character types for codepoints 0 to 0xff
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
+ // Character types for codepoints 0x600 to 0x6ff
+ var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
+ function charType(code) {
+ if (code <= 0xff) return lowTypes.charAt(code);
+ else if (0x590 <= code && code <= 0x5f4) return "R";
+ else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
+ else if (0x700 <= code && code <= 0x8ac) return "r";
+ else return "L";
+ }
+
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
+
+ return function charOrdering(str) {
+ if (!bidiRE.test(str)) return false;
+ var len = str.length, types = [], startType = null;
+ for (var i = 0, type; i < len; ++i) {
+ types.push(type = charType(str.charCodeAt(i)));
+ if (startType == null) {
+ if (type == "L") startType = "L";
+ else if (type == "R" || type == "r") startType = "R";
+ }
+ }
+ if (startType == null) startType = "L";
+
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
+ // change the type of the NSM to the type of the previous
+ // character. If the NSM is at the start of the level run, it will
+ // get the type of sor.
+ for (var i = 0, prev = startType; i < len; ++i) {
+ var type = types[i];
+ if (type == "m") types[i] = prev;
+ else prev = type;
+ }
+
+ // W2. Search backwards from each instance of a European number
+ // until the first strong type (R, L, AL, or sor) is found. If an
+ // AL is found, change the type of the European number to Arabic
+ // number.
+ // W3. Change all ALs to R.
+ for (var i = 0, cur = startType; i < len; ++i) {
+ var type = types[i];
+ if (type == "1" && cur == "r") types[i] = "n";
+ else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
+ }
+
+ // W4. A single European separator between two European numbers
+ // changes to a European number. A single common separator between
+ // two numbers of the same type changes to that type.
+ for (var i = 1, prev = types[0]; i < len - 1; ++i) {
+ var type = types[i];
+ if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
+ else if (type == "," && prev == types[i+1] &&
+ (prev == "1" || prev == "n")) types[i] = prev;
+ prev = type;
+ }
+
+ // W5. A sequence of European terminators adjacent to European
+ // numbers changes to all European numbers.
+ // W6. Otherwise, separators and terminators change to Other
+ // Neutral.
+ for (var i = 0; i < len; ++i) {
+ var type = types[i];
+ if (type == ",") types[i] = "N";
+ else if (type == "%") {
+ for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
+ var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
+ for (var j = i; j < end; ++j) types[j] = replace;
+ i = end - 1;
+ }
+ }
+
+ // W7. Search backwards from each instance of a European number
+ // until the first strong type (R, L, or sor) is found. If an L is
+ // found, then change the type of the European number to L.
+ for (var i = 0, cur = startType; i < len; ++i) {
+ var type = types[i];
+ if (cur == "L" && type == "1") types[i] = "L";
+ else if (isStrong.test(type)) cur = type;
+ }
+
+ // N1. A sequence of neutrals takes the direction of the
+ // surrounding strong text if the text on both sides has the same
+ // direction. European and Arabic numbers act as if they were R in
+ // terms of their influence on neutrals. Start-of-level-run (sor)
+ // and end-of-level-run (eor) are used at level run boundaries.
+ // N2. Any remaining neutrals take the embedding direction.
+ for (var i = 0; i < len; ++i) {
+ if (isNeutral.test(types[i])) {
+ for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
+ var before = (i ? types[i-1] : startType) == "L";
+ var after = (end < len - 1 ? types[end] : startType) == "L";
+ var replace = before || after ? "L" : "R";
+ for (var j = i; j < end; ++j) types[j] = replace;
+ i = end - 1;
+ }
+ }
+
+ // Here we depart from the documented algorithm, in order to avoid
+ // building up an actual levels array. Since there are only three
+ // levels (0, 1, 2) in an implementation that doesn't take
+ // explicit embedding into account, we can build up the order on
+ // the fly, without following the level-based algorithm.
+ var order = [], m;
+ for (var i = 0; i < len;) {
+ if (countsAsLeft.test(types[i])) {
+ var start = i;
+ for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
+ order.push({from: start, to: i, level: 0});
+ } else {
+ var pos = i, at = order.length;
+ for (++i; i < len && types[i] != "L"; ++i) {}
+ for (var j = pos; j < i;) {
+ if (countsAsNum.test(types[j])) {
+ if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
+ var nstart = j;
+ for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
+ order.splice(at, 0, {from: nstart, to: j, level: 2});
+ pos = j;
+ } else ++j;
+ }
+ if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
+ }
+ }
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
+ order[0].from = m[0].length;
+ order.unshift({from: 0, to: m[0].length, level: 0});
+ }
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
+ lst(order).to -= m[0].length;
+ order.push({from: len - m[0].length, to: len, level: 0});
+ }
+ if (order[0].level != lst(order).level)
+ order.push({from: len, to: len, level: order[0].level});
+
+ return order;
+ };
+ })();
+
+ // THE END
+
+ CodeMirror.version = "3.0";
+
+ return CodeMirror;
+})();
diff -r 8e546d108658 -r b42911b78a16 dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/mode/clike.js
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/mode/clike.js Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,300 @@
+CodeMirror.defineMode("clike", function(config, parserConfig) {
+ var indentUnit = config.indentUnit,
+ statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
+ keywords = parserConfig.keywords || {},
+ builtin = parserConfig.builtin || {},
+ blockKeywords = parserConfig.blockKeywords || {},
+ atoms = parserConfig.atoms || {},
+ hooks = parserConfig.hooks || {},
+ multiLineStrings = parserConfig.multiLineStrings;
+ var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+ var curPunc;
+
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (hooks[ch]) {
+ var result = hooks[ch](stream, state);
+ if (result !== false) return result;
+ }
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ }
+ if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ curPunc = ch;
+ return null;
+ }
+ if (/\d/.test(ch)) {
+ stream.eatWhile(/[\w\.]/);
+ return "number";
+ }
+ if (ch == "/") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ }
+ if (stream.eat("/")) {
+ stream.skipToEnd();
+ return "comment";
+ }
+ }
+ if (isOperatorChar.test(ch)) {
+ stream.eatWhile(isOperatorChar);
+ return "operator";
+ }
+ stream.eatWhile(/[\w\$_]/);
+ var cur = stream.current();
+ if (keywords.propertyIsEnumerable(cur)) {
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+ return "keyword";
+ }
+ if (builtin.propertyIsEnumerable(cur)) {
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+ return "builtin";
+ }
+ if (atoms.propertyIsEnumerable(cur)) return "atom";
+ return "variable";
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next, end = false;
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) {end = true; break;}
+ escaped = !escaped && next == "\\";
+ }
+ if (end || !(escaped || multiLineStrings))
+ state.tokenize = null;
+ return "string";
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "/" && maybeEnd) {
+ state.tokenize = null;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return "comment";
+ }
+
+ function Context(indented, column, type, align, prev) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.align = align;
+ this.prev = prev;
+ }
+ function pushContext(state, col, type) {
+ var indent = state.indented;
+ if (state.context && state.context.type == "statement")
+ indent = state.context.indented;
+ return state.context = new Context(indent, col, type, null, state.context);
+ }
+ function popContext(state) {
+ var t = state.context.type;
+ if (t == ")" || t == "]" || t == "}")
+ state.indented = state.context.indented;
+ return state.context = state.context.prev;
+ }
+
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ return {
+ tokenize: null,
+ context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+ indented: 0,
+ startOfLine: true
+ };
+ },
+
+ token: function(stream, state) {
+ var ctx = state.context;
+ if (stream.sol()) {
+ if (ctx.align == null) ctx.align = false;
+ state.indented = stream.indentation();
+ state.startOfLine = true;
+ }
+ if (stream.eatSpace()) return null;
+ curPunc = null;
+ var style = (state.tokenize || tokenBase)(stream, state);
+ if (style == "comment" || style == "meta") return style;
+ if (ctx.align == null) ctx.align = true;
+
+ if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
+ else if (curPunc == "{") pushContext(state, stream.column(), "}");
+ else if (curPunc == "[") pushContext(state, stream.column(), "]");
+ else if (curPunc == "(") pushContext(state, stream.column(), ")");
+ else if (curPunc == "}") {
+ while (ctx.type == "statement") ctx = popContext(state);
+ if (ctx.type == "}") ctx = popContext(state);
+ while (ctx.type == "statement") ctx = popContext(state);
+ }
+ else if (curPunc == ctx.type) popContext(state);
+ else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
+ pushContext(state, stream.column(), "statement");
+ state.startOfLine = false;
+ return style;
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
+ var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+ if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+ var closing = firstChar == ctx.type;
+ if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
+ else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+ else return ctx.indented + (closing ? 0 : indentUnit);
+ },
+
+ electricChars: "{}"
+ };
+});
+
+(function() {
+ function words(str) {
+ var obj = {}, words = str.split(" ");
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+ return obj;
+ }
+ var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
+ "double static else struct entry switch extern typedef float union for unsigned " +
+ "goto while enum void const signed volatile";
+
+ function cppHook(stream, state) {
+ if (!state.startOfLine) return false;
+ for (;;) {
+ if (stream.skipTo("\\")) {
+ stream.next();
+ if (stream.eol()) {
+ state.tokenize = cppHook;
+ break;
+ }
+ } else {
+ stream.skipToEnd();
+ state.tokenize = null;
+ break;
+ }
+ }
+ return "meta";
+ }
+
+ // C#-style strings where "" escapes a quote.
+ function tokenAtString(stream, state) {
+ var next;
+ while ((next = stream.next()) != null) {
+ if (next == '"' && !stream.eat('"')) {
+ state.tokenize = null;
+ break;
+ }
+ }
+ return "string";
+ }
+
+ function mimes(ms, mode) {
+ for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
+ }
+
+ mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], {
+ name: "clike",
+ keywords: words(cKeywords),
+ blockKeywords: words("case do else for if switch while struct"),
+ atoms: words("null"),
+ hooks: {"#": cppHook}
+ });
+ mimes(["text/x-c++src", "text/x-c++hdr"], {
+ name: "clike",
+ keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
+ "static_cast typeid catch operator template typename class friend private " +
+ "this using const_cast inline public throw virtual delete mutable protected " +
+ "wchar_t"),
+ blockKeywords: words("catch class do else finally for if struct switch try while"),
+ atoms: words("true false null"),
+ hooks: {"#": cppHook}
+ });
+ CodeMirror.defineMIME("text/x-java", {
+ name: "clike",
+ keywords: words("abstract assert boolean break byte case catch char class const continue default " +
+ "do double else enum extends final finally float for goto if implements import " +
+ "instanceof int interface long native new package private protected public " +
+ "return short static strictfp super switch synchronized this throw throws transient " +
+ "try void volatile while"),
+ blockKeywords: words("catch class do else finally for if switch try while"),
+ atoms: words("true false null"),
+ hooks: {
+ "@": function(stream) {
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ }
+ }
+ });
+ CodeMirror.defineMIME("text/x-csharp", {
+ name: "clike",
+ keywords: words("abstract as base break case catch checked class const continue" +
+ " default delegate do else enum event explicit extern finally fixed for" +
+ " foreach goto if implicit in interface internal is lock namespace new" +
+ " operator out override params private protected public readonly ref return sealed" +
+ " sizeof stackalloc static struct switch this throw try typeof unchecked" +
+ " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
+ " global group into join let orderby partial remove select set value var yield"),
+ blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
+ builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
+ " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
+ " UInt64 bool byte char decimal double short int long object" +
+ " sbyte float string ushort uint ulong"),
+ atoms: words("true false null"),
+ hooks: {
+ "@": function(stream, state) {
+ if (stream.eat('"')) {
+ state.tokenize = tokenAtString;
+ return tokenAtString(stream, state);
+ }
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ }
+ }
+ });
+ CodeMirror.defineMIME("text/x-scala", {
+ name: "clike",
+ keywords: words(
+
+ /* scala */
+ "abstract case catch class def do else extends false final finally for forSome if " +
+ "implicit import lazy match new null object override package private protected return " +
+ "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
+ "<% >: # @ " +
+
+ /* package scala */
+ "assert assume require print println printf readLine readBoolean readByte readShort " +
+ "readChar readInt readLong readFloat readDouble " +
+
+ "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
+ "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
+ "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
+ "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
+ "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
+
+ /* package java.lang */
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
+ "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
+ "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
+ "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
+
+
+ ),
+ blockKeywords: words("catch class do else finally for forSome if match switch try while"),
+ atoms: words("true false null"),
+ hooks: {
+ "@": function(stream) {
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ }
+ }
+ });
+}());
diff -r 8e546d108658 -r b42911b78a16 dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/mode/xml.js
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/mode/xml.js Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,324 @@
+CodeMirror.defineMode("xml", function(config, parserConfig) {
+ var indentUnit = config.indentUnit;
+ var Kludges = parserConfig.htmlMode ? {
+ autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
+ 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
+ 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
+ 'track': true, 'wbr': true},
+ implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
+ 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
+ 'th': true, 'tr': true},
+ contextGrabbers: {
+ 'dd': {'dd': true, 'dt': true},
+ 'dt': {'dd': true, 'dt': true},
+ 'li': {'li': true},
+ 'option': {'option': true, 'optgroup': true},
+ 'optgroup': {'optgroup': true},
+ 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
+ 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
+ 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
+ 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
+ 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
+ 'rp': {'rp': true, 'rt': true},
+ 'rt': {'rp': true, 'rt': true},
+ 'tbody': {'tbody': true, 'tfoot': true},
+ 'td': {'td': true, 'th': true},
+ 'tfoot': {'tbody': true},
+ 'th': {'td': true, 'th': true},
+ 'thead': {'tbody': true, 'tfoot': true},
+ 'tr': {'tr': true}
+ },
+ doNotIndent: {"pre": true},
+ allowUnquoted: true,
+ allowMissing: true
+ } : {
+ autoSelfClosers: {},
+ implicitlyClosed: {},
+ contextGrabbers: {},
+ doNotIndent: {},
+ allowUnquoted: false,
+ allowMissing: false
+ };
+ var alignCDATA = parserConfig.alignCDATA;
+
+ // Return variables for tokenizers
+ var tagName, type;
+
+ function inText(stream, state) {
+ function chain(parser) {
+ state.tokenize = parser;
+ return parser(stream, state);
+ }
+
+ var ch = stream.next();
+ if (ch == "<") {
+ if (stream.eat("!")) {
+ if (stream.eat("[")) {
+ if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
+ else return null;
+ }
+ else if (stream.match("--")) return chain(inBlock("comment", "-->"));
+ else if (stream.match("DOCTYPE", true, true)) {
+ stream.eatWhile(/[\w\._\-]/);
+ return chain(doctype(1));
+ }
+ else return null;
+ }
+ else if (stream.eat("?")) {
+ stream.eatWhile(/[\w\._\-]/);
+ state.tokenize = inBlock("meta", "?>");
+ return "meta";
+ }
+ else {
+ var isClose = stream.eat("/");
+ tagName = "";
+ var c;
+ while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
+ if (!tagName) return "error";
+ type = isClose ? "closeTag" : "openTag";
+ state.tokenize = inTag;
+ return "tag";
+ }
+ }
+ else if (ch == "&") {
+ var ok;
+ if (stream.eat("#")) {
+ if (stream.eat("x")) {
+ ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
+ } else {
+ ok = stream.eatWhile(/[\d]/) && stream.eat(";");
+ }
+ } else {
+ ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
+ }
+ return ok ? "atom" : "error";
+ }
+ else {
+ stream.eatWhile(/[^&<]/);
+ return null;
+ }
+ }
+
+ function inTag(stream, state) {
+ var ch = stream.next();
+ if (ch == ">" || (ch == "/" && stream.eat(">"))) {
+ state.tokenize = inText;
+ type = ch == ">" ? "endTag" : "selfcloseTag";
+ return "tag";
+ }
+ else if (ch == "=") {
+ type = "equals";
+ return null;
+ }
+ else if (/[\'\"]/.test(ch)) {
+ state.tokenize = inAttribute(ch);
+ return state.tokenize(stream, state);
+ }
+ else {
+ stream.eatWhile(/[^\s\u00a0=<>\"\']/);
+ return "word";
+ }
+ }
+
+ function inAttribute(quote) {
+ return function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.next() == quote) {
+ state.tokenize = inTag;
+ break;
+ }
+ }
+ return "string";
+ };
+ }
+
+ function inBlock(style, terminator) {
+ return function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.match(terminator)) {
+ state.tokenize = inText;
+ break;
+ }
+ stream.next();
+ }
+ return style;
+ };
+ }
+ function doctype(depth) {
+ return function(stream, state) {
+ var ch;
+ while ((ch = stream.next()) != null) {
+ if (ch == "<") {
+ state.tokenize = doctype(depth + 1);
+ return state.tokenize(stream, state);
+ } else if (ch == ">") {
+ if (depth == 1) {
+ state.tokenize = inText;
+ break;
+ } else {
+ state.tokenize = doctype(depth - 1);
+ return state.tokenize(stream, state);
+ }
+ }
+ }
+ return "meta";
+ };
+ }
+
+ var curState, setStyle;
+ function pass() {
+ for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
+ }
+ function cont() {
+ pass.apply(null, arguments);
+ return true;
+ }
+
+ function pushContext(tagName, startOfLine) {
+ var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent);
+ curState.context = {
+ prev: curState.context,
+ tagName: tagName,
+ indent: curState.indented,
+ startOfLine: startOfLine,
+ noIndent: noIndent
+ };
+ }
+ function popContext() {
+ if (curState.context) curState.context = curState.context.prev;
+ }
+
+ function element(type) {
+ if (type == "openTag") {
+ curState.tagName = tagName;
+ return cont(attributes, endtag(curState.startOfLine));
+ } else if (type == "closeTag") {
+ var err = false;
+ if (curState.context) {
+ if (curState.context.tagName != tagName) {
+ if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) {
+ popContext();
+ }
+ err = !curState.context || curState.context.tagName != tagName;
+ }
+ } else {
+ err = true;
+ }
+ if (err) setStyle = "error";
+ return cont(endclosetag(err));
+ }
+ return cont();
+ }
+ function endtag(startOfLine) {
+ return function(type) {
+ var tagName = curState.tagName;
+ curState.tagName = null;
+ if (type == "selfcloseTag" ||
+ (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase()))) {
+ maybePopContext(tagName.toLowerCase());
+ return cont();
+ }
+ if (type == "endTag") {
+ maybePopContext(tagName.toLowerCase());
+ pushContext(tagName, startOfLine);
+ return cont();
+ }
+ return cont();
+ };
+ }
+ function endclosetag(err) {
+ return function(type) {
+ if (err) setStyle = "error";
+ if (type == "endTag") { popContext(); return cont(); }
+ setStyle = "error";
+ return cont(arguments.callee);
+ };
+ }
+ function maybePopContext(nextTagName) {
+ var parentTagName;
+ while (true) {
+ if (!curState.context) {
+ return;
+ }
+ parentTagName = curState.context.tagName.toLowerCase();
+ if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
+ !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
+ return;
+ }
+ popContext();
+ }
+ }
+
+ function attributes(type) {
+ if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);}
+ if (type == "endTag" || type == "selfcloseTag") return pass();
+ setStyle = "error";
+ return cont(attributes);
+ }
+ function attribute(type) {
+ if (type == "equals") return cont(attvalue, attributes);
+ if (!Kludges.allowMissing) setStyle = "error";
+ else if (type == "word") setStyle = "attribute";
+ return (type == "endTag" || type == "selfcloseTag") ? pass() : cont();
+ }
+ function attvalue(type) {
+ if (type == "string") return cont(attvaluemaybe);
+ if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();}
+ setStyle = "error";
+ return (type == "endTag" || type == "selfCloseTag") ? pass() : cont();
+ }
+ function attvaluemaybe(type) {
+ if (type == "string") return cont(attvaluemaybe);
+ else return pass();
+ }
+
+ return {
+ startState: function() {
+ return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null};
+ },
+
+ token: function(stream, state) {
+ if (stream.sol()) {
+ state.startOfLine = true;
+ state.indented = stream.indentation();
+ }
+ if (stream.eatSpace()) return null;
+
+ setStyle = type = tagName = null;
+ var style = state.tokenize(stream, state);
+ state.type = type;
+ if ((style || type) && style != "comment") {
+ curState = state;
+ while (true) {
+ var comb = state.cc.pop() || element;
+ if (comb(type || style)) break;
+ }
+ }
+ state.startOfLine = false;
+ return setStyle || style;
+ },
+
+ indent: function(state, textAfter, fullLine) {
+ var context = state.context;
+ if ((state.tokenize != inTag && state.tokenize != inText) ||
+ context && context.noIndent)
+ return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
+ if (alignCDATA && /
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. Look for COPYING file in the top folder.
+ * If not, see http://opensource.org/licenses/GPL-2.0.
+ */
+package org.apidesign.bck2brwsr.dew;
+
+import java.io.IOException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+
+/**
+ *
+ * @author Jaroslav Tulach
+ */
+public class CompileTest {
+ @Test public void testCompile() throws IOException {
+ String html = ""
+ + " "
+ + "";
+ String java = "package x.y.z;"
+ + "import org.apidesign.bck2brwsr.htmlpage.api.*;"
+ + "import static org.apidesign.bck2brwsr.htmlpage.api.OnEvent.*;"
+ + "@Page(xhtml=\"index.html\", className=\"Index\")"
+ + "class X { "
+ + " @On(event=CLICK, id=\"btn\") static void clcs() {}"
+ + "}";
+ Compile result = Compile.create(html, java);
+
+ assertNotNull(result.get("x/y/z/X.class"), "Class X is compiled: " + result);
+ assertNotNull(result.get("x/y/z/Index.class"), "Class Index is compiled: " + result);
+ }
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/pom.xml
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/pom.xml Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,47 @@
+
+
+ 4.0.0
+
+ org.apidesign.bck2brwsr
+ emul.pom
+ 0.3-SNAPSHOT
+
+ org.apidesign.bck2brwsr
+ emul
+ 0.3-SNAPSHOT
+ Compact API Profile
+ http://maven.apache.org
+
+ UTF-8
+
+
+
+ ${project.groupId}
+ emul.mini
+ ${project.version}
+
+
+ ${project.groupId}
+ vmtest
+ ${project.version}
+ test
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 2.5.1
+
+
+ netbeans.ignore.jdk.bootclasspath
+
+
+ 1.7
+
+
+
+
+
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/io/BufferedReader.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/io/BufferedReader.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,524 @@
+/*
+ * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.io;
+
+import org.apidesign.bck2brwsr.emul.lang.System;
+
+
+/**
+ * Reads text from a character-input stream, buffering characters so as to
+ * provide for the efficient reading of characters, arrays, and lines.
+ *
+ *
The buffer size may be specified, or the default size may be used. The
+ * default is large enough for most purposes.
+ *
+ *
In general, each read request made of a Reader causes a corresponding
+ * read request to be made of the underlying character or byte stream. It is
+ * therefore advisable to wrap a BufferedReader around any Reader whose read()
+ * operations may be costly, such as FileReaders and InputStreamReaders. For
+ * example,
+ *
+ *
+ * BufferedReader in
+ * = new BufferedReader(new FileReader("foo.in"));
+ *
+ *
+ * will buffer the input from the specified file. Without buffering, each
+ * invocation of read() or readLine() could cause bytes to be read from the
+ * file, converted into characters, and then returned, which can be very
+ * inefficient.
+ *
+ *
Programs that use DataInputStreams for textual input can be localized by
+ * replacing each DataInputStream with an appropriate BufferedReader.
+ *
+ * @see FileReader
+ * @see InputStreamReader
+ * @see java.nio.file.Files#newBufferedReader
+ *
+ * @author Mark Reinhold
+ * @since JDK1.1
+ */
+
+public class BufferedReader extends Reader {
+
+ private Reader in;
+
+ private char cb[];
+ private int nChars, nextChar;
+
+ private static final int INVALIDATED = -2;
+ private static final int UNMARKED = -1;
+ private int markedChar = UNMARKED;
+ private int readAheadLimit = 0; /* Valid only when markedChar > 0 */
+
+ /** If the next character is a line feed, skip it */
+ private boolean skipLF = false;
+
+ /** The skipLF flag when the mark was set */
+ private boolean markedSkipLF = false;
+
+ private static int defaultCharBufferSize = 8192;
+ private static int defaultExpectedLineLength = 80;
+
+ /**
+ * Creates a buffering character-input stream that uses an input buffer of
+ * the specified size.
+ *
+ * @param in A Reader
+ * @param sz Input-buffer size
+ *
+ * @exception IllegalArgumentException If sz is <= 0
+ */
+ public BufferedReader(Reader in, int sz) {
+ super(in);
+ if (sz <= 0)
+ throw new IllegalArgumentException("Buffer size <= 0");
+ this.in = in;
+ cb = new char[sz];
+ nextChar = nChars = 0;
+ }
+
+ /**
+ * Creates a buffering character-input stream that uses a default-sized
+ * input buffer.
+ *
+ * @param in A Reader
+ */
+ public BufferedReader(Reader in) {
+ this(in, defaultCharBufferSize);
+ }
+
+ /** Checks to make sure that the stream has not been closed */
+ private void ensureOpen() throws IOException {
+ if (in == null)
+ throw new IOException("Stream closed");
+ }
+
+ /**
+ * Fills the input buffer, taking the mark into account if it is valid.
+ */
+ private void fill() throws IOException {
+ int dst;
+ if (markedChar <= UNMARKED) {
+ /* No mark */
+ dst = 0;
+ } else {
+ /* Marked */
+ int delta = nextChar - markedChar;
+ if (delta >= readAheadLimit) {
+ /* Gone past read-ahead limit: Invalidate mark */
+ markedChar = INVALIDATED;
+ readAheadLimit = 0;
+ dst = 0;
+ } else {
+ if (readAheadLimit <= cb.length) {
+ /* Shuffle in the current buffer */
+ System.arraycopy(cb, markedChar, cb, 0, delta);
+ markedChar = 0;
+ dst = delta;
+ } else {
+ /* Reallocate buffer to accommodate read-ahead limit */
+ char ncb[] = new char[readAheadLimit];
+ System.arraycopy(cb, markedChar, ncb, 0, delta);
+ cb = ncb;
+ markedChar = 0;
+ dst = delta;
+ }
+ nextChar = nChars = delta;
+ }
+ }
+
+ int n;
+ do {
+ n = in.read(cb, dst, cb.length - dst);
+ } while (n == 0);
+ if (n > 0) {
+ nChars = dst + n;
+ nextChar = dst;
+ }
+ }
+
+ /**
+ * Reads a single character.
+ *
+ * @return The character read, as an integer in the range
+ * 0 to 65535 (0x00-0xffff), or -1 if the
+ * end of the stream has been reached
+ * @exception IOException If an I/O error occurs
+ */
+ public int read() throws IOException {
+ synchronized (lock) {
+ ensureOpen();
+ for (;;) {
+ if (nextChar >= nChars) {
+ fill();
+ if (nextChar >= nChars)
+ return -1;
+ }
+ if (skipLF) {
+ skipLF = false;
+ if (cb[nextChar] == '\n') {
+ nextChar++;
+ continue;
+ }
+ }
+ return cb[nextChar++];
+ }
+ }
+ }
+
+ /**
+ * Reads characters into a portion of an array, reading from the underlying
+ * stream if necessary.
+ */
+ private int read1(char[] cbuf, int off, int len) throws IOException {
+ if (nextChar >= nChars) {
+ /* If the requested length is at least as large as the buffer, and
+ if there is no mark/reset activity, and if line feeds are not
+ being skipped, do not bother to copy the characters into the
+ local buffer. In this way buffered streams will cascade
+ harmlessly. */
+ if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
+ return in.read(cbuf, off, len);
+ }
+ fill();
+ }
+ if (nextChar >= nChars) return -1;
+ if (skipLF) {
+ skipLF = false;
+ if (cb[nextChar] == '\n') {
+ nextChar++;
+ if (nextChar >= nChars)
+ fill();
+ if (nextChar >= nChars)
+ return -1;
+ }
+ }
+ int n = Math.min(len, nChars - nextChar);
+ System.arraycopy(cb, nextChar, cbuf, off, n);
+ nextChar += n;
+ return n;
+ }
+
+ /**
+ * Reads characters into a portion of an array.
+ *
+ *
This method implements the general contract of the corresponding
+ * {@link Reader#read(char[], int, int) read} method of the
+ * {@link Reader} class. As an additional convenience, it
+ * attempts to read as many characters as possible by repeatedly invoking
+ * the read method of the underlying stream. This iterated
+ * read continues until one of the following conditions becomes
+ * true:
+ *
+ *
The specified number of characters have been read,
+ *
+ *
The read method of the underlying stream returns
+ * -1, indicating end-of-file, or
+ *
+ *
The ready method of the underlying stream
+ * returns false, indicating that further input requests
+ * would block.
+ *
+ *
If the first read on the underlying stream returns
+ * -1 to indicate end-of-file then this method returns
+ * -1. Otherwise this method returns the number of characters
+ * actually read.
+ *
+ *
Subclasses of this class are encouraged, but not required, to
+ * attempt to read as many characters as possible in the same fashion.
+ *
+ *
Ordinarily this method takes characters from this stream's character
+ * buffer, filling it from the underlying stream as necessary. If,
+ * however, the buffer is empty, the mark is not valid, and the requested
+ * length is at least as large as the buffer, then this method will read
+ * characters directly from the underlying stream into the given array.
+ * Thus redundant BufferedReaders will not copy data
+ * unnecessarily.
+ *
+ * @param cbuf Destination buffer
+ * @param off Offset at which to start storing characters
+ * @param len Maximum number of characters to read
+ *
+ * @return The number of characters read, or -1 if the end of the
+ * stream has been reached
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ public int read(char cbuf[], int off, int len) throws IOException {
+ synchronized (lock) {
+ ensureOpen();
+ if ((off < 0) || (off > cbuf.length) || (len < 0) ||
+ ((off + len) > cbuf.length) || ((off + len) < 0)) {
+ throw new IndexOutOfBoundsException();
+ } else if (len == 0) {
+ return 0;
+ }
+
+ int n = read1(cbuf, off, len);
+ if (n <= 0) return n;
+ while ((n < len) && in.ready()) {
+ int n1 = read1(cbuf, off + n, len - n);
+ if (n1 <= 0) break;
+ n += n1;
+ }
+ return n;
+ }
+ }
+
+ /**
+ * Reads a line of text. A line is considered to be terminated by any one
+ * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
+ * followed immediately by a linefeed.
+ *
+ * @param ignoreLF If true, the next '\n' will be skipped
+ *
+ * @return A String containing the contents of the line, not including
+ * any line-termination characters, or null if the end of the
+ * stream has been reached
+ *
+ * @see java.io.LineNumberReader#readLine()
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ String readLine(boolean ignoreLF) throws IOException {
+ StringBuffer s = null;
+ int startChar;
+
+ synchronized (lock) {
+ ensureOpen();
+ boolean omitLF = ignoreLF || skipLF;
+
+ bufferLoop:
+ for (;;) {
+
+ if (nextChar >= nChars)
+ fill();
+ if (nextChar >= nChars) { /* EOF */
+ if (s != null && s.length() > 0)
+ return s.toString();
+ else
+ return null;
+ }
+ boolean eol = false;
+ char c = 0;
+ int i;
+
+ /* Skip a leftover '\n', if necessary */
+ if (omitLF && (cb[nextChar] == '\n'))
+ nextChar++;
+ skipLF = false;
+ omitLF = false;
+
+ charLoop:
+ for (i = nextChar; i < nChars; i++) {
+ c = cb[i];
+ if ((c == '\n') || (c == '\r')) {
+ eol = true;
+ break charLoop;
+ }
+ }
+
+ startChar = nextChar;
+ nextChar = i;
+
+ if (eol) {
+ String str;
+ if (s == null) {
+ str = new String(cb, startChar, i - startChar);
+ } else {
+ s.append(cb, startChar, i - startChar);
+ str = s.toString();
+ }
+ nextChar++;
+ if (c == '\r') {
+ skipLF = true;
+ }
+ return str;
+ }
+
+ if (s == null)
+ s = new StringBuffer(defaultExpectedLineLength);
+ s.append(cb, startChar, i - startChar);
+ }
+ }
+ }
+
+ /**
+ * Reads a line of text. A line is considered to be terminated by any one
+ * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
+ * followed immediately by a linefeed.
+ *
+ * @return A String containing the contents of the line, not including
+ * any line-termination characters, or null if the end of the
+ * stream has been reached
+ *
+ * @exception IOException If an I/O error occurs
+ *
+ * @see java.nio.file.Files#readAllLines
+ */
+ public String readLine() throws IOException {
+ return readLine(false);
+ }
+
+ /**
+ * Skips characters.
+ *
+ * @param n The number of characters to skip
+ *
+ * @return The number of characters actually skipped
+ *
+ * @exception IllegalArgumentException If n is negative.
+ * @exception IOException If an I/O error occurs
+ */
+ public long skip(long n) throws IOException {
+ if (n < 0L) {
+ throw new IllegalArgumentException("skip value is negative");
+ }
+ synchronized (lock) {
+ ensureOpen();
+ long r = n;
+ while (r > 0) {
+ if (nextChar >= nChars)
+ fill();
+ if (nextChar >= nChars) /* EOF */
+ break;
+ if (skipLF) {
+ skipLF = false;
+ if (cb[nextChar] == '\n') {
+ nextChar++;
+ }
+ }
+ long d = nChars - nextChar;
+ if (r <= d) {
+ nextChar += r;
+ r = 0;
+ break;
+ }
+ else {
+ r -= d;
+ nextChar = nChars;
+ }
+ }
+ return n - r;
+ }
+ }
+
+ /**
+ * Tells whether this stream is ready to be read. A buffered character
+ * stream is ready if the buffer is not empty, or if the underlying
+ * character stream is ready.
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ public boolean ready() throws IOException {
+ synchronized (lock) {
+ ensureOpen();
+
+ /*
+ * If newline needs to be skipped and the next char to be read
+ * is a newline character, then just skip it right away.
+ */
+ if (skipLF) {
+ /* Note that in.ready() will return true if and only if the next
+ * read on the stream will not block.
+ */
+ if (nextChar >= nChars && in.ready()) {
+ fill();
+ }
+ if (nextChar < nChars) {
+ if (cb[nextChar] == '\n')
+ nextChar++;
+ skipLF = false;
+ }
+ }
+ return (nextChar < nChars) || in.ready();
+ }
+ }
+
+ /**
+ * Tells whether this stream supports the mark() operation, which it does.
+ */
+ public boolean markSupported() {
+ return true;
+ }
+
+ /**
+ * Marks the present position in the stream. Subsequent calls to reset()
+ * will attempt to reposition the stream to this point.
+ *
+ * @param readAheadLimit Limit on the number of characters that may be
+ * read while still preserving the mark. An attempt
+ * to reset the stream after reading characters
+ * up to this limit or beyond may fail.
+ * A limit value larger than the size of the input
+ * buffer will cause a new buffer to be allocated
+ * whose size is no smaller than limit.
+ * Therefore large values should be used with care.
+ *
+ * @exception IllegalArgumentException If readAheadLimit is < 0
+ * @exception IOException If an I/O error occurs
+ */
+ public void mark(int readAheadLimit) throws IOException {
+ if (readAheadLimit < 0) {
+ throw new IllegalArgumentException("Read-ahead limit < 0");
+ }
+ synchronized (lock) {
+ ensureOpen();
+ this.readAheadLimit = readAheadLimit;
+ markedChar = nextChar;
+ markedSkipLF = skipLF;
+ }
+ }
+
+ /**
+ * Resets the stream to the most recent mark.
+ *
+ * @exception IOException If the stream has never been marked,
+ * or if the mark has been invalidated
+ */
+ public void reset() throws IOException {
+ synchronized (lock) {
+ ensureOpen();
+ if (markedChar < 0)
+ throw new IOException((markedChar == INVALIDATED)
+ ? "Mark invalid"
+ : "Stream not marked");
+ nextChar = markedChar;
+ skipLF = markedSkipLF;
+ }
+ }
+
+ public void close() throws IOException {
+ synchronized (lock) {
+ if (in == null)
+ return;
+ in.close();
+ in = null;
+ cb = null;
+ }
+ }
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/io/InputStreamReader.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/io/InputStreamReader.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.io;
+
+
+/**
+ * An InputStreamReader is a bridge from byte streams to character streams: It
+ * reads bytes and decodes them into characters using a specified {@link
+ * java.nio.charset.Charset charset}. The charset that it uses
+ * may be specified by name or may be given explicitly, or the platform's
+ * default charset may be accepted.
+ *
+ *
Each invocation of one of an InputStreamReader's read() methods may
+ * cause one or more bytes to be read from the underlying byte-input stream.
+ * To enable the efficient conversion of bytes to characters, more bytes may
+ * be read ahead from the underlying stream than are necessary to satisfy the
+ * current read operation.
+ *
+ *
For top efficiency, consider wrapping an InputStreamReader within a
+ * BufferedReader. For example:
+ *
+ *
+ * BufferedReader in
+ * = new BufferedReader(new InputStreamReader(System.in));
+ *
+ *
+ * @see BufferedReader
+ * @see InputStream
+ * @see java.nio.charset.Charset
+ *
+ * @author Mark Reinhold
+ * @since JDK1.1
+ */
+
+public class InputStreamReader extends Reader {
+
+ /**
+ * Creates an InputStreamReader that uses the default charset.
+ *
+ * @param in An InputStream
+ */
+ public InputStreamReader(InputStream in) {
+ super(in);
+ }
+
+ /**
+ * Creates an InputStreamReader that uses the named charset.
+ *
+ * @param in
+ * An InputStream
+ *
+ * @param charsetName
+ * The name of a supported
+ * {@link java.nio.charset.Charset charset}
+ *
+ * @exception UnsupportedEncodingException
+ * If the named charset is not supported
+ */
+ public InputStreamReader(InputStream in, String charsetName)
+ throws UnsupportedEncodingException
+ {
+ super(in);
+ if (!charsetName.toUpperCase().equals("UTF-8")) {
+ throw new UnsupportedEncodingException(charsetName);
+ }
+ }
+
+ /**
+ * Creates an InputStreamReader that uses the given charset.
+ *
+ * @param in An InputStream
+ * @param cs A charset
+ *
+ * @since 1.4
+ * @spec JSR-51
+ */
+/* XXX:
+ public InputStreamReader(InputStream in, Charset cs) {
+ super(in);
+ if (cs == null)
+ throw new NullPointerException("charset");
+ sd = StreamDecoder.forInputStreamReader(in, this, cs);
+ }
+*/
+ /**
+ * Creates an InputStreamReader that uses the given charset decoder.
+ *
+ * @param in An InputStream
+ * @param dec A charset decoder
+ *
+ * @since 1.4
+ * @spec JSR-51
+ */
+/* XXX:
+ public InputStreamReader(InputStream in, CharsetDecoder dec) {
+ super(in);
+ if (dec == null)
+ throw new NullPointerException("charset decoder");
+ sd = StreamDecoder.forInputStreamReader(in, this, dec);
+ }
+*/
+
+ /**
+ * Returns the name of the character encoding being used by this stream.
+ *
+ *
If the encoding has an historical name then that name is returned;
+ * otherwise the encoding's canonical name is returned.
+ *
+ *
If this instance was created with the {@link
+ * #InputStreamReader(InputStream, String)} constructor then the returned
+ * name, being unique for the encoding, may differ from the name passed to
+ * the constructor. This method will return null if the
+ * stream has been closed.
+ *
+ * @return The historical name of this encoding, or
+ * null if the stream has been closed
+ *
+ * @see java.nio.charset.Charset
+ *
+ * @revised 1.4
+ * @spec JSR-51
+ */
+ public String getEncoding() {
+ return "UTF-8";
+ }
+
+ /**
+ * Reads a single character.
+ *
+ * @return The character read, or -1 if the end of the stream has been
+ * reached
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ public int read() throws IOException {
+ return ((InputStream)lock).read();
+ }
+
+ /**
+ * Reads characters into a portion of an array.
+ *
+ * @param cbuf Destination buffer
+ * @param offset Offset at which to start storing characters
+ * @param length Maximum number of characters to read
+ *
+ * @return The number of characters read, or -1 if the end of the
+ * stream has been reached
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ public int read(char cbuf[], int offset, int length) throws IOException {
+ for (int i = 0; i < length; i++) {
+ int ch = read();
+ if (ch == -1) {
+ if (i == 0) return -1;
+ return i;
+ }
+ cbuf[offset++] = (char) ch;
+ }
+ return length;
+ }
+
+ /**
+ * Tells whether this stream is ready to be read. An InputStreamReader is
+ * ready if its input buffer is not empty, or if bytes are available to be
+ * read from the underlying byte stream.
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ public boolean ready() throws IOException {
+ return ((InputStream)lock).available() > 0;
+ }
+
+ public void close() throws IOException {
+ ((InputStream)lock).close();
+ }
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/io/Reader.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/io/Reader.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,262 @@
+/*
+ * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.io;
+
+
+/**
+ * Abstract class for reading character streams. The only methods that a
+ * subclass must implement are read(char[], int, int) and close(). Most
+ * subclasses, however, will override some of the methods defined here in order
+ * to provide higher efficiency, additional functionality, or both.
+ *
+ *
+ * @see BufferedReader
+ * @see LineNumberReader
+ * @see CharArrayReader
+ * @see InputStreamReader
+ * @see FileReader
+ * @see FilterReader
+ * @see PushbackReader
+ * @see PipedReader
+ * @see StringReader
+ * @see Writer
+ *
+ * @author Mark Reinhold
+ * @since JDK1.1
+ */
+
+public abstract class Reader implements Readable, Closeable {
+
+ /**
+ * The object used to synchronize operations on this stream. For
+ * efficiency, a character-stream object may use an object other than
+ * itself to protect critical sections. A subclass should therefore use
+ * the object in this field rather than this or a synchronized
+ * method.
+ */
+ protected Object lock;
+
+ /**
+ * Creates a new character-stream reader whose critical sections will
+ * synchronize on the reader itself.
+ */
+ protected Reader() {
+ this.lock = this;
+ }
+
+ /**
+ * Creates a new character-stream reader whose critical sections will
+ * synchronize on the given object.
+ *
+ * @param lock The Object to synchronize on.
+ */
+ protected Reader(Object lock) {
+ if (lock == null) {
+ throw new NullPointerException();
+ }
+ this.lock = lock;
+ }
+
+ /**
+ * Attempts to read characters into the specified character buffer.
+ * The buffer is used as a repository of characters as-is: the only
+ * changes made are the results of a put operation. No flipping or
+ * rewinding of the buffer is performed.
+ *
+ * @param target the buffer to read characters into
+ * @return The number of characters added to the buffer, or
+ * -1 if this source of characters is at its end
+ * @throws IOException if an I/O error occurs
+ * @throws NullPointerException if target is null
+ * @throws ReadOnlyBufferException if target is a read only buffer
+ * @since 1.5
+ */
+// public int read(java.nio.CharBuffer target) throws IOException {
+// int len = target.remaining();
+// char[] cbuf = new char[len];
+// int n = read(cbuf, 0, len);
+// if (n > 0)
+// target.put(cbuf, 0, n);
+// return n;
+// }
+
+ /**
+ * Reads a single character. This method will block until a character is
+ * available, an I/O error occurs, or the end of the stream is reached.
+ *
+ *
Subclasses that intend to support efficient single-character input
+ * should override this method.
+ *
+ * @return The character read, as an integer in the range 0 to 65535
+ * (0x00-0xffff), or -1 if the end of the stream has
+ * been reached
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ public int read() throws IOException {
+ char cb[] = new char[1];
+ if (read(cb, 0, 1) == -1)
+ return -1;
+ else
+ return cb[0];
+ }
+
+ /**
+ * Reads characters into an array. This method will block until some input
+ * is available, an I/O error occurs, or the end of the stream is reached.
+ *
+ * @param cbuf Destination buffer
+ *
+ * @return The number of characters read, or -1
+ * if the end of the stream
+ * has been reached
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ public int read(char cbuf[]) throws IOException {
+ return read(cbuf, 0, cbuf.length);
+ }
+
+ /**
+ * Reads characters into a portion of an array. This method will block
+ * until some input is available, an I/O error occurs, or the end of the
+ * stream is reached.
+ *
+ * @param cbuf Destination buffer
+ * @param off Offset at which to start storing characters
+ * @param len Maximum number of characters to read
+ *
+ * @return The number of characters read, or -1 if the end of the
+ * stream has been reached
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ abstract public int read(char cbuf[], int off, int len) throws IOException;
+
+ /** Maximum skip-buffer size */
+ private static final int maxSkipBufferSize = 8192;
+
+ /** Skip buffer, null until allocated */
+ private char skipBuffer[] = null;
+
+ /**
+ * Skips characters. This method will block until some characters are
+ * available, an I/O error occurs, or the end of the stream is reached.
+ *
+ * @param n The number of characters to skip
+ *
+ * @return The number of characters actually skipped
+ *
+ * @exception IllegalArgumentException If n is negative.
+ * @exception IOException If an I/O error occurs
+ */
+ public long skip(long n) throws IOException {
+ if (n < 0L)
+ throw new IllegalArgumentException("skip value is negative");
+ int nn = (int) Math.min(n, maxSkipBufferSize);
+ synchronized (lock) {
+ if ((skipBuffer == null) || (skipBuffer.length < nn))
+ skipBuffer = new char[nn];
+ long r = n;
+ while (r > 0) {
+ int nc = read(skipBuffer, 0, (int)Math.min(r, nn));
+ if (nc == -1)
+ break;
+ r -= nc;
+ }
+ return n - r;
+ }
+ }
+
+ /**
+ * Tells whether this stream is ready to be read.
+ *
+ * @return True if the next read() is guaranteed not to block for input,
+ * false otherwise. Note that returning false does not guarantee that the
+ * next read will block.
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ public boolean ready() throws IOException {
+ return false;
+ }
+
+ /**
+ * Tells whether this stream supports the mark() operation. The default
+ * implementation always returns false. Subclasses should override this
+ * method.
+ *
+ * @return true if and only if this stream supports the mark operation.
+ */
+ public boolean markSupported() {
+ return false;
+ }
+
+ /**
+ * Marks the present position in the stream. Subsequent calls to reset()
+ * will attempt to reposition the stream to this point. Not all
+ * character-input streams support the mark() operation.
+ *
+ * @param readAheadLimit Limit on the number of characters that may be
+ * read while still preserving the mark. After
+ * reading this many characters, attempting to
+ * reset the stream may fail.
+ *
+ * @exception IOException If the stream does not support mark(),
+ * or if some other I/O error occurs
+ */
+ public void mark(int readAheadLimit) throws IOException {
+ throw new IOException("mark() not supported");
+ }
+
+ /**
+ * Resets the stream. If the stream has been marked, then attempt to
+ * reposition it at the mark. If the stream has not been marked, then
+ * attempt to reset it in some way appropriate to the particular stream,
+ * for example by repositioning it to its starting point. Not all
+ * character-input streams support the reset() operation, and some support
+ * reset() without supporting mark().
+ *
+ * @exception IOException If the stream has not been marked,
+ * or if the mark has been invalidated,
+ * or if the stream does not support reset(),
+ * or if some other I/O error occurs
+ */
+ public void reset() throws IOException {
+ throw new IOException("reset() not supported");
+ }
+
+ /**
+ * Closes the stream and releases any system resources associated with
+ * it. Once the stream has been closed, further read(), ready(),
+ * mark(), reset(), or skip() invocations will throw an IOException.
+ * Closing a previously closed stream has no effect.
+ *
+ * @exception IOException If an I/O error occurs
+ */
+ abstract public void close() throws IOException;
+
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/lang/Cloneable.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/lang/Cloneable.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+/**
+ * A class implements the Cloneable interface to
+ * indicate to the {@link java.lang.Object#clone()} method that it
+ * is legal for that method to make a
+ * field-for-field copy of instances of that class.
+ *
+ * Invoking Object's clone method on an instance that does not implement the
+ * Cloneable interface results in the exception
+ * CloneNotSupportedException being thrown.
+ *
+ * By convention, classes that implement this interface should override
+ * Object.clone (which is protected) with a public method.
+ * See {@link java.lang.Object#clone()} for details on overriding this
+ * method.
+ *
+ * Note that this interface does not contain the clone method.
+ * Therefore, it is not possible to clone an object merely by virtue of the
+ * fact that it implements this interface. Even if the clone method is invoked
+ * reflectively, there is no guarantee that it will succeed.
+ *
+ * @author unascribed
+ * @see java.lang.CloneNotSupportedException
+ * @see java.lang.Object#clone()
+ * @since JDK1.0
+ */
+public interface Cloneable {
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/lang/InternalError.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/lang/InternalError.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+/**
+ * Thrown to indicate some unexpected internal error has occurred in
+ * the Java Virtual Machine.
+ *
+ * @author unascribed
+ * @since JDK1.0
+ */
+public
+class InternalError extends VirtualMachineError {
+ private static final long serialVersionUID = -9062593416125562365L;
+
+ /**
+ * Constructs an InternalError with no detail message.
+ */
+ public InternalError() {
+ super();
+ }
+
+ /**
+ * Constructs an InternalError with the specified
+ * detail message.
+ *
+ * @param s the detail message.
+ */
+ public InternalError(String s) {
+ super(s);
+ }
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/lang/Iterable.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/lang/Iterable.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+import java.util.Iterator;
+
+/**
+ * Implementing this interface allows an object to be the target of
+ * the "foreach" statement.
+ *
+ * @param the type of elements returned by the iterator
+ *
+ * @since 1.5
+ */
+public interface Iterable {
+
+ /**
+ * Returns an iterator over a set of elements of type T.
+ *
+ * @return an Iterator.
+ */
+ Iterator iterator();
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/lang/Readable.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/lang/Readable.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+import java.io.IOException;
+
+/**
+ * A Readable is a source of characters. Characters from
+ * a Readable are made available to callers of the read
+ * method via a {@link java.nio.CharBuffer CharBuffer}.
+ *
+ * @since 1.5
+ */
+
+public interface Readable {
+
+ /**
+ * Attempts to read characters into the specified character buffer.
+ * The buffer is used as a repository of characters as-is: the only
+ * changes made are the results of a put operation. No flipping or
+ * rewinding of the buffer is performed.
+ *
+ * @param cb the buffer to read characters into
+ * @return The number of {@code char} values added to the buffer,
+ * or -1 if this source of characters is at its end
+ * @throws IOException if an I/O error occurs
+ * @throws NullPointerException if cb is null
+ * @throws java.nio.ReadOnlyBufferException if cb is a read only buffer
+ */
+// XXX: public int read(java.nio.CharBuffer cb) throws IOException;
+
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/lang/SafeVarargs.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/lang/SafeVarargs.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+import java.lang.annotation.*;
+
+/**
+ * A programmer assertion that the body of the annotated method or
+ * constructor does not perform potentially unsafe operations on its
+ * varargs parameter. Applying this annotation to a method or
+ * constructor suppresses unchecked warnings about a
+ * non-reifiable variable arity (vararg) type and suppresses
+ * unchecked warnings about parameterized array creation at call
+ * sites.
+ *
+ *
In addition to the usage restrictions imposed by its {@link
+ * Target @Target} meta-annotation, compilers are required to implement
+ * additional usage restrictions on this annotation type; it is a
+ * compile-time error if a method or constructor declaration is
+ * annotated with a {@code @SafeVarargs} annotation, and either:
+ *
+ *
the declaration is a fixed arity method or constructor
+ *
+ *
the declaration is a variable arity method that is neither
+ * {@code static} nor {@code final}.
+ *
+ *
+ *
+ *
Compilers are encouraged to issue warnings when this annotation
+ * type is applied to a method or constructor declaration where:
+ *
+ *
+ *
+ *
The variable arity parameter has a reifiable element type,
+ * which includes primitive types, {@code Object}, and {@code String}.
+ * (The unchecked warnings this annotation type suppresses already do
+ * not occur for a reifiable element type.)
+ *
+ *
The body of the method or constructor declaration performs
+ * potentially unsafe operations, such as an assignment to an element
+ * of the variable arity parameter's array that generates an unchecked
+ * warning. Some unsafe operations do not trigger an unchecked
+ * warning. For example, the aliasing in
+ *
+ *
+ * @SafeVarargs // Not actually safe!
+ * static void m(List<String>... stringLists) {
+ * Object[] array = stringLists;
+ * List<Integer> tmpList = Arrays.asList(42);
+ * array[0] = tmpList; // Semantically invalid, but compiles without warnings
+ * String s = stringLists[0].get(0); // Oh no, ClassCastException at runtime!
+ * }
+ *
+ *
+ * leads to a {@code ClassCastException} at runtime.
+ *
+ *
Future versions of the platform may mandate compiler errors for
+ * such unsafe operations.
+ *
+ *
+ *
+ * @jls 4.7 Reifiable Types
+ * @jls 8.4.1 Formal Parameters
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
+public @interface SafeVarargs {}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/lang/SuppressWarnings.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/lang/SuppressWarnings.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+import java.lang.annotation.*;
+import static java.lang.annotation.ElementType.*;
+
+/**
+ * Indicates that the named compiler warnings should be suppressed in the
+ * annotated element (and in all program elements contained in the annotated
+ * element). Note that the set of warnings suppressed in a given element is
+ * a superset of the warnings suppressed in all containing elements. For
+ * example, if you annotate a class to suppress one warning and annotate a
+ * method to suppress another, both warnings will be suppressed in the method.
+ *
+ *
As a matter of style, programmers should always use this annotation
+ * on the most deeply nested element where it is effective. If you want to
+ * suppress a warning in a particular method, you should annotate that
+ * method rather than its class.
+ *
+ * @since 1.5
+ * @author Josh Bloch
+ */
+@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
+@Retention(RetentionPolicy.SOURCE)
+public @interface SuppressWarnings {
+ /**
+ * The set of warnings that are to be suppressed by the compiler in the
+ * annotated element. Duplicate names are permitted. The second and
+ * successive occurrences of a name are ignored. The presence of
+ * unrecognized warning names is not an error: Compilers must
+ * ignore any warning names they do not recognize. They are, however,
+ * free to emit a warning if an annotation contains an unrecognized
+ * warning name.
+ *
+ *
Compiler vendors should document the warning names they support in
+ * conjunction with this annotation type. They are encouraged to cooperate
+ * to ensure that the same names work across multiple compilers.
+ */
+ String[] value();
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/util/AbstractCollection.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/util/AbstractCollection.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,457 @@
+/*
+ * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.util;
+
+/**
+ * This class provides a skeletal implementation of the Collection
+ * interface, to minimize the effort required to implement this interface.
+ *
+ * To implement an unmodifiable collection, the programmer needs only to
+ * extend this class and provide implementations for the iterator and
+ * size methods. (The iterator returned by the iterator
+ * method must implement hasNext and next.)
+ *
+ * To implement a modifiable collection, the programmer must additionally
+ * override this class's add method (which otherwise throws an
+ * UnsupportedOperationException), and the iterator returned by the
+ * iterator method must additionally implement its remove
+ * method.
+ *
+ * The programmer should generally provide a void (no argument) and
+ * Collection constructor, as per the recommendation in the
+ * Collection interface specification.
+ *
+ * The documentation for each non-abstract method in this class describes its
+ * implementation in detail. Each of these methods may be overridden if
+ * the collection being implemented admits a more efficient implementation.
+ *
+ * This class is a member of the
+ *
+ * Java Collections Framework.
+ *
+ * @author Josh Bloch
+ * @author Neal Gafter
+ * @see Collection
+ * @since 1.2
+ */
+
+public abstract class AbstractCollection implements Collection {
+ /**
+ * Sole constructor. (For invocation by subclass constructors, typically
+ * implicit.)
+ */
+ protected AbstractCollection() {
+ }
+
+ // Query Operations
+
+ /**
+ * Returns an iterator over the elements contained in this collection.
+ *
+ * @return an iterator over the elements contained in this collection
+ */
+ public abstract Iterator iterator();
+
+ public abstract int size();
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over the elements in the collection,
+ * checking each element in turn for equality with the specified element.
+ *
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ */
+ public boolean contains(Object o) {
+ Iterator it = iterator();
+ if (o==null) {
+ while (it.hasNext())
+ if (it.next()==null)
+ return true;
+ } else {
+ while (it.hasNext())
+ if (o.equals(it.next()))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation returns an array containing all the elements
+ * returned by this collection's iterator, in the same order, stored in
+ * consecutive elements of the array, starting with index {@code 0}.
+ * The length of the returned array is equal to the number of elements
+ * returned by the iterator, even if the size of this collection changes
+ * during iteration, as might happen if the collection permits
+ * concurrent modification during iteration. The {@code size} method is
+ * called only as an optimization hint; the correct result is returned
+ * even if the iterator returns a different number of elements.
+ *
+ *
This method is equivalent to:
+ *
+ *
{@code
+ * List list = new ArrayList(size());
+ * for (E e : this)
+ * list.add(e);
+ * return list.toArray();
+ * }
+ */
+ public Object[] toArray() {
+ // Estimate size of array; be prepared to see more or fewer elements
+ Object[] r = new Object[size()];
+ Iterator it = iterator();
+ for (int i = 0; i < r.length; i++) {
+ if (! it.hasNext()) // fewer elements than expected
+ return Arrays.copyOf(r, i);
+ r[i] = it.next();
+ }
+ return it.hasNext() ? finishToArray(r, it) : r;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation returns an array containing all the elements
+ * returned by this collection's iterator in the same order, stored in
+ * consecutive elements of the array, starting with index {@code 0}.
+ * If the number of elements returned by the iterator is too large to
+ * fit into the specified array, then the elements are returned in a
+ * newly allocated array with length equal to the number of elements
+ * returned by the iterator, even if the size of this collection
+ * changes during iteration, as might happen if the collection permits
+ * concurrent modification during iteration. The {@code size} method is
+ * called only as an optimization hint; the correct result is returned
+ * even if the iterator returns a different number of elements.
+ *
+ *
This method is equivalent to:
+ *
+ *
{@code
+ * List list = new ArrayList(size());
+ * for (E e : this)
+ * list.add(e);
+ * return list.toArray(a);
+ * }
+ *
+ * @throws ArrayStoreException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ */
+ public T[] toArray(T[] a) {
+ // Estimate size of array; be prepared to see more or fewer elements
+ int size = size();
+ T[] r = a.length >= size ? a :
+ (T[])java.lang.reflect.Array
+ .newInstance(a.getClass().getComponentType(), size);
+ Iterator it = iterator();
+
+ for (int i = 0; i < r.length; i++) {
+ if (! it.hasNext()) { // fewer elements than expected
+ if (a != r)
+ return Arrays.copyOf(r, i);
+ r[i] = null; // null-terminate
+ return r;
+ }
+ r[i] = (T)it.next();
+ }
+ return it.hasNext() ? finishToArray(r, it) : r;
+ }
+
+ /**
+ * The maximum size of array to allocate.
+ * Some VMs reserve some header words in an array.
+ * Attempts to allocate larger arrays may result in
+ * OutOfMemoryError: Requested array size exceeds VM limit
+ */
+ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+
+ /**
+ * Reallocates the array being used within toArray when the iterator
+ * returned more elements than expected, and finishes filling it from
+ * the iterator.
+ *
+ * @param r the array, replete with previously stored elements
+ * @param it the in-progress iterator over this collection
+ * @return array containing the elements in the given array, plus any
+ * further elements returned by the iterator, trimmed to size
+ */
+ private static T[] finishToArray(T[] r, Iterator> it) {
+ int i = r.length;
+ while (it.hasNext()) {
+ int cap = r.length;
+ if (i == cap) {
+ int newCap = cap + (cap >> 1) + 1;
+ // overflow-conscious code
+ if (newCap - MAX_ARRAY_SIZE > 0)
+ newCap = hugeCapacity(cap + 1);
+ r = Arrays.copyOf(r, newCap);
+ }
+ r[i++] = (T)it.next();
+ }
+ // trim if overallocated
+ return (i == r.length) ? r : Arrays.copyOf(r, i);
+ }
+
+ private static int hugeCapacity(int minCapacity) {
+ if (minCapacity < 0) // overflow
+ throw new OutOfMemoryError
+ ("Required array size too large");
+ return (minCapacity > MAX_ARRAY_SIZE) ?
+ Integer.MAX_VALUE :
+ MAX_ARRAY_SIZE;
+ }
+
+ // Modification Operations
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over the collection looking for the
+ * specified element. If it finds the element, it removes the element
+ * from the collection using the iterator's remove method.
+ *
+ *
Note that this implementation throws an
+ * UnsupportedOperationException if the iterator returned by this
+ * collection's iterator method does not implement the remove
+ * method and this collection contains the specified object.
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ */
+ public boolean remove(Object o) {
+ Iterator it = iterator();
+ if (o==null) {
+ while (it.hasNext()) {
+ if (it.next()==null) {
+ it.remove();
+ return true;
+ }
+ }
+ } else {
+ while (it.hasNext()) {
+ if (o.equals(it.next())) {
+ it.remove();
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+
+ // Bulk Operations
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over the specified collection,
+ * checking each element returned by the iterator in turn to see
+ * if it's contained in this collection. If all elements are so
+ * contained true is returned, otherwise false.
+ *
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ * @see #contains(Object)
+ */
+ public boolean containsAll(Collection> c) {
+ for (Object e : c)
+ if (!contains(e))
+ return false;
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over the specified collection, and adds
+ * each object returned by the iterator to this collection, in turn.
+ *
+ *
Note that this implementation will throw an
+ * UnsupportedOperationException unless add is
+ * overridden (assuming the specified collection is non-empty).
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ * @throws IllegalArgumentException {@inheritDoc}
+ * @throws IllegalStateException {@inheritDoc}
+ *
+ * @see #add(Object)
+ */
+ public boolean addAll(Collection extends E> c) {
+ boolean modified = false;
+ for (E e : c)
+ if (add(e))
+ modified = true;
+ return modified;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over this collection, checking each
+ * element returned by the iterator in turn to see if it's contained
+ * in the specified collection. If it's so contained, it's removed from
+ * this collection with the iterator's remove method.
+ *
+ *
Note that this implementation will throw an
+ * UnsupportedOperationException if the iterator returned by the
+ * iterator method does not implement the remove method
+ * and this collection contains one or more elements in common with the
+ * specified collection.
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ *
+ * @see #remove(Object)
+ * @see #contains(Object)
+ */
+ public boolean removeAll(Collection> c) {
+ boolean modified = false;
+ Iterator> it = iterator();
+ while (it.hasNext()) {
+ if (c.contains(it.next())) {
+ it.remove();
+ modified = true;
+ }
+ }
+ return modified;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over this collection, checking each
+ * element returned by the iterator in turn to see if it's contained
+ * in the specified collection. If it's not so contained, it's removed
+ * from this collection with the iterator's remove method.
+ *
+ *
Note that this implementation will throw an
+ * UnsupportedOperationException if the iterator returned by the
+ * iterator method does not implement the remove method
+ * and this collection contains one or more elements not present in the
+ * specified collection.
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ *
+ * @see #remove(Object)
+ * @see #contains(Object)
+ */
+ public boolean retainAll(Collection> c) {
+ boolean modified = false;
+ Iterator it = iterator();
+ while (it.hasNext()) {
+ if (!c.contains(it.next())) {
+ it.remove();
+ modified = true;
+ }
+ }
+ return modified;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over this collection, removing each
+ * element using the Iterator.remove operation. Most
+ * implementations will probably choose to override this method for
+ * efficiency.
+ *
+ *
Note that this implementation will throw an
+ * UnsupportedOperationException if the iterator returned by this
+ * collection's iterator method does not implement the
+ * remove method and this collection is non-empty.
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ */
+ public void clear() {
+ Iterator it = iterator();
+ while (it.hasNext()) {
+ it.next();
+ it.remove();
+ }
+ }
+
+
+ // String conversion
+
+ /**
+ * Returns a string representation of this collection. The string
+ * representation consists of a list of the collection's elements in the
+ * order they are returned by its iterator, enclosed in square brackets
+ * ("[]"). Adjacent elements are separated by the characters
+ * ", " (comma and space). Elements are converted to strings as
+ * by {@link String#valueOf(Object)}.
+ *
+ * @return a string representation of this collection
+ */
+ public String toString() {
+ Iterator it = iterator();
+ if (! it.hasNext())
+ return "[]";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append('[');
+ for (;;) {
+ E e = it.next();
+ sb.append(e == this ? "(this Collection)" : e);
+ if (! it.hasNext())
+ return sb.append(']').toString();
+ sb.append(',').append(' ');
+ }
+ }
+
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/util/AbstractList.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/util/AbstractList.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,781 @@
+/*
+ * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.util;
+
+/**
+ * This class provides a skeletal implementation of the {@link List}
+ * interface to minimize the effort required to implement this interface
+ * backed by a "random access" data store (such as an array). For sequential
+ * access data (such as a linked list), {@link AbstractSequentialList} should
+ * be used in preference to this class.
+ *
+ *
To implement an unmodifiable list, the programmer needs only to extend
+ * this class and provide implementations for the {@link #get(int)} and
+ * {@link List#size() size()} methods.
+ *
+ *
To implement a modifiable list, the programmer must additionally
+ * override the {@link #set(int, Object) set(int, E)} method (which otherwise
+ * throws an {@code UnsupportedOperationException}). If the list is
+ * variable-size the programmer must additionally override the
+ * {@link #add(int, Object) add(int, E)} and {@link #remove(int)} methods.
+ *
+ *
The programmer should generally provide a void (no argument) and collection
+ * constructor, as per the recommendation in the {@link Collection} interface
+ * specification.
+ *
+ *
Unlike the other abstract collection implementations, the programmer does
+ * not have to provide an iterator implementation; the iterator and
+ * list iterator are implemented by this class, on top of the "random access"
+ * methods:
+ * {@link #get(int)},
+ * {@link #set(int, Object) set(int, E)},
+ * {@link #add(int, Object) add(int, E)} and
+ * {@link #remove(int)}.
+ *
+ *
The documentation for each non-abstract method in this class describes its
+ * implementation in detail. Each of these methods may be overridden if the
+ * collection being implemented admits a more efficient implementation.
+ *
+ *
This class is a member of the
+ *
+ * Java Collections Framework.
+ *
+ * @author Josh Bloch
+ * @author Neal Gafter
+ * @since 1.2
+ */
+
+public abstract class AbstractList extends AbstractCollection implements List {
+ /**
+ * Sole constructor. (For invocation by subclass constructors, typically
+ * implicit.)
+ */
+ protected AbstractList() {
+ }
+
+ /**
+ * Appends the specified element to the end of this list (optional
+ * operation).
+ *
+ *
Lists that support this operation may place limitations on what
+ * elements may be added to this list. In particular, some
+ * lists will refuse to add null elements, and others will impose
+ * restrictions on the type of elements that may be added. List
+ * classes should clearly specify in their documentation any restrictions
+ * on what elements may be added.
+ *
+ *
This implementation calls {@code add(size(), e)}.
+ *
+ *
Note that this implementation throws an
+ * {@code UnsupportedOperationException} unless
+ * {@link #add(int, Object) add(int, E)} is overridden.
+ *
+ * @param e element to be appended to this list
+ * @return {@code true} (as specified by {@link Collection#add})
+ * @throws UnsupportedOperationException if the {@code add} operation
+ * is not supported by this list
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this list
+ * @throws NullPointerException if the specified element is null and this
+ * list does not permit null elements
+ * @throws IllegalArgumentException if some property of this element
+ * prevents it from being added to this list
+ */
+ public boolean add(E e) {
+ add(size(), e);
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ */
+ abstract public E get(int index);
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation first gets a list iterator (with
+ * {@code listIterator()}). Then, it iterates over the list until the
+ * specified element is found or the end of the list is reached.
+ *
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ */
+ public int indexOf(Object o) {
+ ListIterator it = listIterator();
+ if (o==null) {
+ while (it.hasNext())
+ if (it.next()==null)
+ return it.previousIndex();
+ } else {
+ while (it.hasNext())
+ if (o.equals(it.next()))
+ return it.previousIndex();
+ }
+ return -1;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation first gets a list iterator that points to the end
+ * of the list (with {@code listIterator(size())}). Then, it iterates
+ * backwards over the list until the specified element is found, or the
+ * beginning of the list is reached.
+ *
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ */
+ public int lastIndexOf(Object o) {
+ ListIterator it = listIterator(size());
+ if (o==null) {
+ while (it.hasPrevious())
+ if (it.previous()==null)
+ return it.nextIndex();
+ } else {
+ while (it.hasPrevious())
+ if (o.equals(it.previous()))
+ return it.nextIndex();
+ }
+ return -1;
+ }
+
+
+ // Bulk Operations
+
+ /**
+ * Removes all of the elements from this list (optional operation).
+ * The list will be empty after this call returns.
+ *
+ *
This implementation calls {@code removeRange(0, size())}.
+ *
+ *
Note that this implementation throws an
+ * {@code UnsupportedOperationException} unless {@code remove(int
+ * index)} or {@code removeRange(int fromIndex, int toIndex)} is
+ * overridden.
+ *
+ * @throws UnsupportedOperationException if the {@code clear} operation
+ * is not supported by this list
+ */
+ public void clear() {
+ removeRange(0, size());
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation gets an iterator over the specified collection
+ * and iterates over it, inserting the elements obtained from the
+ * iterator into this list at the appropriate position, one at a time,
+ * using {@code add(int, E)}.
+ * Many implementations will override this method for efficiency.
+ *
+ *
Note that this implementation throws an
+ * {@code UnsupportedOperationException} unless
+ * {@link #add(int, Object) add(int, E)} is overridden.
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ * @throws IllegalArgumentException {@inheritDoc}
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ */
+ public boolean addAll(int index, Collection extends E> c) {
+ rangeCheckForAdd(index);
+ boolean modified = false;
+ for (E e : c) {
+ add(index++, e);
+ modified = true;
+ }
+ return modified;
+ }
+
+
+ // Iterators
+
+ /**
+ * Returns an iterator over the elements in this list in proper sequence.
+ *
+ *
This implementation returns a straightforward implementation of the
+ * iterator interface, relying on the backing list's {@code size()},
+ * {@code get(int)}, and {@code remove(int)} methods.
+ *
+ *
Note that the iterator returned by this method will throw an
+ * {@link UnsupportedOperationException} in response to its
+ * {@code remove} method unless the list's {@code remove(int)} method is
+ * overridden.
+ *
+ *
This implementation can be made to throw runtime exceptions in the
+ * face of concurrent modification, as described in the specification
+ * for the (protected) {@link #modCount} field.
+ *
+ * @return an iterator over the elements in this list in proper sequence
+ */
+ public Iterator iterator() {
+ return new Itr();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation returns a straightforward implementation of the
+ * {@code ListIterator} interface that extends the implementation of the
+ * {@code Iterator} interface returned by the {@code iterator()} method.
+ * The {@code ListIterator} implementation relies on the backing list's
+ * {@code get(int)}, {@code set(int, E)}, {@code add(int, E)}
+ * and {@code remove(int)} methods.
+ *
+ *
Note that the list iterator returned by this implementation will
+ * throw an {@link UnsupportedOperationException} in response to its
+ * {@code remove}, {@code set} and {@code add} methods unless the
+ * list's {@code remove(int)}, {@code set(int, E)}, and
+ * {@code add(int, E)} methods are overridden.
+ *
+ *
This implementation can be made to throw runtime exceptions in the
+ * face of concurrent modification, as described in the specification for
+ * the (protected) {@link #modCount} field.
+ *
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ */
+ public ListIterator listIterator(final int index) {
+ rangeCheckForAdd(index);
+
+ return new ListItr(index);
+ }
+
+ private class Itr implements Iterator {
+ /**
+ * Index of element to be returned by subsequent call to next.
+ */
+ int cursor = 0;
+
+ /**
+ * Index of element returned by most recent call to next or
+ * previous. Reset to -1 if this element is deleted by a call
+ * to remove.
+ */
+ int lastRet = -1;
+
+ /**
+ * The modCount value that the iterator believes that the backing
+ * List should have. If this expectation is violated, the iterator
+ * has detected concurrent modification.
+ */
+ int expectedModCount = modCount;
+
+ public boolean hasNext() {
+ return cursor != size();
+ }
+
+ public E next() {
+ checkForComodification();
+ try {
+ int i = cursor;
+ E next = get(i);
+ lastRet = i;
+ cursor = i + 1;
+ return next;
+ } catch (IndexOutOfBoundsException e) {
+ checkForComodification();
+ throw new NoSuchElementException();
+ }
+ }
+
+ public void remove() {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
+ try {
+ AbstractList.this.remove(lastRet);
+ if (lastRet < cursor)
+ cursor--;
+ lastRet = -1;
+ expectedModCount = modCount;
+ } catch (IndexOutOfBoundsException e) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ final void checkForComodification() {
+ if (modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ private class ListItr extends Itr implements ListIterator {
+ ListItr(int index) {
+ cursor = index;
+ }
+
+ public boolean hasPrevious() {
+ return cursor != 0;
+ }
+
+ public E previous() {
+ checkForComodification();
+ try {
+ int i = cursor - 1;
+ E previous = get(i);
+ lastRet = cursor = i;
+ return previous;
+ } catch (IndexOutOfBoundsException e) {
+ checkForComodification();
+ throw new NoSuchElementException();
+ }
+ }
+
+ public int nextIndex() {
+ return cursor;
+ }
+
+ public int previousIndex() {
+ return cursor-1;
+ }
+
+ public void set(E e) {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
+ try {
+ AbstractList.this.set(lastRet, e);
+ expectedModCount = modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ public void add(E e) {
+ checkForComodification();
+
+ try {
+ int i = cursor;
+ AbstractList.this.add(i, e);
+ lastRet = -1;
+ cursor = i + 1;
+ expectedModCount = modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation returns a list that subclasses
+ * {@code AbstractList}. The subclass stores, in private fields, the
+ * offset of the subList within the backing list, the size of the subList
+ * (which can change over its lifetime), and the expected
+ * {@code modCount} value of the backing list. There are two variants
+ * of the subclass, one of which implements {@code RandomAccess}.
+ * If this list implements {@code RandomAccess} the returned list will
+ * be an instance of the subclass that implements {@code RandomAccess}.
+ *
+ *
The subclass's {@code set(int, E)}, {@code get(int)},
+ * {@code add(int, E)}, {@code remove(int)}, {@code addAll(int,
+ * Collection)} and {@code removeRange(int, int)} methods all
+ * delegate to the corresponding methods on the backing abstract list,
+ * after bounds-checking the index and adjusting for the offset. The
+ * {@code addAll(Collection c)} method merely returns {@code addAll(size,
+ * c)}.
+ *
+ *
The {@code listIterator(int)} method returns a "wrapper object"
+ * over a list iterator on the backing list, which is created with the
+ * corresponding method on the backing list. The {@code iterator} method
+ * merely returns {@code listIterator()}, and the {@code size} method
+ * merely returns the subclass's {@code size} field.
+ *
+ *
All methods first check to see if the actual {@code modCount} of
+ * the backing list is equal to its expected value, and throw a
+ * {@code ConcurrentModificationException} if it is not.
+ *
+ * @throws IndexOutOfBoundsException if an endpoint index value is out of range
+ * {@code (fromIndex < 0 || toIndex > size)}
+ * @throws IllegalArgumentException if the endpoint indices are out of order
+ * {@code (fromIndex > toIndex)}
+ */
+ public List subList(int fromIndex, int toIndex) {
+ return (this instanceof RandomAccess ?
+ new RandomAccessSubList<>(this, fromIndex, toIndex) :
+ new SubList<>(this, fromIndex, toIndex));
+ }
+
+ // Comparison and hashing
+
+ /**
+ * Compares the specified object with this list for equality. Returns
+ * {@code true} if and only if the specified object is also a list, both
+ * lists have the same size, and all corresponding pairs of elements in
+ * the two lists are equal. (Two elements {@code e1} and
+ * {@code e2} are equal if {@code (e1==null ? e2==null :
+ * e1.equals(e2))}.) In other words, two lists are defined to be
+ * equal if they contain the same elements in the same order.
+ *
+ * This implementation first checks if the specified object is this
+ * list. If so, it returns {@code true}; if not, it checks if the
+ * specified object is a list. If not, it returns {@code false}; if so,
+ * it iterates over both lists, comparing corresponding pairs of elements.
+ * If any comparison returns {@code false}, this method returns
+ * {@code false}. If either iterator runs out of elements before the
+ * other it returns {@code false} (as the lists are of unequal length);
+ * otherwise it returns {@code true} when the iterations complete.
+ *
+ * @param o the object to be compared for equality with this list
+ * @return {@code true} if the specified object is equal to this list
+ */
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof List))
+ return false;
+
+ ListIterator e1 = listIterator();
+ ListIterator e2 = ((List) o).listIterator();
+ while (e1.hasNext() && e2.hasNext()) {
+ E o1 = e1.next();
+ Object o2 = e2.next();
+ if (!(o1==null ? o2==null : o1.equals(o2)))
+ return false;
+ }
+ return !(e1.hasNext() || e2.hasNext());
+ }
+
+ /**
+ * Returns the hash code value for this list.
+ *
+ *
This implementation uses exactly the code that is used to define the
+ * list hash function in the documentation for the {@link List#hashCode}
+ * method.
+ *
+ * @return the hash code value for this list
+ */
+ public int hashCode() {
+ int hashCode = 1;
+ for (E e : this)
+ hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
+ return hashCode;
+ }
+
+ /**
+ * Removes from this list all of the elements whose index is between
+ * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
+ * Shifts any succeeding elements to the left (reduces their index).
+ * This call shortens the list by {@code (toIndex - fromIndex)} elements.
+ * (If {@code toIndex==fromIndex}, this operation has no effect.)
+ *
+ *
This method is called by the {@code clear} operation on this list
+ * and its subLists. Overriding this method to take advantage of
+ * the internals of the list implementation can substantially
+ * improve the performance of the {@code clear} operation on this list
+ * and its subLists.
+ *
+ *
This implementation gets a list iterator positioned before
+ * {@code fromIndex}, and repeatedly calls {@code ListIterator.next}
+ * followed by {@code ListIterator.remove} until the entire range has
+ * been removed. Note: if {@code ListIterator.remove} requires linear
+ * time, this implementation requires quadratic time.
+ *
+ * @param fromIndex index of first element to be removed
+ * @param toIndex index after last element to be removed
+ */
+ protected void removeRange(int fromIndex, int toIndex) {
+ ListIterator it = listIterator(fromIndex);
+ for (int i=0, n=toIndex-fromIndex; istructurally modified.
+ * Structural modifications are those that change the size of the
+ * list, or otherwise perturb it in such a fashion that iterations in
+ * progress may yield incorrect results.
+ *
+ *
This field is used by the iterator and list iterator implementation
+ * returned by the {@code iterator} and {@code listIterator} methods.
+ * If the value of this field changes unexpectedly, the iterator (or list
+ * iterator) will throw a {@code ConcurrentModificationException} in
+ * response to the {@code next}, {@code remove}, {@code previous},
+ * {@code set} or {@code add} operations. This provides
+ * fail-fast behavior, rather than non-deterministic behavior in
+ * the face of concurrent modification during iteration.
+ *
+ *
Use of this field by subclasses is optional. If a subclass
+ * wishes to provide fail-fast iterators (and list iterators), then it
+ * merely has to increment this field in its {@code add(int, E)} and
+ * {@code remove(int)} methods (and any other methods that it overrides
+ * that result in structural modifications to the list). A single call to
+ * {@code add(int, E)} or {@code remove(int)} must add no more than
+ * one to this field, or the iterators (and list iterators) will throw
+ * bogus {@code ConcurrentModificationExceptions}. If an implementation
+ * does not wish to provide fail-fast iterators, this field may be
+ * ignored.
+ */
+ protected transient int modCount = 0;
+
+ private void rangeCheckForAdd(int index) {
+ if (index < 0 || index > size())
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ private String outOfBoundsMsg(int index) {
+ return "Index: "+index+", Size: "+size();
+ }
+}
+
+class SubList extends AbstractList {
+ private final AbstractList l;
+ private final int offset;
+ private int size;
+
+ SubList(AbstractList list, int fromIndex, int toIndex) {
+ if (fromIndex < 0)
+ throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
+ if (toIndex > list.size())
+ throw new IndexOutOfBoundsException("toIndex = " + toIndex);
+ if (fromIndex > toIndex)
+ throw new IllegalArgumentException("fromIndex(" + fromIndex +
+ ") > toIndex(" + toIndex + ")");
+ l = list;
+ offset = fromIndex;
+ size = toIndex - fromIndex;
+ this.modCount = l.modCount;
+ }
+
+ public E set(int index, E element) {
+ rangeCheck(index);
+ checkForComodification();
+ return l.set(index+offset, element);
+ }
+
+ public E get(int index) {
+ rangeCheck(index);
+ checkForComodification();
+ return l.get(index+offset);
+ }
+
+ public int size() {
+ checkForComodification();
+ return size;
+ }
+
+ public void add(int index, E element) {
+ rangeCheckForAdd(index);
+ checkForComodification();
+ l.add(index+offset, element);
+ this.modCount = l.modCount;
+ size++;
+ }
+
+ public E remove(int index) {
+ rangeCheck(index);
+ checkForComodification();
+ E result = l.remove(index+offset);
+ this.modCount = l.modCount;
+ size--;
+ return result;
+ }
+
+ protected void removeRange(int fromIndex, int toIndex) {
+ checkForComodification();
+ l.removeRange(fromIndex+offset, toIndex+offset);
+ this.modCount = l.modCount;
+ size -= (toIndex-fromIndex);
+ }
+
+ public boolean addAll(Collection extends E> c) {
+ return addAll(size, c);
+ }
+
+ public boolean addAll(int index, Collection extends E> c) {
+ rangeCheckForAdd(index);
+ int cSize = c.size();
+ if (cSize==0)
+ return false;
+
+ checkForComodification();
+ l.addAll(offset+index, c);
+ this.modCount = l.modCount;
+ size += cSize;
+ return true;
+ }
+
+ public Iterator iterator() {
+ return listIterator();
+ }
+
+ public ListIterator listIterator(final int index) {
+ checkForComodification();
+ rangeCheckForAdd(index);
+
+ return new ListIterator() {
+ private final ListIterator i = l.listIterator(index+offset);
+
+ public boolean hasNext() {
+ return nextIndex() < size;
+ }
+
+ public E next() {
+ if (hasNext())
+ return i.next();
+ else
+ throw new NoSuchElementException();
+ }
+
+ public boolean hasPrevious() {
+ return previousIndex() >= 0;
+ }
+
+ public E previous() {
+ if (hasPrevious())
+ return i.previous();
+ else
+ throw new NoSuchElementException();
+ }
+
+ public int nextIndex() {
+ return i.nextIndex() - offset;
+ }
+
+ public int previousIndex() {
+ return i.previousIndex() - offset;
+ }
+
+ public void remove() {
+ i.remove();
+ SubList.this.modCount = l.modCount;
+ size--;
+ }
+
+ public void set(E e) {
+ i.set(e);
+ }
+
+ public void add(E e) {
+ i.add(e);
+ SubList.this.modCount = l.modCount;
+ size++;
+ }
+ };
+ }
+
+ public List subList(int fromIndex, int toIndex) {
+ return new SubList<>(this, fromIndex, toIndex);
+ }
+
+ private void rangeCheck(int index) {
+ if (index < 0 || index >= size)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ private void rangeCheckForAdd(int index) {
+ if (index < 0 || index > size)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ private String outOfBoundsMsg(int index) {
+ return "Index: "+index+", Size: "+size;
+ }
+
+ private void checkForComodification() {
+ if (this.modCount != l.modCount)
+ throw new ConcurrentModificationException();
+ }
+}
+
+class RandomAccessSubList extends SubList implements RandomAccess {
+ RandomAccessSubList(AbstractList list, int fromIndex, int toIndex) {
+ super(list, fromIndex, toIndex);
+ }
+
+ public List subList(int fromIndex, int toIndex) {
+ return new RandomAccessSubList<>(this, fromIndex, toIndex);
+ }
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/util/AbstractMap.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/util/AbstractMap.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,822 @@
+/*
+ * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.util;
+import java.util.Map.Entry;
+
+/**
+ * This class provides a skeletal implementation of the Map
+ * interface, to minimize the effort required to implement this interface.
+ *
+ *
To implement an unmodifiable map, the programmer needs only to extend this
+ * class and provide an implementation for the entrySet method, which
+ * returns a set-view of the map's mappings. Typically, the returned set
+ * will, in turn, be implemented atop AbstractSet. This set should
+ * not support the add or remove methods, and its iterator
+ * should not support the remove method.
+ *
+ *
To implement a modifiable map, the programmer must additionally override
+ * this class's put method (which otherwise throws an
+ * UnsupportedOperationException), and the iterator returned by
+ * entrySet().iterator() must additionally implement its
+ * remove method.
+ *
+ *
The programmer should generally provide a void (no argument) and map
+ * constructor, as per the recommendation in the Map interface
+ * specification.
+ *
+ *
The documentation for each non-abstract method in this class describes its
+ * implementation in detail. Each of these methods may be overridden if the
+ * map being implemented admits a more efficient implementation.
+ *
+ *
This class is a member of the
+ *
+ * Java Collections Framework.
+ *
+ * @param the type of keys maintained by this map
+ * @param the type of mapped values
+ *
+ * @author Josh Bloch
+ * @author Neal Gafter
+ * @see Map
+ * @see Collection
+ * @since 1.2
+ */
+
+public abstract class AbstractMap implements Map {
+ /**
+ * Sole constructor. (For invocation by subclass constructors, typically
+ * implicit.)
+ */
+ protected AbstractMap() {
+ }
+
+ // Query Operations
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation returns entrySet().size().
+ */
+ public int size() {
+ return entrySet().size();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over entrySet() searching
+ * for an entry with the specified value. If such an entry is found,
+ * true is returned. If the iteration terminates without
+ * finding such an entry, false is returned. Note that this
+ * implementation requires linear time in the size of the map.
+ *
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ */
+ public boolean containsValue(Object value) {
+ Iterator> i = entrySet().iterator();
+ if (value==null) {
+ while (i.hasNext()) {
+ Entry e = i.next();
+ if (e.getValue()==null)
+ return true;
+ }
+ } else {
+ while (i.hasNext()) {
+ Entry e = i.next();
+ if (value.equals(e.getValue()))
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over entrySet() searching
+ * for an entry with the specified key. If such an entry is found,
+ * true is returned. If the iteration terminates without
+ * finding such an entry, false is returned. Note that this
+ * implementation requires linear time in the size of the map; many
+ * implementations will override this method.
+ *
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ */
+ public boolean containsKey(Object key) {
+ Iterator> i = entrySet().iterator();
+ if (key==null) {
+ while (i.hasNext()) {
+ Entry e = i.next();
+ if (e.getKey()==null)
+ return true;
+ }
+ } else {
+ while (i.hasNext()) {
+ Entry e = i.next();
+ if (key.equals(e.getKey()))
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over entrySet() searching
+ * for an entry with the specified key. If such an entry is found,
+ * the entry's value is returned. If the iteration terminates without
+ * finding such an entry, null is returned. Note that this
+ * implementation requires linear time in the size of the map; many
+ * implementations will override this method.
+ *
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ */
+ public V get(Object key) {
+ Iterator> i = entrySet().iterator();
+ if (key==null) {
+ while (i.hasNext()) {
+ Entry e = i.next();
+ if (e.getKey()==null)
+ return e.getValue();
+ }
+ } else {
+ while (i.hasNext()) {
+ Entry e = i.next();
+ if (key.equals(e.getKey()))
+ return e.getValue();
+ }
+ }
+ return null;
+ }
+
+
+ // Modification Operations
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation always throws an
+ * UnsupportedOperationException.
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ * @throws IllegalArgumentException {@inheritDoc}
+ */
+ public V put(K key, V value) {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over entrySet() searching for an
+ * entry with the specified key. If such an entry is found, its value is
+ * obtained with its getValue operation, the entry is removed
+ * from the collection (and the backing map) with the iterator's
+ * remove operation, and the saved value is returned. If the
+ * iteration terminates without finding such an entry, null is
+ * returned. Note that this implementation requires linear time in the
+ * size of the map; many implementations will override this method.
+ *
+ *
Note that this implementation throws an
+ * UnsupportedOperationException if the entrySet
+ * iterator does not support the remove method and this map
+ * contains a mapping for the specified key.
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ */
+ public V remove(Object key) {
+ Iterator> i = entrySet().iterator();
+ Entry correctEntry = null;
+ if (key==null) {
+ while (correctEntry==null && i.hasNext()) {
+ Entry e = i.next();
+ if (e.getKey()==null)
+ correctEntry = e;
+ }
+ } else {
+ while (correctEntry==null && i.hasNext()) {
+ Entry e = i.next();
+ if (key.equals(e.getKey()))
+ correctEntry = e;
+ }
+ }
+
+ V oldValue = null;
+ if (correctEntry !=null) {
+ oldValue = correctEntry.getValue();
+ i.remove();
+ }
+ return oldValue;
+ }
+
+
+ // Bulk Operations
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation iterates over the specified map's
+ * entrySet() collection, and calls this map's put
+ * operation once for each entry returned by the iteration.
+ *
+ *
Note that this implementation throws an
+ * UnsupportedOperationException if this map does not support
+ * the put operation and the specified map is nonempty.
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ * @throws ClassCastException {@inheritDoc}
+ * @throws NullPointerException {@inheritDoc}
+ * @throws IllegalArgumentException {@inheritDoc}
+ */
+ public void putAll(Map extends K, ? extends V> m) {
+ for (Map.Entry extends K, ? extends V> e : m.entrySet())
+ put(e.getKey(), e.getValue());
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation calls entrySet().clear().
+ *
+ *
Note that this implementation throws an
+ * UnsupportedOperationException if the entrySet
+ * does not support the clear operation.
+ *
+ * @throws UnsupportedOperationException {@inheritDoc}
+ */
+ public void clear() {
+ entrySet().clear();
+ }
+
+
+ // Views
+
+ /**
+ * Each of these fields are initialized to contain an instance of the
+ * appropriate view the first time this view is requested. The views are
+ * stateless, so there's no reason to create more than one of each.
+ */
+ transient volatile Set keySet = null;
+ transient volatile Collection values = null;
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation returns a set that subclasses {@link AbstractSet}.
+ * The subclass's iterator method returns a "wrapper object" over this
+ * map's entrySet() iterator. The size method
+ * delegates to this map's size method and the
+ * contains method delegates to this map's
+ * containsKey method.
+ *
+ *
The set is created the first time this method is called,
+ * and returned in response to all subsequent calls. No synchronization
+ * is performed, so there is a slight chance that multiple calls to this
+ * method will not all return the same set.
+ */
+ public Set keySet() {
+ if (keySet == null) {
+ keySet = new AbstractSet() {
+ public Iterator iterator() {
+ return new Iterator() {
+ private Iterator> i = entrySet().iterator();
+
+ public boolean hasNext() {
+ return i.hasNext();
+ }
+
+ public K next() {
+ return i.next().getKey();
+ }
+
+ public void remove() {
+ i.remove();
+ }
+ };
+ }
+
+ public int size() {
+ return AbstractMap.this.size();
+ }
+
+ public boolean isEmpty() {
+ return AbstractMap.this.isEmpty();
+ }
+
+ public void clear() {
+ AbstractMap.this.clear();
+ }
+
+ public boolean contains(Object k) {
+ return AbstractMap.this.containsKey(k);
+ }
+ };
+ }
+ return keySet;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ *
This implementation returns a collection that subclasses {@link
+ * AbstractCollection}. The subclass's iterator method returns a
+ * "wrapper object" over this map's entrySet() iterator.
+ * The size method delegates to this map's size
+ * method and the contains method delegates to this map's
+ * containsValue method.
+ *
+ *
The collection is created the first time this method is called, and
+ * returned in response to all subsequent calls. No synchronization is
+ * performed, so there is a slight chance that multiple calls to this
+ * method will not all return the same collection.
+ */
+ public Collection values() {
+ if (values == null) {
+ values = new AbstractCollection() {
+ public Iterator iterator() {
+ return new Iterator() {
+ private Iterator> i = entrySet().iterator();
+
+ public boolean hasNext() {
+ return i.hasNext();
+ }
+
+ public V next() {
+ return i.next().getValue();
+ }
+
+ public void remove() {
+ i.remove();
+ }
+ };
+ }
+
+ public int size() {
+ return AbstractMap.this.size();
+ }
+
+ public boolean isEmpty() {
+ return AbstractMap.this.isEmpty();
+ }
+
+ public void clear() {
+ AbstractMap.this.clear();
+ }
+
+ public boolean contains(Object v) {
+ return AbstractMap.this.containsValue(v);
+ }
+ };
+ }
+ return values;
+ }
+
+ public abstract Set> entrySet();
+
+
+ // Comparison and hashing
+
+ /**
+ * Compares the specified object with this map for equality. Returns
+ * true if the given object is also a map and the two maps
+ * represent the same mappings. More formally, two maps m1 and
+ * m2 represent the same mappings if
+ * m1.entrySet().equals(m2.entrySet()). This ensures that the
+ * equals method works properly across different implementations
+ * of the Map interface.
+ *
+ *
This implementation first checks if the specified object is this map;
+ * if so it returns true. Then, it checks if the specified
+ * object is a map whose size is identical to the size of this map; if
+ * not, it returns false. If so, it iterates over this map's
+ * entrySet collection, and checks that the specified map
+ * contains each mapping that this map contains. If the specified map
+ * fails to contain such a mapping, false is returned. If the
+ * iteration completes, true is returned.
+ *
+ * @param o object to be compared for equality with this map
+ * @return true if the specified object is equal to this map
+ */
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+
+ if (!(o instanceof Map))
+ return false;
+ Map m = (Map) o;
+ if (m.size() != size())
+ return false;
+
+ try {
+ Iterator> i = entrySet().iterator();
+ while (i.hasNext()) {
+ Entry e = i.next();
+ K key = e.getKey();
+ V value = e.getValue();
+ if (value == null) {
+ if (!(m.get(key)==null && m.containsKey(key)))
+ return false;
+ } else {
+ if (!value.equals(m.get(key)))
+ return false;
+ }
+ }
+ } catch (ClassCastException unused) {
+ return false;
+ } catch (NullPointerException unused) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Returns the hash code value for this map. The hash code of a map is
+ * defined to be the sum of the hash codes of each entry in the map's
+ * entrySet() view. This ensures that m1.equals(m2)
+ * implies that m1.hashCode()==m2.hashCode() for any two maps
+ * m1 and m2, as required by the general contract of
+ * {@link Object#hashCode}.
+ *
+ *
This implementation iterates over entrySet(), calling
+ * {@link Map.Entry#hashCode hashCode()} on each element (entry) in the
+ * set, and adding up the results.
+ *
+ * @return the hash code value for this map
+ * @see Map.Entry#hashCode()
+ * @see Object#equals(Object)
+ * @see Set#equals(Object)
+ */
+ public int hashCode() {
+ int h = 0;
+ Iterator> i = entrySet().iterator();
+ while (i.hasNext())
+ h += i.next().hashCode();
+ return h;
+ }
+
+ /**
+ * Returns a string representation of this map. The string representation
+ * consists of a list of key-value mappings in the order returned by the
+ * map's entrySet view's iterator, enclosed in braces
+ * ("{}"). Adjacent mappings are separated by the characters
+ * ", " (comma and space). Each key-value mapping is rendered as
+ * the key followed by an equals sign ("=") followed by the
+ * associated value. Keys and values are converted to strings as by
+ * {@link String#valueOf(Object)}.
+ *
+ * @return a string representation of this map
+ */
+ public String toString() {
+ Iterator> i = entrySet().iterator();
+ if (! i.hasNext())
+ return "{}";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append('{');
+ for (;;) {
+ Entry e = i.next();
+ K key = e.getKey();
+ V value = e.getValue();
+ sb.append(key == this ? "(this Map)" : key);
+ sb.append('=');
+ sb.append(value == this ? "(this Map)" : value);
+ if (! i.hasNext())
+ return sb.append('}').toString();
+ sb.append(',').append(' ');
+ }
+ }
+
+ /**
+ * Returns a shallow copy of this AbstractMap instance: the keys
+ * and values themselves are not cloned.
+ *
+ * @return a shallow copy of this map
+ */
+ protected Object clone() throws CloneNotSupportedException {
+ AbstractMap result = (AbstractMap)super.clone();
+ result.keySet = null;
+ result.values = null;
+ return result;
+ }
+
+ /**
+ * Utility method for SimpleEntry and SimpleImmutableEntry.
+ * Test for equality, checking for nulls.
+ */
+ private static boolean eq(Object o1, Object o2) {
+ return o1 == null ? o2 == null : o1.equals(o2);
+ }
+
+ // Implementation Note: SimpleEntry and SimpleImmutableEntry
+ // are distinct unrelated classes, even though they share
+ // some code. Since you can't add or subtract final-ness
+ // of a field in a subclass, they can't share representations,
+ // and the amount of duplicated code is too small to warrant
+ // exposing a common abstract class.
+
+
+ /**
+ * An Entry maintaining a key and a value. The value may be
+ * changed using the setValue method. This class
+ * facilitates the process of building custom map
+ * implementations. For example, it may be convenient to return
+ * arrays of SimpleEntry instances in method
+ * Map.entrySet().toArray.
+ *
+ * @since 1.6
+ */
+ public static class SimpleEntry
+ implements Entry, java.io.Serializable
+ {
+ private static final long serialVersionUID = -8499721149061103585L;
+
+ private final K key;
+ private V value;
+
+ /**
+ * Creates an entry representing a mapping from the specified
+ * key to the specified value.
+ *
+ * @param key the key represented by this entry
+ * @param value the value represented by this entry
+ */
+ public SimpleEntry(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ /**
+ * Creates an entry representing the same mapping as the
+ * specified entry.
+ *
+ * @param entry the entry to copy
+ */
+ public SimpleEntry(Entry extends K, ? extends V> entry) {
+ this.key = entry.getKey();
+ this.value = entry.getValue();
+ }
+
+ /**
+ * Returns the key corresponding to this entry.
+ *
+ * @return the key corresponding to this entry
+ */
+ public K getKey() {
+ return key;
+ }
+
+ /**
+ * Returns the value corresponding to this entry.
+ *
+ * @return the value corresponding to this entry
+ */
+ public V getValue() {
+ return value;
+ }
+
+ /**
+ * Replaces the value corresponding to this entry with the specified
+ * value.
+ *
+ * @param value new value to be stored in this entry
+ * @return the old value corresponding to the entry
+ */
+ public V setValue(V value) {
+ V oldValue = this.value;
+ this.value = value;
+ return oldValue;
+ }
+
+ /**
+ * Compares the specified object with this entry for equality.
+ * Returns {@code true} if the given object is also a map entry and
+ * the two entries represent the same mapping. More formally, two
+ * entries {@code e1} and {@code e2} represent the same mapping
+ * if
+ * This ensures that the {@code equals} method works properly across
+ * different implementations of the {@code Map.Entry} interface.
+ *
+ * @param o object to be compared for equality with this map entry
+ * @return {@code true} if the specified object is equal to this map
+ * entry
+ * @see #hashCode
+ */
+ public boolean equals(Object o) {
+ if (!(o instanceof Map.Entry))
+ return false;
+ Map.Entry e = (Map.Entry)o;
+ return eq(key, e.getKey()) && eq(value, e.getValue());
+ }
+
+ /**
+ * Returns the hash code value for this map entry. The hash code
+ * of a map entry {@code e} is defined to be:
+ * This ensures that {@code e1.equals(e2)} implies that
+ * {@code e1.hashCode()==e2.hashCode()} for any two Entries
+ * {@code e1} and {@code e2}, as required by the general
+ * contract of {@link Object#hashCode}.
+ *
+ * @return the hash code value for this map entry
+ * @see #equals
+ */
+ public int hashCode() {
+ return (key == null ? 0 : key.hashCode()) ^
+ (value == null ? 0 : value.hashCode());
+ }
+
+ /**
+ * Returns a String representation of this map entry. This
+ * implementation returns the string representation of this
+ * entry's key followed by the equals character ("=")
+ * followed by the string representation of this entry's value.
+ *
+ * @return a String representation of this map entry
+ */
+ public String toString() {
+ return key + "=" + value;
+ }
+
+ }
+
+ /**
+ * An Entry maintaining an immutable key and value. This class
+ * does not support method setValue. This class may be
+ * convenient in methods that return thread-safe snapshots of
+ * key-value mappings.
+ *
+ * @since 1.6
+ */
+ public static class SimpleImmutableEntry
+ implements Entry, java.io.Serializable
+ {
+ private static final long serialVersionUID = 7138329143949025153L;
+
+ private final K key;
+ private final V value;
+
+ /**
+ * Creates an entry representing a mapping from the specified
+ * key to the specified value.
+ *
+ * @param key the key represented by this entry
+ * @param value the value represented by this entry
+ */
+ public SimpleImmutableEntry(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ /**
+ * Creates an entry representing the same mapping as the
+ * specified entry.
+ *
+ * @param entry the entry to copy
+ */
+ public SimpleImmutableEntry(Entry extends K, ? extends V> entry) {
+ this.key = entry.getKey();
+ this.value = entry.getValue();
+ }
+
+ /**
+ * Returns the key corresponding to this entry.
+ *
+ * @return the key corresponding to this entry
+ */
+ public K getKey() {
+ return key;
+ }
+
+ /**
+ * Returns the value corresponding to this entry.
+ *
+ * @return the value corresponding to this entry
+ */
+ public V getValue() {
+ return value;
+ }
+
+ /**
+ * Replaces the value corresponding to this entry with the specified
+ * value (optional operation). This implementation simply throws
+ * UnsupportedOperationException, as this class implements
+ * an immutable map entry.
+ *
+ * @param value new value to be stored in this entry
+ * @return (Does not return)
+ * @throws UnsupportedOperationException always
+ */
+ public V setValue(V value) {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Compares the specified object with this entry for equality.
+ * Returns {@code true} if the given object is also a map entry and
+ * the two entries represent the same mapping. More formally, two
+ * entries {@code e1} and {@code e2} represent the same mapping
+ * if
+ * This ensures that the {@code equals} method works properly across
+ * different implementations of the {@code Map.Entry} interface.
+ *
+ * @param o object to be compared for equality with this map entry
+ * @return {@code true} if the specified object is equal to this map
+ * entry
+ * @see #hashCode
+ */
+ public boolean equals(Object o) {
+ if (!(o instanceof Map.Entry))
+ return false;
+ Map.Entry e = (Map.Entry)o;
+ return eq(key, e.getKey()) && eq(value, e.getValue());
+ }
+
+ /**
+ * Returns the hash code value for this map entry. The hash code
+ * of a map entry {@code e} is defined to be:
+ * This ensures that {@code e1.equals(e2)} implies that
+ * {@code e1.hashCode()==e2.hashCode()} for any two Entries
+ * {@code e1} and {@code e2}, as required by the general
+ * contract of {@link Object#hashCode}.
+ *
+ * @return the hash code value for this map entry
+ * @see #equals
+ */
+ public int hashCode() {
+ return (key == null ? 0 : key.hashCode()) ^
+ (value == null ? 0 : value.hashCode());
+ }
+
+ /**
+ * Returns a String representation of this map entry. This
+ * implementation returns the string representation of this
+ * entry's key followed by the equals character ("=")
+ * followed by the string representation of this entry's value.
+ *
+ * @return a String representation of this map entry
+ */
+ public String toString() {
+ return key + "=" + value;
+ }
+
+ }
+
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/util/AbstractSet.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/util/AbstractSet.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,185 @@
+/*
+ * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.util;
+
+/**
+ * This class provides a skeletal implementation of the Set
+ * interface to minimize the effort required to implement this
+ * interface.
+ *
+ * The process of implementing a set by extending this class is identical
+ * to that of implementing a Collection by extending AbstractCollection,
+ * except that all of the methods and constructors in subclasses of this
+ * class must obey the additional constraints imposed by the Set
+ * interface (for instance, the add method must not permit addition of
+ * multiple instances of an object to a set).
+ *
+ * Note that this class does not override any of the implementations from
+ * the AbstractCollection class. It merely adds implementations
+ * for equals and hashCode.
+ *
+ * This class is a member of the
+ *
+ * Java Collections Framework.
+ *
+ * @param the type of elements maintained by this set
+ *
+ * @author Josh Bloch
+ * @author Neal Gafter
+ * @see Collection
+ * @see AbstractCollection
+ * @see Set
+ * @since 1.2
+ */
+
+public abstract class AbstractSet extends AbstractCollection implements Set {
+ /**
+ * Sole constructor. (For invocation by subclass constructors, typically
+ * implicit.)
+ */
+ protected AbstractSet() {
+ }
+
+ // Comparison and hashing
+
+ /**
+ * Compares the specified object with this set for equality. Returns
+ * true if the given object is also a set, the two sets have
+ * the same size, and every member of the given set is contained in
+ * this set. This ensures that the equals method works
+ * properly across different implementations of the Set
+ * interface.
+ *
+ * This implementation first checks if the specified object is this
+ * set; if so it returns true. Then, it checks if the
+ * specified object is a set whose size is identical to the size of
+ * this set; if not, it returns false. If so, it returns
+ * containsAll((Collection) o).
+ *
+ * @param o object to be compared for equality with this set
+ * @return true if the specified object is equal to this set
+ */
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+
+ if (!(o instanceof Set))
+ return false;
+ Collection c = (Collection) o;
+ if (c.size() != size())
+ return false;
+ try {
+ return containsAll(c);
+ } catch (ClassCastException unused) {
+ return false;
+ } catch (NullPointerException unused) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns the hash code value for this set. The hash code of a set is
+ * defined to be the sum of the hash codes of the elements in the set,
+ * where the hash code of a null element is defined to be zero.
+ * This ensures that s1.equals(s2) implies that
+ * s1.hashCode()==s2.hashCode() for any two sets s1
+ * and s2, as required by the general contract of
+ * {@link Object#hashCode}.
+ *
+ *
This implementation iterates over the set, calling the
+ * hashCode method on each element in the set, and adding up
+ * the results.
+ *
+ * @return the hash code value for this set
+ * @see Object#equals(Object)
+ * @see Set#equals(Object)
+ */
+ public int hashCode() {
+ int h = 0;
+ Iterator i = iterator();
+ while (i.hasNext()) {
+ E obj = i.next();
+ if (obj != null)
+ h += obj.hashCode();
+ }
+ return h;
+ }
+
+ /**
+ * Removes from this set all of its elements that are contained in the
+ * specified collection (optional operation). If the specified
+ * collection is also a set, this operation effectively modifies this
+ * set so that its value is the asymmetric set difference of
+ * the two sets.
+ *
+ *
This implementation determines which is the smaller of this set
+ * and the specified collection, by invoking the size
+ * method on each. If this set has fewer elements, then the
+ * implementation iterates over this set, checking each element
+ * returned by the iterator in turn to see if it is contained in
+ * the specified collection. If it is so contained, it is removed
+ * from this set with the iterator's remove method. If
+ * the specified collection has fewer elements, then the
+ * implementation iterates over the specified collection, removing
+ * from this set each element returned by the iterator, using this
+ * set's remove method.
+ *
+ *
Note that this implementation will throw an
+ * UnsupportedOperationException if the iterator returned by the
+ * iterator method does not implement the remove method.
+ *
+ * @param c collection containing elements to be removed from this set
+ * @return true if this set changed as a result of the call
+ * @throws UnsupportedOperationException if the removeAll operation
+ * is not supported by this set
+ * @throws ClassCastException if the class of an element of this set
+ * is incompatible with the specified collection
+ * (optional)
+ * @throws NullPointerException if this set contains a null element and the
+ * specified collection does not permit null elements
+ * (optional),
+ * or if the specified collection is null
+ * @see #remove(Object)
+ * @see #contains(Object)
+ */
+ public boolean removeAll(Collection> c) {
+ boolean modified = false;
+
+ if (size() > c.size()) {
+ for (Iterator> i = c.iterator(); i.hasNext(); )
+ modified |= remove(i.next());
+ } else {
+ for (Iterator> i = iterator(); i.hasNext(); ) {
+ if (c.contains(i.next())) {
+ i.remove();
+ modified = true;
+ }
+ }
+ }
+ return modified;
+ }
+
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/util/ArrayList.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/util/ArrayList.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,1089 @@
+/*
+ * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.util;
+
+import org.apidesign.bck2brwsr.emul.lang.System;
+
+/**
+ * Resizable-array implementation of the List interface. Implements
+ * all optional list operations, and permits all elements, including
+ * null. In addition to implementing the List interface,
+ * this class provides methods to manipulate the size of the array that is
+ * used internally to store the list. (This class is roughly equivalent to
+ * Vector, except that it is unsynchronized.)
+ *
+ *
The size, isEmpty, get, set,
+ * iterator, and listIterator operations run in constant
+ * time. The add operation runs in amortized constant time,
+ * that is, adding n elements requires O(n) time. All of the other operations
+ * run in linear time (roughly speaking). The constant factor is low compared
+ * to that for the LinkedList implementation.
+ *
+ *
Each ArrayList instance has a capacity. The capacity is
+ * the size of the array used to store the elements in the list. It is always
+ * at least as large as the list size. As elements are added to an ArrayList,
+ * its capacity grows automatically. The details of the growth policy are not
+ * specified beyond the fact that adding an element has constant amortized
+ * time cost.
+ *
+ *
An application can increase the capacity of an ArrayList instance
+ * before adding a large number of elements using the ensureCapacity
+ * operation. This may reduce the amount of incremental reallocation.
+ *
+ *
Note that this implementation is not synchronized.
+ * If multiple threads access an ArrayList instance concurrently,
+ * and at least one of the threads modifies the list structurally, it
+ * must be synchronized externally. (A structural modification is
+ * any operation that adds or deletes one or more elements, or explicitly
+ * resizes the backing array; merely setting the value of an element is not
+ * a structural modification.) This is typically accomplished by
+ * synchronizing on some object that naturally encapsulates the list.
+ *
+ * If no such object exists, the list should be "wrapped" using the
+ * {@link Collections#synchronizedList Collections.synchronizedList}
+ * method. This is best done at creation time, to prevent accidental
+ * unsynchronized access to the list:
+ * List list = Collections.synchronizedList(new ArrayList(...));
+ *
+ *
+ * The iterators returned by this class's {@link #iterator() iterator} and
+ * {@link #listIterator(int) listIterator} methods are fail-fast:
+ * if the list is structurally modified at any time after the iterator is
+ * created, in any way except through the iterator's own
+ * {@link ListIterator#remove() remove} or
+ * {@link ListIterator#add(Object) add} methods, the iterator will throw a
+ * {@link ConcurrentModificationException}. Thus, in the face of
+ * concurrent modification, the iterator fails quickly and cleanly, rather
+ * than risking arbitrary, non-deterministic behavior at an undetermined
+ * time in the future.
+ *
+ *
Note that the fail-fast behavior of an iterator cannot be guaranteed
+ * as it is, generally speaking, impossible to make any hard guarantees in the
+ * presence of unsynchronized concurrent modification. Fail-fast iterators
+ * throw {@code ConcurrentModificationException} on a best-effort basis.
+ * Therefore, it would be wrong to write a program that depended on this
+ * exception for its correctness: the fail-fast behavior of iterators
+ * should be used only to detect bugs.
+ *
+ *
This class is a member of the
+ *
+ * Java Collections Framework.
+ *
+ * @author Josh Bloch
+ * @author Neal Gafter
+ * @see Collection
+ * @see List
+ * @see LinkedList
+ * @see Vector
+ * @since 1.2
+ */
+
+public class ArrayList extends AbstractList
+ implements List, RandomAccess, Cloneable, java.io.Serializable
+{
+ private static final long serialVersionUID = 8683452581122892189L;
+
+ /**
+ * The array buffer into which the elements of the ArrayList are stored.
+ * The capacity of the ArrayList is the length of this array buffer.
+ */
+ private transient Object[] elementData;
+
+ /**
+ * The size of the ArrayList (the number of elements it contains).
+ *
+ * @serial
+ */
+ private int size;
+
+ /**
+ * Constructs an empty list with the specified initial capacity.
+ *
+ * @param initialCapacity the initial capacity of the list
+ * @throws IllegalArgumentException if the specified initial capacity
+ * is negative
+ */
+ public ArrayList(int initialCapacity) {
+ super();
+ if (initialCapacity < 0)
+ throw new IllegalArgumentException("Illegal Capacity: "+
+ initialCapacity);
+ this.elementData = new Object[initialCapacity];
+ }
+
+ /**
+ * Constructs an empty list with an initial capacity of ten.
+ */
+ public ArrayList() {
+ this(10);
+ }
+
+ /**
+ * Constructs a list containing the elements of the specified
+ * collection, in the order they are returned by the collection's
+ * iterator.
+ *
+ * @param c the collection whose elements are to be placed into this list
+ * @throws NullPointerException if the specified collection is null
+ */
+ public ArrayList(Collection extends E> c) {
+ elementData = c.toArray();
+ size = elementData.length;
+ // c.toArray might (incorrectly) not return Object[] (see 6260652)
+ if (elementData.getClass() != Object[].class)
+ elementData = Arrays.copyOf(elementData, size, Object[].class);
+ }
+
+ /**
+ * Trims the capacity of this ArrayList instance to be the
+ * list's current size. An application can use this operation to minimize
+ * the storage of an ArrayList instance.
+ */
+ public void trimToSize() {
+ modCount++;
+ int oldCapacity = elementData.length;
+ if (size < oldCapacity) {
+ elementData = Arrays.copyOf(elementData, size);
+ }
+ }
+
+ /**
+ * Increases the capacity of this ArrayList instance, if
+ * necessary, to ensure that it can hold at least the number of elements
+ * specified by the minimum capacity argument.
+ *
+ * @param minCapacity the desired minimum capacity
+ */
+ public void ensureCapacity(int minCapacity) {
+ if (minCapacity > 0)
+ ensureCapacityInternal(minCapacity);
+ }
+
+ private void ensureCapacityInternal(int minCapacity) {
+ modCount++;
+ // overflow-conscious code
+ if (minCapacity - elementData.length > 0)
+ grow(minCapacity);
+ }
+
+ /**
+ * The maximum size of array to allocate.
+ * Some VMs reserve some header words in an array.
+ * Attempts to allocate larger arrays may result in
+ * OutOfMemoryError: Requested array size exceeds VM limit
+ */
+ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+
+ /**
+ * Increases the capacity to ensure that it can hold at least the
+ * number of elements specified by the minimum capacity argument.
+ *
+ * @param minCapacity the desired minimum capacity
+ */
+ private void grow(int minCapacity) {
+ // overflow-conscious code
+ int oldCapacity = elementData.length;
+ int newCapacity = oldCapacity + (oldCapacity >> 1);
+ if (newCapacity - minCapacity < 0)
+ newCapacity = minCapacity;
+ if (newCapacity - MAX_ARRAY_SIZE > 0)
+ newCapacity = hugeCapacity(minCapacity);
+ // minCapacity is usually close to size, so this is a win:
+ elementData = Arrays.copyOf(elementData, newCapacity);
+ }
+
+ private static int hugeCapacity(int minCapacity) {
+ if (minCapacity < 0) // overflow
+ throw new OutOfMemoryError();
+ return (minCapacity > MAX_ARRAY_SIZE) ?
+ Integer.MAX_VALUE :
+ MAX_ARRAY_SIZE;
+ }
+
+ /**
+ * Returns the number of elements in this list.
+ *
+ * @return the number of elements in this list
+ */
+ public int size() {
+ return size;
+ }
+
+ /**
+ * Returns true if this list contains no elements.
+ *
+ * @return true if this list contains no elements
+ */
+ public boolean isEmpty() {
+ return size == 0;
+ }
+
+ /**
+ * Returns true if this list contains the specified element.
+ * More formally, returns true if and only if this list contains
+ * at least one element e such that
+ * (o==null ? e==null : o.equals(e)).
+ *
+ * @param o element whose presence in this list is to be tested
+ * @return true if this list contains the specified element
+ */
+ public boolean contains(Object o) {
+ return indexOf(o) >= 0;
+ }
+
+ /**
+ * Returns the index of the first occurrence of the specified element
+ * in this list, or -1 if this list does not contain the element.
+ * More formally, returns the lowest index i such that
+ * (o==null ? get(i)==null : o.equals(get(i))),
+ * or -1 if there is no such index.
+ */
+ public int indexOf(Object o) {
+ if (o == null) {
+ for (int i = 0; i < size; i++)
+ if (elementData[i]==null)
+ return i;
+ } else {
+ for (int i = 0; i < size; i++)
+ if (o.equals(elementData[i]))
+ return i;
+ }
+ return -1;
+ }
+
+ /**
+ * Returns the index of the last occurrence of the specified element
+ * in this list, or -1 if this list does not contain the element.
+ * More formally, returns the highest index i such that
+ * (o==null ? get(i)==null : o.equals(get(i))),
+ * or -1 if there is no such index.
+ */
+ public int lastIndexOf(Object o) {
+ if (o == null) {
+ for (int i = size-1; i >= 0; i--)
+ if (elementData[i]==null)
+ return i;
+ } else {
+ for (int i = size-1; i >= 0; i--)
+ if (o.equals(elementData[i]))
+ return i;
+ }
+ return -1;
+ }
+
+ /**
+ * Returns a shallow copy of this ArrayList instance. (The
+ * elements themselves are not copied.)
+ *
+ * @return a clone of this ArrayList instance
+ */
+ public Object clone() {
+ try {
+ @SuppressWarnings("unchecked")
+ ArrayList v = (ArrayList) super.clone();
+ v.elementData = Arrays.copyOf(elementData, size);
+ v.modCount = 0;
+ return v;
+ } catch (CloneNotSupportedException e) {
+ // this shouldn't happen, since we are Cloneable
+ throw new InternalError();
+ }
+ }
+
+ /**
+ * Returns an array containing all of the elements in this list
+ * in proper sequence (from first to last element).
+ *
+ *
The returned array will be "safe" in that no references to it are
+ * maintained by this list. (In other words, this method must allocate
+ * a new array). The caller is thus free to modify the returned array.
+ *
+ *
This method acts as bridge between array-based and collection-based
+ * APIs.
+ *
+ * @return an array containing all of the elements in this list in
+ * proper sequence
+ */
+ public Object[] toArray() {
+ return Arrays.copyOf(elementData, size);
+ }
+
+ /**
+ * Returns an array containing all of the elements in this list in proper
+ * sequence (from first to last element); the runtime type of the returned
+ * array is that of the specified array. If the list fits in the
+ * specified array, it is returned therein. Otherwise, a new array is
+ * allocated with the runtime type of the specified array and the size of
+ * this list.
+ *
+ *
If the list fits in the specified array with room to spare
+ * (i.e., the array has more elements than the list), the element in
+ * the array immediately following the end of the collection is set to
+ * null. (This is useful in determining the length of the
+ * list only if the caller knows that the list does not contain
+ * any null elements.)
+ *
+ * @param a the array into which the elements of the list are to
+ * be stored, if it is big enough; otherwise, a new array of the
+ * same runtime type is allocated for this purpose.
+ * @return an array containing the elements of the list
+ * @throws ArrayStoreException if the runtime type of the specified array
+ * is not a supertype of the runtime type of every element in
+ * this list
+ * @throws NullPointerException if the specified array is null
+ */
+ @SuppressWarnings("unchecked")
+ public T[] toArray(T[] a) {
+ if (a.length < size)
+ // Make a new array of a's runtime type, but my contents:
+ return (T[]) Arrays.copyOf(elementData, size, a.getClass());
+ System.arraycopy(elementData, 0, a, 0, size);
+ if (a.length > size)
+ a[size] = null;
+ return a;
+ }
+
+ // Positional Access Operations
+
+ @SuppressWarnings("unchecked")
+ E elementData(int index) {
+ return (E) elementData[index];
+ }
+
+ /**
+ * Returns the element at the specified position in this list.
+ *
+ * @param index index of the element to return
+ * @return the element at the specified position in this list
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ */
+ public E get(int index) {
+ rangeCheck(index);
+
+ return elementData(index);
+ }
+
+ /**
+ * Replaces the element at the specified position in this list with
+ * the specified element.
+ *
+ * @param index index of the element to replace
+ * @param element element to be stored at the specified position
+ * @return the element previously at the specified position
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ */
+ public E set(int index, E element) {
+ rangeCheck(index);
+
+ E oldValue = elementData(index);
+ elementData[index] = element;
+ return oldValue;
+ }
+
+ /**
+ * Appends the specified element to the end of this list.
+ *
+ * @param e element to be appended to this list
+ * @return true (as specified by {@link Collection#add})
+ */
+ public boolean add(E e) {
+ ensureCapacityInternal(size + 1); // Increments modCount!!
+ elementData[size++] = e;
+ return true;
+ }
+
+ /**
+ * Inserts the specified element at the specified position in this
+ * list. Shifts the element currently at that position (if any) and
+ * any subsequent elements to the right (adds one to their indices).
+ *
+ * @param index index at which the specified element is to be inserted
+ * @param element element to be inserted
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ */
+ public void add(int index, E element) {
+ rangeCheckForAdd(index);
+
+ ensureCapacityInternal(size + 1); // Increments modCount!!
+ System.arraycopy(elementData, index, elementData, index + 1,
+ size - index);
+ elementData[index] = element;
+ size++;
+ }
+
+ /**
+ * Removes the element at the specified position in this list.
+ * Shifts any subsequent elements to the left (subtracts one from their
+ * indices).
+ *
+ * @param index the index of the element to be removed
+ * @return the element that was removed from the list
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ */
+ public E remove(int index) {
+ rangeCheck(index);
+
+ modCount++;
+ E oldValue = elementData(index);
+
+ int numMoved = size - index - 1;
+ if (numMoved > 0)
+ System.arraycopy(elementData, index+1, elementData, index,
+ numMoved);
+ elementData[--size] = null; // Let gc do its work
+
+ return oldValue;
+ }
+
+ /**
+ * Removes the first occurrence of the specified element from this list,
+ * if it is present. If the list does not contain the element, it is
+ * unchanged. More formally, removes the element with the lowest index
+ * i such that
+ * (o==null ? get(i)==null : o.equals(get(i)))
+ * (if such an element exists). Returns true if this list
+ * contained the specified element (or equivalently, if this list
+ * changed as a result of the call).
+ *
+ * @param o element to be removed from this list, if present
+ * @return true if this list contained the specified element
+ */
+ public boolean remove(Object o) {
+ if (o == null) {
+ for (int index = 0; index < size; index++)
+ if (elementData[index] == null) {
+ fastRemove(index);
+ return true;
+ }
+ } else {
+ for (int index = 0; index < size; index++)
+ if (o.equals(elementData[index])) {
+ fastRemove(index);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /*
+ * Private remove method that skips bounds checking and does not
+ * return the value removed.
+ */
+ private void fastRemove(int index) {
+ modCount++;
+ int numMoved = size - index - 1;
+ if (numMoved > 0)
+ System.arraycopy(elementData, index+1, elementData, index,
+ numMoved);
+ elementData[--size] = null; // Let gc do its work
+ }
+
+ /**
+ * Removes all of the elements from this list. The list will
+ * be empty after this call returns.
+ */
+ public void clear() {
+ modCount++;
+
+ // Let gc do its work
+ for (int i = 0; i < size; i++)
+ elementData[i] = null;
+
+ size = 0;
+ }
+
+ /**
+ * Appends all of the elements in the specified collection to the end of
+ * this list, in the order that they are returned by the
+ * specified collection's Iterator. The behavior of this operation is
+ * undefined if the specified collection is modified while the operation
+ * is in progress. (This implies that the behavior of this call is
+ * undefined if the specified collection is this list, and this
+ * list is nonempty.)
+ *
+ * @param c collection containing elements to be added to this list
+ * @return true if this list changed as a result of the call
+ * @throws NullPointerException if the specified collection is null
+ */
+ public boolean addAll(Collection extends E> c) {
+ Object[] a = c.toArray();
+ int numNew = a.length;
+ ensureCapacityInternal(size + numNew); // Increments modCount
+ System.arraycopy(a, 0, elementData, size, numNew);
+ size += numNew;
+ return numNew != 0;
+ }
+
+ /**
+ * Inserts all of the elements in the specified collection into this
+ * list, starting at the specified position. Shifts the element
+ * currently at that position (if any) and any subsequent elements to
+ * the right (increases their indices). The new elements will appear
+ * in the list in the order that they are returned by the
+ * specified collection's iterator.
+ *
+ * @param index index at which to insert the first element from the
+ * specified collection
+ * @param c collection containing elements to be added to this list
+ * @return true if this list changed as a result of the call
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ * @throws NullPointerException if the specified collection is null
+ */
+ public boolean addAll(int index, Collection extends E> c) {
+ rangeCheckForAdd(index);
+
+ Object[] a = c.toArray();
+ int numNew = a.length;
+ ensureCapacityInternal(size + numNew); // Increments modCount
+
+ int numMoved = size - index;
+ if (numMoved > 0)
+ System.arraycopy(elementData, index, elementData, index + numNew,
+ numMoved);
+
+ System.arraycopy(a, 0, elementData, index, numNew);
+ size += numNew;
+ return numNew != 0;
+ }
+
+ /**
+ * Removes from this list all of the elements whose index is between
+ * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
+ * Shifts any succeeding elements to the left (reduces their index).
+ * This call shortens the list by {@code (toIndex - fromIndex)} elements.
+ * (If {@code toIndex==fromIndex}, this operation has no effect.)
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex} or
+ * {@code toIndex} is out of range
+ * ({@code fromIndex < 0 ||
+ * fromIndex >= size() ||
+ * toIndex > size() ||
+ * toIndex < fromIndex})
+ */
+ protected void removeRange(int fromIndex, int toIndex) {
+ modCount++;
+ int numMoved = size - toIndex;
+ System.arraycopy(elementData, toIndex, elementData, fromIndex,
+ numMoved);
+
+ // Let gc do its work
+ int newSize = size - (toIndex-fromIndex);
+ while (size != newSize)
+ elementData[--size] = null;
+ }
+
+ /**
+ * Checks if the given index is in range. If not, throws an appropriate
+ * runtime exception. This method does *not* check if the index is
+ * negative: It is always used immediately prior to an array access,
+ * which throws an ArrayIndexOutOfBoundsException if index is negative.
+ */
+ private void rangeCheck(int index) {
+ if (index >= size)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ /**
+ * A version of rangeCheck used by add and addAll.
+ */
+ private void rangeCheckForAdd(int index) {
+ if (index > size || index < 0)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ /**
+ * Constructs an IndexOutOfBoundsException detail message.
+ * Of the many possible refactorings of the error handling code,
+ * this "outlining" performs best with both server and client VMs.
+ */
+ private String outOfBoundsMsg(int index) {
+ return "Index: "+index+", Size: "+size;
+ }
+
+ /**
+ * Removes from this list all of its elements that are contained in the
+ * specified collection.
+ *
+ * @param c collection containing elements to be removed from this list
+ * @return {@code true} if this list changed as a result of the call
+ * @throws ClassCastException if the class of an element of this list
+ * is incompatible with the specified collection
+ * (optional)
+ * @throws NullPointerException if this list contains a null element and the
+ * specified collection does not permit null elements
+ * (optional),
+ * or if the specified collection is null
+ * @see Collection#contains(Object)
+ */
+ public boolean removeAll(Collection> c) {
+ return batchRemove(c, false);
+ }
+
+ /**
+ * Retains only the elements in this list that are contained in the
+ * specified collection. In other words, removes from this list all
+ * of its elements that are not contained in the specified collection.
+ *
+ * @param c collection containing elements to be retained in this list
+ * @return {@code true} if this list changed as a result of the call
+ * @throws ClassCastException if the class of an element of this list
+ * is incompatible with the specified collection
+ * (optional)
+ * @throws NullPointerException if this list contains a null element and the
+ * specified collection does not permit null elements
+ * (optional),
+ * or if the specified collection is null
+ * @see Collection#contains(Object)
+ */
+ public boolean retainAll(Collection> c) {
+ return batchRemove(c, true);
+ }
+
+ private boolean batchRemove(Collection> c, boolean complement) {
+ final Object[] elementData = this.elementData;
+ int r = 0, w = 0;
+ boolean modified = false;
+ try {
+ for (; r < size; r++)
+ if (c.contains(elementData[r]) == complement)
+ elementData[w++] = elementData[r];
+ } finally {
+ // Preserve behavioral compatibility with AbstractCollection,
+ // even if c.contains() throws.
+ if (r != size) {
+ System.arraycopy(elementData, r,
+ elementData, w,
+ size - r);
+ w += size - r;
+ }
+ if (w != size) {
+ for (int i = w; i < size; i++)
+ elementData[i] = null;
+ modCount += size - w;
+ size = w;
+ modified = true;
+ }
+ }
+ return modified;
+ }
+
+ /**
+ * Returns a list iterator over the elements in this list (in proper
+ * sequence), starting at the specified position in the list.
+ * The specified index indicates the first element that would be
+ * returned by an initial call to {@link ListIterator#next next}.
+ * An initial call to {@link ListIterator#previous previous} would
+ * return the element with the specified index minus one.
+ *
+ *
The returned list iterator is fail-fast.
+ *
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ */
+ public ListIterator listIterator(int index) {
+ if (index < 0 || index > size)
+ throw new IndexOutOfBoundsException("Index: "+index);
+ return new ListItr(index);
+ }
+
+ /**
+ * Returns a list iterator over the elements in this list (in proper
+ * sequence).
+ *
+ *
The returned list iterator is fail-fast.
+ *
+ * @see #listIterator(int)
+ */
+ public ListIterator listIterator() {
+ return new ListItr(0);
+ }
+
+ /**
+ * Returns an iterator over the elements in this list in proper sequence.
+ *
+ *
The returned iterator is fail-fast.
+ *
+ * @return an iterator over the elements in this list in proper sequence
+ */
+ public Iterator iterator() {
+ return new Itr();
+ }
+
+ /**
+ * An optimized version of AbstractList.Itr
+ */
+ private class Itr implements Iterator {
+ int cursor; // index of next element to return
+ int lastRet = -1; // index of last element returned; -1 if no such
+ int expectedModCount = modCount;
+
+ public boolean hasNext() {
+ return cursor != size;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E next() {
+ checkForComodification();
+ int i = cursor;
+ if (i >= size)
+ throw new NoSuchElementException();
+ Object[] elementData = ArrayList.this.elementData;
+ if (i >= elementData.length)
+ throw new ConcurrentModificationException();
+ cursor = i + 1;
+ return (E) elementData[lastRet = i];
+ }
+
+ public void remove() {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
+ try {
+ ArrayList.this.remove(lastRet);
+ cursor = lastRet;
+ lastRet = -1;
+ expectedModCount = modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ final void checkForComodification() {
+ if (modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ /**
+ * An optimized version of AbstractList.ListItr
+ */
+ private class ListItr extends Itr implements ListIterator {
+ ListItr(int index) {
+ super();
+ cursor = index;
+ }
+
+ public boolean hasPrevious() {
+ return cursor != 0;
+ }
+
+ public int nextIndex() {
+ return cursor;
+ }
+
+ public int previousIndex() {
+ return cursor - 1;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E previous() {
+ checkForComodification();
+ int i = cursor - 1;
+ if (i < 0)
+ throw new NoSuchElementException();
+ Object[] elementData = ArrayList.this.elementData;
+ if (i >= elementData.length)
+ throw new ConcurrentModificationException();
+ cursor = i;
+ return (E) elementData[lastRet = i];
+ }
+
+ public void set(E e) {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
+ try {
+ ArrayList.this.set(lastRet, e);
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ public void add(E e) {
+ checkForComodification();
+
+ try {
+ int i = cursor;
+ ArrayList.this.add(i, e);
+ cursor = i + 1;
+ lastRet = -1;
+ expectedModCount = modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+ }
+
+ /**
+ * Returns a view of the portion of this list between the specified
+ * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
+ * {@code fromIndex} and {@code toIndex} are equal, the returned list is
+ * empty.) The returned list is backed by this list, so non-structural
+ * changes in the returned list are reflected in this list, and vice-versa.
+ * The returned list supports all of the optional list operations.
+ *
+ *
This method eliminates the need for explicit range operations (of
+ * the sort that commonly exist for arrays). Any operation that expects
+ * a list can be used as a range operation by passing a subList view
+ * instead of a whole list. For example, the following idiom
+ * removes a range of elements from a list:
+ *
+ * list.subList(from, to).clear();
+ *
+ * Similar idioms may be constructed for {@link #indexOf(Object)} and
+ * {@link #lastIndexOf(Object)}, and all of the algorithms in the
+ * {@link Collections} class can be applied to a subList.
+ *
+ *
The semantics of the list returned by this method become undefined if
+ * the backing list (i.e., this list) is structurally modified in
+ * any way other than via the returned list. (Structural modifications are
+ * those that change the size of this list, or otherwise perturb it in such
+ * a fashion that iterations in progress may yield incorrect results.)
+ *
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ * @throws IllegalArgumentException {@inheritDoc}
+ */
+ public List subList(int fromIndex, int toIndex) {
+ subListRangeCheck(fromIndex, toIndex, size);
+ return new SubList(this, 0, fromIndex, toIndex);
+ }
+
+ static void subListRangeCheck(int fromIndex, int toIndex, int size) {
+ if (fromIndex < 0)
+ throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
+ if (toIndex > size)
+ throw new IndexOutOfBoundsException("toIndex = " + toIndex);
+ if (fromIndex > toIndex)
+ throw new IllegalArgumentException("fromIndex(" + fromIndex +
+ ") > toIndex(" + toIndex + ")");
+ }
+
+ private class SubList extends AbstractList implements RandomAccess {
+ private final AbstractList parent;
+ private final int parentOffset;
+ private final int offset;
+ int size;
+
+ SubList(AbstractList parent,
+ int offset, int fromIndex, int toIndex) {
+ this.parent = parent;
+ this.parentOffset = fromIndex;
+ this.offset = offset + fromIndex;
+ this.size = toIndex - fromIndex;
+ this.modCount = ArrayList.this.modCount;
+ }
+
+ public E set(int index, E e) {
+ rangeCheck(index);
+ checkForComodification();
+ E oldValue = ArrayList.this.elementData(offset + index);
+ ArrayList.this.elementData[offset + index] = e;
+ return oldValue;
+ }
+
+ public E get(int index) {
+ rangeCheck(index);
+ checkForComodification();
+ return ArrayList.this.elementData(offset + index);
+ }
+
+ public int size() {
+ checkForComodification();
+ return this.size;
+ }
+
+ public void add(int index, E e) {
+ rangeCheckForAdd(index);
+ checkForComodification();
+ parent.add(parentOffset + index, e);
+ this.modCount = parent.modCount;
+ this.size++;
+ }
+
+ public E remove(int index) {
+ rangeCheck(index);
+ checkForComodification();
+ E result = parent.remove(parentOffset + index);
+ this.modCount = parent.modCount;
+ this.size--;
+ return result;
+ }
+
+ protected void removeRange(int fromIndex, int toIndex) {
+ checkForComodification();
+ parent.removeRange(parentOffset + fromIndex,
+ parentOffset + toIndex);
+ this.modCount = parent.modCount;
+ this.size -= toIndex - fromIndex;
+ }
+
+ public boolean addAll(Collection extends E> c) {
+ return addAll(this.size, c);
+ }
+
+ public boolean addAll(int index, Collection extends E> c) {
+ rangeCheckForAdd(index);
+ int cSize = c.size();
+ if (cSize==0)
+ return false;
+
+ checkForComodification();
+ parent.addAll(parentOffset + index, c);
+ this.modCount = parent.modCount;
+ this.size += cSize;
+ return true;
+ }
+
+ public Iterator iterator() {
+ return listIterator();
+ }
+
+ public ListIterator listIterator(final int index) {
+ checkForComodification();
+ rangeCheckForAdd(index);
+ final int offset = this.offset;
+
+ return new ListIterator() {
+ int cursor = index;
+ int lastRet = -1;
+ int expectedModCount = ArrayList.this.modCount;
+
+ public boolean hasNext() {
+ return cursor != SubList.this.size;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E next() {
+ checkForComodification();
+ int i = cursor;
+ if (i >= SubList.this.size)
+ throw new NoSuchElementException();
+ Object[] elementData = ArrayList.this.elementData;
+ if (offset + i >= elementData.length)
+ throw new ConcurrentModificationException();
+ cursor = i + 1;
+ return (E) elementData[offset + (lastRet = i)];
+ }
+
+ public boolean hasPrevious() {
+ return cursor != 0;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E previous() {
+ checkForComodification();
+ int i = cursor - 1;
+ if (i < 0)
+ throw new NoSuchElementException();
+ Object[] elementData = ArrayList.this.elementData;
+ if (offset + i >= elementData.length)
+ throw new ConcurrentModificationException();
+ cursor = i;
+ return (E) elementData[offset + (lastRet = i)];
+ }
+
+ public int nextIndex() {
+ return cursor;
+ }
+
+ public int previousIndex() {
+ return cursor - 1;
+ }
+
+ public void remove() {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
+ try {
+ SubList.this.remove(lastRet);
+ cursor = lastRet;
+ lastRet = -1;
+ expectedModCount = ArrayList.this.modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ public void set(E e) {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
+ try {
+ ArrayList.this.set(offset + lastRet, e);
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ public void add(E e) {
+ checkForComodification();
+
+ try {
+ int i = cursor;
+ SubList.this.add(i, e);
+ cursor = i + 1;
+ lastRet = -1;
+ expectedModCount = ArrayList.this.modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ final void checkForComodification() {
+ if (expectedModCount != ArrayList.this.modCount)
+ throw new ConcurrentModificationException();
+ }
+ };
+ }
+
+ public List subList(int fromIndex, int toIndex) {
+ subListRangeCheck(fromIndex, toIndex, size);
+ return new SubList(this, offset, fromIndex, toIndex);
+ }
+
+ private void rangeCheck(int index) {
+ if (index < 0 || index >= this.size)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ private void rangeCheckForAdd(int index) {
+ if (index < 0 || index > this.size)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ private String outOfBoundsMsg(int index) {
+ return "Index: "+index+", Size: "+this.size;
+ }
+
+ private void checkForComodification() {
+ if (ArrayList.this.modCount != this.modCount)
+ throw new ConcurrentModificationException();
+ }
+ }
+}
diff -r 8e546d108658 -r b42911b78a16 emul/compact/src/main/java/java/util/Arrays.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/emul/compact/src/main/java/java/util/Arrays.java Sun Jan 27 10:19:02 2013 +0100
@@ -0,0 +1,3671 @@
+/*
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.util;
+
+import java.lang.reflect.*;
+import org.apidesign.bck2brwsr.emul.lang.System;
+
+/**
+ * This class contains various methods for manipulating arrays (such as
+ * sorting and searching). This class also contains a static factory
+ * that allows arrays to be viewed as lists.
+ *
+ *
The methods in this class all throw a {@code NullPointerException},
+ * if the specified array reference is null, except where noted.
+ *
+ *
The documentation for the methods contained in this class includes
+ * briefs description of the implementations. Such descriptions should
+ * be regarded as implementation notes, rather than parts of the
+ * specification. Implementors should feel free to substitute other
+ * algorithms, so long as the specification itself is adhered to. (For
+ * example, the algorithm used by {@code sort(Object[])} does not have to be
+ * a MergeSort, but it does have to be stable.)
+ *
+ *
This class is a member of the
+ *
+ * Java Collections Framework.
+ *
+ * @author Josh Bloch
+ * @author Neal Gafter
+ * @author John Rose
+ * @since 1.2
+ */
+public class Arrays {
+
+ // Suppresses default constructor, ensuring non-instantiability.
+ private Arrays() {}
+
+ /*
+ * Sorting of primitive type arrays.
+ */
+
+ /**
+ * Sorts the specified array into ascending numerical order.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ */
+ public static void sort(int[] a) {
+ DualPivotQuicksort.sort(a);
+ }
+
+ /**
+ * Sorts the specified range of the array into ascending order. The range
+ * to be sorted extends from the index {@code fromIndex}, inclusive, to
+ * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+ * the range to be sorted is empty.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ * @param fromIndex the index of the first element, inclusive, to be sorted
+ * @param toIndex the index of the last element, exclusive, to be sorted
+ *
+ * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+ * @throws ArrayIndexOutOfBoundsException
+ * if {@code fromIndex < 0} or {@code toIndex > a.length}
+ */
+ public static void sort(int[] a, int fromIndex, int toIndex) {
+ rangeCheck(a.length, fromIndex, toIndex);
+ DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
+ }
+
+ /**
+ * Sorts the specified array into ascending numerical order.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ */
+ public static void sort(long[] a) {
+ DualPivotQuicksort.sort(a);
+ }
+
+ /**
+ * Sorts the specified range of the array into ascending order. The range
+ * to be sorted extends from the index {@code fromIndex}, inclusive, to
+ * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+ * the range to be sorted is empty.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ * @param fromIndex the index of the first element, inclusive, to be sorted
+ * @param toIndex the index of the last element, exclusive, to be sorted
+ *
+ * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+ * @throws ArrayIndexOutOfBoundsException
+ * if {@code fromIndex < 0} or {@code toIndex > a.length}
+ */
+ public static void sort(long[] a, int fromIndex, int toIndex) {
+ rangeCheck(a.length, fromIndex, toIndex);
+ DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
+ }
+
+ /**
+ * Sorts the specified array into ascending numerical order.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ */
+ public static void sort(short[] a) {
+ DualPivotQuicksort.sort(a);
+ }
+
+ /**
+ * Sorts the specified range of the array into ascending order. The range
+ * to be sorted extends from the index {@code fromIndex}, inclusive, to
+ * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+ * the range to be sorted is empty.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ * @param fromIndex the index of the first element, inclusive, to be sorted
+ * @param toIndex the index of the last element, exclusive, to be sorted
+ *
+ * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+ * @throws ArrayIndexOutOfBoundsException
+ * if {@code fromIndex < 0} or {@code toIndex > a.length}
+ */
+ public static void sort(short[] a, int fromIndex, int toIndex) {
+ rangeCheck(a.length, fromIndex, toIndex);
+ DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
+ }
+
+ /**
+ * Sorts the specified array into ascending numerical order.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ */
+ public static void sort(char[] a) {
+ DualPivotQuicksort.sort(a);
+ }
+
+ /**
+ * Sorts the specified range of the array into ascending order. The range
+ * to be sorted extends from the index {@code fromIndex}, inclusive, to
+ * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+ * the range to be sorted is empty.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ * @param fromIndex the index of the first element, inclusive, to be sorted
+ * @param toIndex the index of the last element, exclusive, to be sorted
+ *
+ * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+ * @throws ArrayIndexOutOfBoundsException
+ * if {@code fromIndex < 0} or {@code toIndex > a.length}
+ */
+ public static void sort(char[] a, int fromIndex, int toIndex) {
+ rangeCheck(a.length, fromIndex, toIndex);
+ DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
+ }
+
+ /**
+ * Sorts the specified array into ascending numerical order.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ */
+ public static void sort(byte[] a) {
+ DualPivotQuicksort.sort(a);
+ }
+
+ /**
+ * Sorts the specified range of the array into ascending order. The range
+ * to be sorted extends from the index {@code fromIndex}, inclusive, to
+ * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+ * the range to be sorted is empty.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ * @param fromIndex the index of the first element, inclusive, to be sorted
+ * @param toIndex the index of the last element, exclusive, to be sorted
+ *
+ * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+ * @throws ArrayIndexOutOfBoundsException
+ * if {@code fromIndex < 0} or {@code toIndex > a.length}
+ */
+ public static void sort(byte[] a, int fromIndex, int toIndex) {
+ rangeCheck(a.length, fromIndex, toIndex);
+ DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
+ }
+
+ /**
+ * Sorts the specified array into ascending numerical order.
+ *
+ *
The {@code <} relation does not provide a total order on all float
+ * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
+ * value compares neither less than, greater than, nor equal to any value,
+ * even itself. This method uses the total order imposed by the method
+ * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
+ * {@code 0.0f} and {@code Float.NaN} is considered greater than any
+ * other value and all {@code Float.NaN} values are considered equal.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ */
+ public static void sort(float[] a) {
+ DualPivotQuicksort.sort(a);
+ }
+
+ /**
+ * Sorts the specified range of the array into ascending order. The range
+ * to be sorted extends from the index {@code fromIndex}, inclusive, to
+ * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+ * the range to be sorted is empty.
+ *
+ *
The {@code <} relation does not provide a total order on all float
+ * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
+ * value compares neither less than, greater than, nor equal to any value,
+ * even itself. This method uses the total order imposed by the method
+ * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
+ * {@code 0.0f} and {@code Float.NaN} is considered greater than any
+ * other value and all {@code Float.NaN} values are considered equal.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ * @param fromIndex the index of the first element, inclusive, to be sorted
+ * @param toIndex the index of the last element, exclusive, to be sorted
+ *
+ * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+ * @throws ArrayIndexOutOfBoundsException
+ * if {@code fromIndex < 0} or {@code toIndex > a.length}
+ */
+ public static void sort(float[] a, int fromIndex, int toIndex) {
+ rangeCheck(a.length, fromIndex, toIndex);
+ DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
+ }
+
+ /**
+ * Sorts the specified array into ascending numerical order.
+ *
+ *
The {@code <} relation does not provide a total order on all double
+ * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
+ * value compares neither less than, greater than, nor equal to any value,
+ * even itself. This method uses the total order imposed by the method
+ * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
+ * {@code 0.0d} and {@code Double.NaN} is considered greater than any
+ * other value and all {@code Double.NaN} values are considered equal.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ */
+ public static void sort(double[] a) {
+ DualPivotQuicksort.sort(a);
+ }
+
+ /**
+ * Sorts the specified range of the array into ascending order. The range
+ * to be sorted extends from the index {@code fromIndex}, inclusive, to
+ * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+ * the range to be sorted is empty.
+ *
+ *
The {@code <} relation does not provide a total order on all double
+ * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
+ * value compares neither less than, greater than, nor equal to any value,
+ * even itself. This method uses the total order imposed by the method
+ * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
+ * {@code 0.0d} and {@code Double.NaN} is considered greater than any
+ * other value and all {@code Double.NaN} values are considered equal.
+ *
+ *
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
+ * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
+ * offers O(n log(n)) performance on many data sets that cause other
+ * quicksorts to degrade to quadratic performance, and is typically
+ * faster than traditional (one-pivot) Quicksort implementations.
+ *
+ * @param a the array to be sorted
+ * @param fromIndex the index of the first element, inclusive, to be sorted
+ * @param toIndex the index of the last element, exclusive, to be sorted
+ *
+ * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+ * @throws ArrayIndexOutOfBoundsException
+ * if {@code fromIndex < 0} or {@code toIndex > a.length}
+ */
+ public static void sort(double[] a, int fromIndex, int toIndex) {
+ rangeCheck(a.length, fromIndex, toIndex);
+ DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
+ }
+
+ /*
+ * Sorting of complex type arrays.
+ */
+
+ /**
+ * Old merge sort implementation can be selected (for
+ * compatibility with broken comparators) using a system property.
+ * Cannot be a static boolean in the enclosing class due to
+ * circular dependencies. To be removed in a future release.
+ */
+ static final class LegacyMergeSort {
+ private static final boolean userRequested = false;
+ }
+
+ /*
+ * If this platform has an optimizing VM, check whether ComparableTimSort
+ * offers any performance benefit over TimSort in conjunction with a
+ * comparator that returns:
+ * {@code ((Comparable)first).compareTo(Second)}.
+ * If not, you are better off deleting ComparableTimSort to
+ * eliminate the code duplication. In other words, the commented
+ * out code below is the preferable implementation for sorting
+ * arrays of Comparables if it offers sufficient performance.
+ */
+
+// /**
+// * A comparator that implements the natural ordering of a group of
+// * mutually comparable elements. Using this comparator saves us
+// * from duplicating most of the code in this file (one version for
+// * Comparables, one for explicit Comparators).
+// */
+// private static final Comparator