2 var whiteSpaceRe = /^\s*|\s*$/g,
3 undefined, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1';
6 majorVersion : '@@tinymce_major_version@@',
8 minorVersion : '@@tinymce_minor_version@@',
10 releaseDate : '@@tinymce_release_date@@',
13 var t = this, d = document, na = navigator, ua = na.userAgent, i, nl, n, base, p, v;
15 t.isOpera = win.opera && opera.buildNumber;
17 t.isWebKit = /WebKit/.test(ua);
19 t.isIE = !t.isWebKit && !t.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(na.appName);
21 t.isIE6 = t.isIE && /MSIE [56]/.test(ua);
23 t.isGecko = !t.isWebKit && /Gecko/.test(ua);
25 t.isMac = ua.indexOf('Mac') != -1;
27 t.isAir = /adobeair/i.test(ua);
29 t.isIDevice = /(iPad|iPhone)/.test(ua);
31 // TinyMCE .NET webcontrol might be setting the values for TinyMCE
32 if (win.tinyMCEPreInit) {
33 t.suffix = tinyMCEPreInit.suffix;
34 t.baseURL = tinyMCEPreInit.base;
35 t.query = tinyMCEPreInit.query;
39 // Get suffix and base
42 // If base element found, add that infront of baseURL
43 nl = d.getElementsByTagName('base');
44 for (i=0; i<nl.length; i++) {
46 // Host only value like http://site.com or http://site.com:8008
47 if (/^https?:\/\/[^\/]+$/.test(v))
50 base = v ? v.match(/.*\//)[0] : ''; // Get only directory
55 if (n.src && /tiny_mce(|_gzip|_jquery|_prototype|_full)(_dev|_src)?.js/.test(n.src)) {
56 if (/_(src|dev)\.js/g.test(n.src))
59 if ((p = n.src.indexOf('?')) != -1)
60 t.query = n.src.substring(p + 1);
62 t.baseURL = n.src.substring(0, n.src.lastIndexOf('/'));
64 // If path to script is relative and a base href was found add that one infront
65 // the src property will always be an absolute one on non IE browsers and IE 8
66 // so this logic will basically only be executed on older IE versions
67 if (base && t.baseURL.indexOf('://') == -1 && t.baseURL.indexOf('/') !== 0)
68 t.baseURL = base + t.baseURL;
77 nl = d.getElementsByTagName('script');
78 for (i=0; i<nl.length; i++) {
84 n = d.getElementsByTagName('head')[0];
86 nl = n.getElementsByTagName('script');
87 for (i=0; i<nl.length; i++) {
98 return o !== undefined;
100 if (t == 'array' && (o.hasOwnProperty && o instanceof Array))
103 return typeof(o) == t;
106 makeMap : function(items, delim, map) {
110 delim = delim || ',';
112 if (typeof(items) == "string")
113 items = items.split(delim);
124 each : function(o, cb, s) {
132 if (o.length !== undefined) {
133 // Indexed arrays, needed for Safari
134 for (n=0, l = o.length; n < l; n++) {
135 if (cb.call(s, o[n], n, o) === false)
141 if (o.hasOwnProperty(n)) {
142 if (cb.call(s, o[n], n, o) === false)
152 map : function(a, f) {
155 tinymce.each(a, function(v) {
162 grep : function(a, f) {
165 tinymce.each(a, function(v) {
173 inArray : function(a, v) {
177 for (i = 0, l = a.length; i < l; i++) {
186 extend : function(o, e) {
187 var i, l, a = arguments;
189 for (i = 1, l = a.length; i < l; i++) {
192 tinymce.each(e, function(v, n) {
203 return (s ? '' + s : '').replace(whiteSpaceRe, '');
206 create : function(s, p, root) {
207 var t = this, sp, ns, cn, scn, c, de = 0;
209 // Parse : <prefix> <class>:<super class>
210 s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
211 cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name
213 // Create namespace for new class
214 ns = t.createNS(s[3].replace(/\.\w+$/, ''), root);
216 // Class already exists
220 // Make pure static class
221 if (s[2] == 'static') {
225 this.onCreate(s[2], s[3], ns[cn]);
230 // Create default constructor
232 p[cn] = function() {};
236 // Add constructor and methods
238 t.extend(ns[cn].prototype, p);
242 sp = t.resolve(s[5]).prototype;
243 scn = s[5].match(/\.(\w+)$/i)[1]; // Class name
245 // Extend constructor
248 // Add passthrough constructor
249 ns[cn] = function() {
250 return sp[scn].apply(this, arguments);
253 // Add inherit constructor
254 ns[cn] = function() {
255 this.parent = sp[scn];
256 return c.apply(this, arguments);
259 ns[cn].prototype[cn] = ns[cn];
262 t.each(sp, function(f, n) {
263 ns[cn].prototype[n] = sp[n];
266 // Add overridden methods
267 t.each(p, function(f, n) {
268 // Extend methods if needed
270 ns[cn].prototype[n] = function() {
272 return f.apply(this, arguments);
276 ns[cn].prototype[n] = f;
281 // Add static methods
282 t.each(p['static'], function(f, n) {
287 this.onCreate(s[2], s[3], ns[cn].prototype);
290 walk : function(o, f, n, s) {
297 tinymce.each(o, function(o, i) {
298 if (f.call(s, o, i, n) === false)
301 tinymce.walk(o, f, n, s);
306 createNS : function(n, o) {
312 for (i=0; i<n.length; i++) {
324 resolve : function(n, o) {
330 for (i = 0, l = n.length; i < l; i++) {
340 addUnload : function(f, s) {
343 f = {func : f, scope : s || this};
347 var li = t.unloads, o, n;
350 // Call unload handlers
355 o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy
358 // Detach unload function
359 if (win.detachEvent) {
360 win.detachEvent('onbeforeunload', fakeUnload);
361 win.detachEvent('onunload', unload);
362 } else if (win.removeEventListener)
363 win.removeEventListener('unload', unload, false);
365 // Destroy references
366 t.unloads = o = li = w = unload = 0;
368 // Run garbarge collector on IE
369 if (win.CollectGarbage)
374 function fakeUnload() {
377 // Is there things still loading, then do some magic
378 if (d.readyState == 'interactive') {
380 // Prevent memory leak
381 d.detachEvent('onstop', stop);
383 // Call unload handler
390 // Fire unload when the currently loading page is stopped
392 d.attachEvent('onstop', stop);
394 // Remove onstop listener after a while to prevent the unload function
395 // to execute if the user presses cancel in an onbeforeunload
396 // confirm dialog and then presses the browser stop button
397 win.setTimeout(function() {
399 d.detachEvent('onstop', stop);
404 // Attach unload handler
405 if (win.attachEvent) {
406 win.attachEvent('onunload', unload);
407 win.attachEvent('onbeforeunload', fakeUnload);
408 } else if (win.addEventListener)
409 win.addEventListener('unload', unload, false);
411 // Setup initial unload handler array
419 removeUnload : function(f) {
420 var u = this.unloads, r = null;
422 tinymce.each(u, function(o, i) {
423 if (o && o.func == f) {
433 explode : function(s, d) {
434 return s ? tinymce.map(s.split(d || ','), tinymce.trim) : s;
437 _addVer : function(u) {
443 v = (u.indexOf('?') == -1 ? '?' : '&') + this.query;
445 if (u.indexOf('#') == -1)
448 return u.replace('#', v + '#');
451 // Fix function for IE 9 where regexps isn't working correctly
452 // Todo: remove me once MS fixes the bug
453 _replace : function(find, replace, str) {
454 // On IE9 we have to fake $x replacement
455 if (isRegExpBroken) {
456 return str.replace(find, function() {
457 var val = replace, args = arguments, i;
459 for (i = 0; i < args.length - 2; i++) {
460 if (args[i] === undefined) {
461 val = val.replace(new RegExp('\\$' + i, 'g'), '');
463 val = val.replace(new RegExp('\\$' + i, 'g'), args[i]);
471 return str.replace(find, replace);
476 // Initialize the API
479 // Expose tinymce namespace to the global namespace (window)
480 win.tinymce = win.tinyMCE = tinymce;
482 // Describe the different namespaces
485 tinymce.create('tinymce.util.Dispatcher', {
489 Dispatcher : function(s) {
490 this.scope = s || this;
494 add : function(cb, s) {
495 this.listeners.push({cb : cb, scope : s || this.scope});
500 addToTop : function(cb, s) {
501 this.listeners.unshift({cb : cb, scope : s || this.scope});
506 remove : function(cb) {
507 var l = this.listeners, o = null;
509 tinymce.each(l, function(c, i) {
520 dispatch : function() {
521 var s, a = arguments, i, li = this.listeners, c;
523 // Needs to be a real loop since the listener count might change while looping
524 // And this is also more efficient
525 for (i = 0; i<li.length; i++) {
527 s = c.cb.apply(c.scope, a);
538 var each = tinymce.each;
540 tinymce.create('tinymce.util.URI', {
541 URI : function(u, s) {
542 var t = this, o, a, b;
548 s = t.settings = s || {};
550 // Strange app protocol or local anchor
551 if (/^(mailto|tel|news|javascript|about|data):/i.test(u) || /^\s*#/.test(u)) {
556 // Absolute path with no host, fake host and protocol
557 if (u.indexOf('/') === 0 && u.indexOf('//') !== 0)
558 u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u;
560 // Relative path http:// or protocol relative //path
561 if (!/^\w*:?\/\//.test(u))
562 u = (s.base_uri.protocol || 'http') + '://mce_host' + t.toAbsPath(s.base_uri.path, u);
564 // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)
565 u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something
566 u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u);
567 each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {
570 // Zope 3 workaround, they use @@something
572 s = s.replace(/\(mce_at\)/g, '@@');
577 if (b = s.base_uri) {
579 t.protocol = b.protocol;
582 t.userInfo = b.userInfo;
584 if (!t.port && t.host == 'mce_host')
587 if (!t.host || t.host == 'mce_host')
593 //t.path = t.path || '/';
596 setPath : function(p) {
599 p = /^(.*?)\/?(\w+)?$/.exec(p);
611 toRelative : function(u) {
617 u = new tinymce.util.URI(u, {base_uri : t});
619 // Not on same domain/port or protocol
620 if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol)
623 o = t.toRelPath(t.path, u.path);
636 toAbsolute : function(u, nh) {
637 var u = new tinymce.util.URI(u, {base_uri : this});
639 return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0);
642 toRelPath : function(base, path) {
643 var items, bp = 0, out = '', i, l;
646 base = base.substring(0, base.lastIndexOf('/'));
647 base = base.split('/');
648 items = path.split('/');
650 if (base.length >= items.length) {
651 for (i = 0, l = base.length; i < l; i++) {
652 if (i >= items.length || base[i] != items[i]) {
659 if (base.length < items.length) {
660 for (i = 0, l = items.length; i < l; i++) {
661 if (i >= base.length || base[i] != items[i]) {
671 for (i = 0, l = base.length - (bp - 1); i < l; i++)
674 for (i = bp - 1, l = items.length; i < l; i++) {
676 out += "/" + items[i];
684 toAbsPath : function(base, path) {
685 var i, nb = 0, o = [], tr, outPath;
688 tr = /\/$/.test(path) ? '/' : '';
689 base = base.split('/');
690 path = path.split('/');
692 // Remove empty chunks
693 each(base, function(k) {
700 // Merge relURLParts chunks
701 for (i = path.length - 1, o = []; i >= 0; i--) {
703 if (path[i].length == 0 || path[i] == ".")
707 if (path[i] == '..') {
721 i = base.length - nb;
725 outPath = o.reverse().join('/');
727 outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');
729 // Add front / if it's needed
730 if (outPath.indexOf('/') !== 0)
731 outPath = '/' + outPath;
733 // Add traling / if it's needed
734 if (tr && outPath.lastIndexOf('/') !== outPath.length - 1)
740 getURI : function(nh) {
744 if (!t.source || nh) {
749 s += t.protocol + '://';
752 s += t.userInfo + '@';
778 var each = tinymce.each;
780 tinymce.create('static tinymce.util.Cookie', {
781 getHash : function(n) {
782 var v = this.get(n), h;
785 each(v.split('&'), function(v) {
788 h[unescape(v[0])] = unescape(v[1]);
795 setHash : function(n, v, e, p, d, s) {
798 each(v, function(v, k) {
799 o += (!o ? '' : '&') + escape(k) + '=' + escape(v);
802 this.set(n, o, e, p, d, s);
806 var c = document.cookie, e, p = n + "=", b;
812 b = c.indexOf("; " + p);
822 e = c.indexOf(";", b);
827 return unescape(c.substring(b + p.length, e));
830 set : function(n, v, e, p, d, s) {
831 document.cookie = n + "=" + escape(v) +
832 ((e) ? "; expires=" + e.toGMTString() : "") +
833 ((p) ? "; path=" + escape(p) : "") +
834 ((d) ? "; domain=" + d : "") +
835 ((s) ? "; secure" : "");
838 remove : function(n, p) {
841 d.setTime(d.getTime() - 1000);
843 this.set(n, '', d, p, d);
848 function serialize(o, quote) {
851 quote = quote || '"';
859 v = '\bb\tt\nn\ff\rr\""\'\'\\\\';
861 return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function(a, b) {
862 // Make sure single quotes never get encoded inside double quotes for JSON compatibility
863 if (quote === '"' && a === "'")
869 return '\\' + v.charAt(i + 1);
871 a = b.charCodeAt().toString(16);
873 return '\\u' + '0000'.substring(a.length) + a;
878 if (o.hasOwnProperty && o instanceof Array) {
879 for (i=0, v = '['; i<o.length; i++)
880 v += (i > 0 ? ',' : '') + serialize(o[i], quote);
888 v += typeof o[i] != 'function' ? (v.length > 1 ? ',' + quote : quote) + i + quote +':' + serialize(o[i], quote) : '';
896 tinymce.util.JSON = {
897 serialize: serialize,
901 return eval('(' + s + ')');
909 tinymce.create('static tinymce.util.XHR', {
911 var x, t, w = window, c = 0;
914 o.scope = o.scope || this;
915 o.success_scope = o.success_scope || o.scope;
916 o.error_scope = o.error_scope || o.scope;
917 o.async = o.async === false ? false : true;
918 o.data = o.data || '';
924 x = new ActiveXObject(s);
931 x = w.XMLHttpRequest ? new XMLHttpRequest() : get('Microsoft.XMLHTTP') || get('Msxml2.XMLHTTP');
934 if (x.overrideMimeType)
935 x.overrideMimeType(o.content_type);
937 x.open(o.type || (o.data ? 'POST' : 'GET'), o.url, o.async);
940 x.setRequestHeader('Content-Type', o.content_type);
942 x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
947 if (!o.async || x.readyState == 4 || c++ > 10000) {
948 if (o.success && c < 10000 && x.status == 200)
949 o.success.call(o.success_scope, '' + x.responseText, x, o);
951 o.error.call(o.error_scope, c > 10000 ? 'TIMED_OUT' : 'GENERAL', x, o);
955 w.setTimeout(ready, 10);
958 // Syncronous request
962 // Wait for response, onReadyStateChange can not be used since it leaks memory in IE
963 t = w.setTimeout(ready, 10);
968 var extend = tinymce.extend, JSON = tinymce.util.JSON, XHR = tinymce.util.XHR;
970 tinymce.create('tinymce.util.JSONRequest', {
971 JSONRequest : function(s) {
972 this.settings = extend({
978 var ecb = o.error, scb = o.success;
980 o = extend(this.settings, o);
982 o.success = function(c, x) {
985 if (typeof(c) == 'undefined') {
987 error : 'JSON Parse error.'
992 ecb.call(o.error_scope || o.scope, c.error, x);
994 scb.call(o.success_scope || o.scope, c.result);
997 o.error = function(ty, x) {
999 ecb.call(o.error_scope || o.scope, ty, x);
1002 o.data = JSON.serialize({
1003 id : o.id || 'c' + (this.count++),
1008 // JSON content type for Ruby on rails. Bug: #1883287
1009 o.content_type = 'application/json';
1015 sendRPC : function(o) {
1016 return new tinymce.util.JSONRequest().send(o);
1021 (function(tinymce) {
1022 var namedEntities, baseEntities, reverseEntities,
1023 attrsCharsRegExp = /[&\"\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
1024 textCharsRegExp = /[<>&\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
1025 rawCharsRegExp = /[<>&\"\']/g,
1026 entityRegExp = /&(#)?([\w]+);/g,
1028 128 : "\u20AC", 130 : "\u201A", 131 : "\u0192", 132 : "\u201E", 133 : "\u2026", 134 : "\u2020",
1029 135 : "\u2021", 136 : "\u02C6", 137 : "\u2030", 138 : "\u0160", 139 : "\u2039", 140 : "\u0152",
1030 142 : "\u017D", 145 : "\u2018", 146 : "\u2019", 147 : "\u201C", 148 : "\u201D", 149 : "\u2022",
1031 150 : "\u2013", 151 : "\u2014", 152 : "\u02DC", 153 : "\u2122", 154 : "\u0161", 155 : "\u203A",
1032 156 : "\u0153", 158 : "\u017E", 159 : "\u0178"
1044 // Reverse lookup table for raw entities
1053 // Decodes text by using the browser
1054 function nativeDecode(text) {
1057 elm = document.createElement("div");
1058 elm.innerHTML = text;
1060 return elm.textContent || elm.innerText || text;
1063 // Build a two way lookup table for the entities
1064 function buildEntitiesLookup(items, radix) {
1065 var i, chr, entity, lookup = {};
1068 items = items.split(',');
1069 radix = radix || 10;
1071 // Build entities lookup table
1072 for (i = 0; i < items.length; i += 2) {
1073 chr = String.fromCharCode(parseInt(items[i], radix));
1075 // Only add non base entities
1076 if (!baseEntities[chr]) {
1077 entity = '&' + items[i + 1] + ';';
1078 lookup[chr] = entity;
1079 lookup[entity] = chr;
1087 // Unpack entities lookup where the numbers are in radix 32 to reduce the size
1088 namedEntities = buildEntitiesLookup(
1089 '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' +
1090 '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' +
1091 '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' +
1092 '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' +
1093 '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' +
1094 '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' +
1095 '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' +
1096 '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' +
1097 '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' +
1098 '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' +
1099 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' +
1100 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' +
1101 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' +
1102 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' +
1103 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' +
1104 '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' +
1105 '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' +
1106 '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' +
1107 '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' +
1108 '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' +
1109 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' +
1110 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' +
1111 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' +
1112 '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' +
1113 '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro'
1116 tinymce.html = tinymce.html || {};
1118 tinymce.html.Entities = {
1119 encodeRaw : function(text, attr) {
1120 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1121 return baseEntities[chr] || chr;
1125 encodeAllRaw : function(text) {
1126 return ('' + text).replace(rawCharsRegExp, function(chr) {
1127 return baseEntities[chr] || chr;
1131 encodeNumeric : function(text, attr) {
1132 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1133 // Multi byte sequence convert it to a single entity
1135 return '&#' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';';
1137 return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
1141 encodeNamed : function(text, attr, entities) {
1142 entities = entities || namedEntities;
1144 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1145 return baseEntities[chr] || entities[chr] || chr;
1149 getEncodeFunc : function(name, entities) {
1150 var Entities = tinymce.html.Entities;
1152 entities = buildEntitiesLookup(entities) || namedEntities;
1154 function encodeNamedAndNumeric(text, attr) {
1155 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1156 return baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
1160 function encodeCustomNamed(text, attr) {
1161 return Entities.encodeNamed(text, attr, entities);
1164 // Replace + with , to be compatible with previous TinyMCE versions
1165 name = tinymce.makeMap(name.replace(/\+/g, ','));
1167 // Named and numeric encoder
1168 if (name.named && name.numeric)
1169 return encodeNamedAndNumeric;
1175 return encodeCustomNamed;
1177 return Entities.encodeNamed;
1182 return Entities.encodeNumeric;
1185 return Entities.encodeRaw;
1188 decode : function(text) {
1189 return text.replace(entityRegExp, function(all, numeric, value) {
1191 value = parseInt(value);
1193 // Support upper UTF
1194 if (value > 0xFFFF) {
1197 return String.fromCharCode(0xD800 + (value >> 10), 0xDC00 + (value & 0x3FF));
1199 return asciiMap[value] || String.fromCharCode(value);
1202 return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
1207 tinymce.html.Styles = function(settings, schema) {
1208 var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,
1209 urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,
1210 styleRegExp = /\s*([^:]+):\s*([^;]+);?/g,
1211 trimRightRegExp = /\s+$/,
1212 urlColorRegExp = /rgb/,
1213 undef, i, encodingLookup = {}, encodingItems;
1215 settings = settings || {};
1217 encodingItems = '\\" \\\' \\; \\: ; : _'.split(' ');
1218 for (i = 0; i < encodingItems.length; i++) {
1219 encodingLookup[encodingItems[i]] = '_' + i;
1220 encodingLookup['_' + i] = encodingItems[i];
1223 function toHex(match, r, g, b) {
1225 val = parseInt(val).toString(16);
1227 return val.length > 1 ? val : '0' + val; // 0 -> 00
1230 return '#' + hex(r) + hex(g) + hex(b);
1234 toHex : function(color) {
1235 return color.replace(rgbRegExp, toHex);
1238 parse : function(css) {
1239 var styles = {}, matches, name, value, isEncoded, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || this;
1241 function compress(prefix, suffix) {
1242 var top, right, bottom, left;
1244 // Get values and check it it needs compressing
1245 top = styles[prefix + '-top' + suffix];
1249 right = styles[prefix + '-right' + suffix];
1253 bottom = styles[prefix + '-bottom' + suffix];
1254 if (right != bottom)
1257 left = styles[prefix + '-left' + suffix];
1262 styles[prefix + suffix] = left;
1263 delete styles[prefix + '-top' + suffix];
1264 delete styles[prefix + '-right' + suffix];
1265 delete styles[prefix + '-bottom' + suffix];
1266 delete styles[prefix + '-left' + suffix];
1269 function canCompress(key) {
1270 var value = styles[key], i;
1272 if (!value || value.indexOf(' ') < 0)
1275 value = value.split(' ');
1278 if (value[i] !== value[0])
1282 styles[key] = value[0];
1287 function compress2(target, a, b, c) {
1288 if (!canCompress(a))
1291 if (!canCompress(b))
1294 if (!canCompress(c))
1298 styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
1304 // Encodes the specified string by replacing all \" \' ; : with _<num>
1305 function encode(str) {
1308 return encodingLookup[str];
1311 // Decodes the specified string by replacing all _<num> with it's original value \" \' etc
1312 // It will also decode the \" \' if keep_slashes is set to fale or omitted
1313 function decode(str, keep_slashes) {
1315 str = str.replace(/_[0-9]/g, function(str) {
1316 return encodingLookup[str];
1321 str = str.replace(/\\([\'\";:])/g, "$1");
1327 // Encode \" \' % and ; and : inside strings so they don't interfere with the style parsing
1328 css = css.replace(/\\[\"\';:_]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {
1329 return str.replace(/[;:]/g, encode);
1333 while (matches = styleRegExp.exec(css)) {
1334 name = matches[1].replace(trimRightRegExp, '').toLowerCase();
1335 value = matches[2].replace(trimRightRegExp, '');
1337 if (name && value.length > 0) {
1338 // Opera will produce 700 instead of bold in their style values
1339 if (name === 'font-weight' && value === '700')
1341 else if (name === 'color' || name === 'background-color') // Lowercase colors like RED
1342 value = value.toLowerCase();
1344 // Convert RGB colors to HEX
1345 value = value.replace(rgbRegExp, toHex);
1347 // Convert URLs and force them into url('value') format
1348 value = value.replace(urlOrStrRegExp, function(match, url, url2, url3, str, str2) {
1354 // Force strings into single quote format
1355 return "'" + str.replace(/\'/g, "\\'") + "'";
1358 url = decode(url || url2 || url3);
1360 // Convert the URL to relative/absolute depending on config
1362 url = urlConverter.call(urlConverterScope, url, 'style');
1364 // Output new URL format
1365 return "url('" + url.replace(/\'/g, "\\'") + "')";
1368 styles[name] = isEncoded ? decode(value, true) : value;
1371 styleRegExp.lastIndex = matches.index + matches[0].length;
1374 // Compress the styles to reduce it's size for example IE will expand styles
1375 compress("border", "");
1376 compress("border", "-width");
1377 compress("border", "-color");
1378 compress("border", "-style");
1379 compress("padding", "");
1380 compress("margin", "");
1381 compress2('border', 'border-width', 'border-style', 'border-color');
1383 // Remove pointless border, IE produces these
1384 if (styles.border === 'medium none')
1385 delete styles.border;
1391 serialize : function(styles, element_name) {
1392 var css = '', name, value;
1394 function serializeStyles(name) {
1395 var styleList, i, l, name, value;
1397 styleList = schema.styles[name];
1399 for (i = 0, l = styleList.length; i < l; i++) {
1400 name = styleList[i];
1401 value = styles[name];
1403 if (value !== undef && value.length > 0)
1404 css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
1409 // Serialize styles according to schema
1410 if (element_name && schema && schema.styles) {
1411 // Serialize global styles and element specific styles
1412 serializeStyles('*');
1413 serializeStyles(name);
1415 // Output the styles in the order they are inside the object
1416 for (name in styles) {
1417 value = styles[name];
1419 if (value !== undef && value.length > 0)
1420 css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
1428 (function(tinymce) {
1429 var transitional = {}, boolAttrMap, blockElementsMap, shortEndedElementsMap, nonEmptyElementsMap,
1430 whiteSpaceElementsMap, selfClosingElementsMap, makeMap = tinymce.makeMap, each = tinymce.each;
1432 function split(str, delim) {
1433 return str.split(delim || ',');
1436 function unpack(lookup, data) {
1437 var key, elements = {};
1439 function replace(value) {
1440 return value.replace(/[A-Z]+/g, function(key) {
1441 return replace(lookup[key]);
1446 for (key in lookup) {
1447 if (lookup.hasOwnProperty(key))
1448 lookup[key] = replace(lookup[key]);
1451 // Unpack and parse data into object map
1452 replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) {
1453 attributes = split(attributes, '|');
1456 attributes : makeMap(attributes),
1457 attributesOrder : attributes,
1458 children : makeMap(children, '|', {'#comment' : {}})
1465 // Build a lookup table for block elements both lowercase and uppercase
1466 blockElementsMap = 'h1,h2,h3,h4,h5,h6,hr,p,div,address,pre,form,table,tbody,thead,tfoot,' +
1467 'th,tr,td,li,ol,ul,caption,blockquote,center,dl,dt,dd,dir,fieldset,' +
1468 'noscript,menu,isindex,samp,header,footer,article,section,hgroup';
1469 blockElementsMap = makeMap(blockElementsMap, ',', makeMap(blockElementsMap.toUpperCase()));
1471 // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size
1472 transitional = unpack({
1475 ZG : 'E|span|width|align|char|charoff|valign',
1476 X : 'p|T|div|U|W|isindex|fieldset|table',
1477 ZF : 'E|align|char|charoff|valign',
1478 W : 'pre|hr|blockquote|address|center|noframes',
1479 ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height',
1481 U : 'ul|ol|dl|menu|dir',
1482 ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q',
1483 T : 'h1|h2|h3|h4|h5|h6',
1489 P : 'ins|del|script',
1490 O : 'input|select|textarea|label|button',
1492 M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym',
1495 J : 'tt|i|b|u|s|strike',
1496 I : 'big|small|font|basefont',
1499 F : 'object|applet|img|map|iframe',
1501 D : 'accesskey|tabindex|onfocus|onblur',
1502 C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup',
1503 B : 'lang|xml:lang|dir',
1504 A : 'id|class|style|title'
1505 }, 'script[id|charset|type|language|src|defer|xml:space][]' +
1506 'style[B|id|type|media|title|xml:space][]' +
1507 'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' +
1508 'param[id|name|value|valuetype|type][]' +
1510 'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' +
1514 'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' +
1515 'h1[E|align][#|S]' +
1516 'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' +
1517 'map[B|C|A|name][X|form|Q|area]' +
1518 'h2[E|align][#|S]' +
1519 'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' +
1520 'h3[E|align][#|S]' +
1529 'font[A|B|size|color|face][#|S]' +
1530 'basefont[id|size|color|face][]' +
1544 'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' +
1545 'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' +
1546 'optgroup[E|disabled|label][option]' +
1547 'option[E|selected|disabled|label|value][]' +
1548 'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' +
1549 'label[E|for|accesskey|onfocus|onblur][#|S]' +
1550 'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' +
1551 'h4[E|align][#|S]' +
1552 'ins[E|cite|datetime][#|Y]' +
1553 'h5[E|align][#|S]' +
1554 'del[E|cite|datetime][#|Y]' +
1555 'h6[E|align][#|S]' +
1556 'div[E|align][#|Y]' +
1557 'ul[E|type|compact][li]' +
1558 'li[E|type|value][#|Y]' +
1559 'ol[E|type|compact|start][li]' +
1560 'dl[E|compact][dt|dd]' +
1563 'menu[E|compact][li]' +
1564 'dir[E|compact][li]' +
1565 'pre[E|width|xml:space][#|ZA]' +
1566 'hr[E|align|noshade|size|width][]' +
1567 'blockquote[E|cite][#|Y]' +
1568 'address[E][#|S|p]' +
1570 'noframes[E][#|Y]' +
1571 'isindex[A|B|prompt][]' +
1572 'fieldset[E][#|legend|Y]' +
1573 'legend[E|accesskey|align][#|S]' +
1574 'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' +
1575 'caption[E|align][#|S]' +
1577 'colgroup[ZG][col]' +
1579 'tr[ZF|bgcolor][th|td]' +
1581 'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' +
1582 'noscript[E][#|Y]' +
1586 'area[E|D|shape|coords|href|nohref|alt|target][]' +
1587 'base[id|href|target][]' +
1588 'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]'
1591 boolAttrMap = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected,preload,autoplay,loop,controls');
1592 shortEndedElementsMap = makeMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed,source');
1593 nonEmptyElementsMap = tinymce.extend(makeMap('td,th,iframe,video,object'), shortEndedElementsMap);
1594 whiteSpaceElementsMap = makeMap('pre,script,style');
1595 selfClosingElementsMap = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');
1597 tinymce.html.Schema = function(settings) {
1598 var self = this, elements = {}, children = {}, patternElements = [], validStyles;
1600 settings = settings || {};
1602 // Allow all elements and attributes if verify_html is set to false
1603 if (settings.verify_html === false)
1604 settings.valid_elements = '*[*]';
1606 // Build styles list
1607 if (settings.valid_styles) {
1610 // Convert styles into a rule list
1611 each(settings.valid_styles, function(value, key) {
1612 validStyles[key] = tinymce.explode(value);
1616 // Converts a wildcard expression string to a regexp for example *a will become /.*a/.
1617 function patternToRegExp(str) {
1618 return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
1621 // Parses the specified valid_elements string and adds to the current rules
1622 // This function is a bit hard to read since it's heavily optimized for speed
1623 function addValidElements(valid_elements) {
1624 var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder,
1625 prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value,
1626 elementRuleRegExp = /^([#+-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/,
1627 attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,
1628 hasPatternsRegExp = /[*?+]/;
1630 if (valid_elements) {
1631 // Split valid elements into an array with rules
1632 valid_elements = split(valid_elements);
1634 if (elements['@']) {
1635 globalAttributes = elements['@'].attributes;
1636 globalAttributesOrder = elements['@'].attributesOrder;
1640 for (ei = 0, el = valid_elements.length; ei < el; ei++) {
1641 // Parse element rule
1642 matches = elementRuleRegExp.exec(valid_elements[ei]);
1644 // Setup local names for matches
1645 prefix = matches[1];
1646 elementName = matches[2];
1647 outputName = matches[3];
1648 attrData = matches[4];
1650 // Create new attributes and attributesOrder
1652 attributesOrder = [];
1654 // Create the new element
1656 attributes : attributes,
1657 attributesOrder : attributesOrder
1660 // Padd empty elements prefix
1662 element.paddEmpty = true;
1664 // Remove empty elements prefix
1666 element.removeEmpty = true;
1668 // Copy attributes from global rule into current rule
1669 if (globalAttributes) {
1670 for (key in globalAttributes)
1671 attributes[key] = globalAttributes[key];
1673 attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
1676 // Attributes defined
1678 attrData = split(attrData, '|');
1679 for (ai = 0, al = attrData.length; ai < al; ai++) {
1680 matches = attrRuleRegExp.exec(attrData[ai]);
1683 attrType = matches[1];
1684 attrName = matches[2].replace(/::/g, ':');
1685 prefix = matches[3];
1689 if (attrType === '!') {
1690 element.attributesRequired = element.attributesRequired || [];
1691 element.attributesRequired.push(attrName);
1692 attr.required = true;
1695 // Denied from global
1696 if (attrType === '-') {
1697 delete attributes[attrName];
1698 attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1);
1705 if (prefix === '=') {
1706 element.attributesDefault = element.attributesDefault || [];
1707 element.attributesDefault.push({name: attrName, value: value});
1708 attr.defaultValue = value;
1712 if (prefix === ':') {
1713 element.attributesForced = element.attributesForced || [];
1714 element.attributesForced.push({name: attrName, value: value});
1715 attr.forcedValue = value;
1720 attr.validValues = makeMap(value, '?');
1723 // Check for attribute patterns
1724 if (hasPatternsRegExp.test(attrName)) {
1725 element.attributePatterns = element.attributePatterns || [];
1726 attr.pattern = patternToRegExp(attrName);
1727 element.attributePatterns.push(attr);
1729 // Add attribute to order list if it doesn't already exist
1730 if (!attributes[attrName])
1731 attributesOrder.push(attrName);
1733 attributes[attrName] = attr;
1739 // Global rule, store away these for later usage
1740 if (!globalAttributes && elementName == '@') {
1741 globalAttributes = attributes;
1742 globalAttributesOrder = attributesOrder;
1745 // Handle substitute elements such as b/strong
1747 element.outputName = elementName;
1748 elements[outputName] = element;
1751 // Add pattern or exact element
1752 if (hasPatternsRegExp.test(elementName)) {
1753 element.pattern = patternToRegExp(elementName);
1754 patternElements.push(element);
1756 elements[elementName] = element;
1762 function setValidElements(valid_elements) {
1764 patternElements = [];
1766 addValidElements(valid_elements);
1768 each(transitional, function(element, name) {
1769 children[name] = element.children;
1773 // Adds custom non HTML elements to the schema
1774 function addCustomElements(custom_elements) {
1775 var customElementRegExp = /^(~)?(.+)$/;
1777 if (custom_elements) {
1778 each(split(custom_elements), function(rule) {
1779 var matches = customElementRegExp.exec(rule),
1780 cloneName = matches[1] === '~' ? 'span' : 'div',
1783 children[name] = children[cloneName];
1785 // Add custom elements at span/div positions
1786 each(children, function(element, child) {
1787 if (element[cloneName])
1788 element[name] = element[cloneName];
1794 // Adds valid children to the schema object
1795 function addValidChildren(valid_children) {
1796 var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/;
1798 if (valid_children) {
1799 each(split(valid_children), function(rule) {
1800 var matches = childRuleRegExp.exec(rule), parent, prefix;
1803 prefix = matches[1];
1805 // Add/remove items from default
1807 parent = children[matches[2]];
1809 parent = children[matches[2]] = {'#comment' : {}};
1811 parent = children[matches[2]];
1813 each(split(matches[3], '|'), function(child) {
1815 delete parent[child];
1824 if (!settings.valid_elements) {
1825 // No valid elements defined then clone the elements from the transitional spec
1826 each(transitional, function(element, name) {
1828 attributes : element.attributes,
1829 attributesOrder : element.attributesOrder
1832 children[name] = element.children;
1836 each(split('strong/b,em/i'), function(item) {
1837 item = split(item, '/');
1838 elements[item[1]].outputName = item[0];
1841 // Add default alt attribute for images
1842 elements.img.attributesDefault = [{name: 'alt', value: ''}];
1844 // Remove these if they are empty by default
1845 each(split('ol,ul,li,sub,sup,blockquote,tr,div,span,font,a,table,tbody'), function(name) {
1846 elements[name].removeEmpty = true;
1849 // Padd these by default
1850 each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) {
1851 elements[name].paddEmpty = true;
1854 setValidElements(settings.valid_elements);
1856 addCustomElements(settings.custom_elements);
1857 addValidChildren(settings.valid_children);
1858 addValidElements(settings.extended_valid_elements);
1860 // Todo: Remove this when we fix list handling to be valid
1861 addValidChildren('+ol[ul|ol],+ul[ul|ol]');
1863 // Delete invalid elements
1864 if (settings.invalid_elements) {
1865 tinymce.each(tinymce.explode(settings.invalid_elements), function(item) {
1867 delete elements[item];
1871 self.children = children;
1873 self.styles = validStyles;
1875 self.getBoolAttrs = function() {
1879 self.getBlockElements = function() {
1880 return blockElementsMap;
1883 self.getShortEndedElements = function() {
1884 return shortEndedElementsMap;
1887 self.getSelfClosingElements = function() {
1888 return selfClosingElementsMap;
1891 self.getNonEmptyElements = function() {
1892 return nonEmptyElementsMap;
1895 self.getWhiteSpaceElements = function() {
1896 return whiteSpaceElementsMap;
1899 self.isValidChild = function(name, child) {
1900 var parent = children[name];
1902 return !!(parent && parent[child]);
1905 self.getElementRule = function(name) {
1906 var element = elements[name], i;
1908 // Exact match found
1912 // No exact match then try the patterns
1913 i = patternElements.length;
1915 element = patternElements[i];
1917 if (element.pattern.test(name))
1922 self.addValidElements = addValidElements;
1924 self.setValidElements = setValidElements;
1926 self.addCustomElements = addCustomElements;
1928 self.addValidChildren = addValidChildren;
1931 // Expose boolMap and blockElementMap as static properties for usage in DOMUtils
1932 tinymce.html.Schema.boolAttrMap = boolAttrMap;
1933 tinymce.html.Schema.blockElementsMap = blockElementsMap;
1935 (function(tinymce) {
1936 tinymce.html.SaxParser = function(settings, schema) {
1937 var self = this, noop = function() {};
1939 settings = settings || {};
1940 self.schema = schema = schema || new tinymce.html.Schema();
1942 if (settings.fix_self_closing !== false)
1943 settings.fix_self_closing = true;
1945 // Add handler functions from settings and setup default handlers
1946 tinymce.each('comment cdata text start end pi doctype'.split(' '), function(name) {
1948 self[name] = settings[name] || noop;
1951 self.parse = function(html) {
1952 var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name,
1953 shortEndedElements, fillAttrsMap, isShortEnded, validate, elementRule, isValidElement, attr, attribsValue,
1954 validAttributesMap, validAttributePatterns, attributesRequired, attributesDefault, attributesForced, selfClosing,
1955 tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0, decode = tinymce.html.Entities.decode, fixSelfClosing;
1957 function processEndTag(name) {
1960 // Find position of parent of the same type
1963 if (stack[pos].name === name)
1969 // Close all the open elements
1970 for (i = stack.length - 1; i >= pos; i--) {
1974 self.end(name.name);
1977 // Remove the open elements from the stack
1982 // Precompile RegExps and map objects
1983 tokenRegExp = new RegExp('<(?:' +
1984 '(?:!--([\\w\\W]*?)-->)|' + // Comment
1985 '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + // CDATA
1986 '(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE
1987 '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI
1988 '(?:\\/([^>]+)>)|' + // End element
1989 '(?:([^\\s\\/<>]+)\\s*((?:[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*)>)' + // Start element
1992 attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:\\.|[^\"])*)\")|(?:\'((?:\\.|[^\'])*)\')|([^>\s]+)))?/g;
1994 'script' : /<\/script[^>]*>/gi,
1995 'style' : /<\/style[^>]*>/gi,
1996 'noscript' : /<\/noscript[^>]*>/gi
1999 // Setup lookup tables for empty elements and boolean attributes
2000 shortEndedElements = schema.getShortEndedElements();
2001 selfClosing = schema.getSelfClosingElements();
2002 fillAttrsMap = schema.getBoolAttrs();
2003 validate = settings.validate;
2004 fixSelfClosing = settings.fix_self_closing;
2006 while (matches = tokenRegExp.exec(html)) {
2008 if (index < matches.index)
2009 self.text(decode(html.substr(index, matches.index - index)));
2011 if (value = matches[6]) { // End element
2012 processEndTag(value.toLowerCase());
2013 } else if (value = matches[7]) { // Start element
2014 value = value.toLowerCase();
2015 isShortEnded = value in shortEndedElements;
2017 // Is self closing tag for example an <li> after an open <li>
2018 if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value)
2019 processEndTag(value);
2022 if (!validate || (elementRule = schema.getElementRule(value))) {
2023 isValidElement = true;
2025 // Grab attributes map and patters when validation is enabled
2027 validAttributesMap = elementRule.attributes;
2028 validAttributePatterns = elementRule.attributePatterns;
2032 if (attribsValue = matches[8]) {
2036 attribsValue.replace(attrRegExp, function(match, name, value, val2, val3) {
2039 name = name.toLowerCase();
2040 value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute
2042 // Validate name and value
2043 if (validate && name.indexOf('data-') !== 0) {
2044 attrRule = validAttributesMap[name];
2046 // Find rule by pattern matching
2047 if (!attrRule && validAttributePatterns) {
2048 i = validAttributePatterns.length;
2050 attrRule = validAttributePatterns[i];
2051 if (attrRule.pattern.test(name))
2060 // No attribute rule found
2065 if (attrRule.validValues && !(value in attrRule.validValues))
2069 // Add attribute to list and map
2070 attrList.map[name] = value;
2081 // Process attributes if validation is enabled
2083 attributesRequired = elementRule.attributesRequired;
2084 attributesDefault = elementRule.attributesDefault;
2085 attributesForced = elementRule.attributesForced;
2087 // Handle forced attributes
2088 if (attributesForced) {
2089 i = attributesForced.length;
2091 attr = attributesForced[i];
2093 attrValue = attr.value;
2095 if (attrValue === '{$uid}')
2096 attrValue = 'mce_' + idCount++;
2098 attrList.map[name] = attrValue;
2099 attrList.push({name: name, value: attrValue});
2103 // Handle default attributes
2104 if (attributesDefault) {
2105 i = attributesDefault.length;
2107 attr = attributesDefault[i];
2110 if (!(name in attrList.map)) {
2111 attrValue = attr.value;
2113 if (attrValue === '{$uid}')
2114 attrValue = 'mce_' + idCount++;
2116 attrList.map[name] = attrValue;
2117 attrList.push({name: name, value: attrValue});
2122 // Handle required attributes
2123 if (attributesRequired) {
2124 i = attributesRequired.length;
2126 if (attributesRequired[i] in attrList.map)
2130 // None of the required attributes where found
2132 isValidElement = false;
2135 // Invalidate element if it's marked as bogus
2136 if (attrList.map['data-mce-bogus'])
2137 isValidElement = false;
2141 self.start(value, attrList, isShortEnded);
2143 isValidElement = false;
2145 // Treat script, noscript and style a bit different since they may include code that looks like elements
2146 if (endRegExp = specialElements[value]) {
2147 endRegExp.lastIndex = index = matches.index + matches[0].length;
2149 if (matches = endRegExp.exec(html)) {
2151 text = html.substr(index, matches.index - index);
2153 index = matches.index + matches[0].length;
2155 text = html.substr(index);
2156 index = html.length;
2159 if (isValidElement && text.length > 0)
2160 self.text(text, true);
2165 tokenRegExp.lastIndex = index;
2169 // Push value on to stack
2170 if (!isShortEnded) {
2171 if (!attribsValue || attribsValue.indexOf('/') != attribsValue.length - 1)
2172 stack.push({name: value, valid: isValidElement});
2173 else if (isValidElement)
2176 } else if (value = matches[1]) { // Comment
2177 self.comment(value);
2178 } else if (value = matches[2]) { // CDATA
2180 } else if (value = matches[3]) { // DOCTYPE
2181 self.doctype(value);
2182 } else if (value = matches[4]) { // PI
2183 self.pi(value, matches[5]);
2186 index = matches.index + matches[0].length;
2190 if (index < html.length)
2191 self.text(decode(html.substr(index)));
2193 // Close any open elements
2194 for (i = stack.length - 1; i >= 0; i--) {
2198 self.end(value.name);
2203 (function(tinymce) {
2204 var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = {
2210 '#document-fragment' : 11
2213 // Walks the tree left/right
2214 function walk(node, root_node, prev) {
2215 var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next';
2217 // Walk into nodes if it has a start
2218 if (node[startName])
2219 return node[startName];
2221 // Return the sibling if it has one
2222 if (node !== root_node) {
2223 sibling = node[siblingName];
2228 // Walk up the parents to look for siblings
2229 for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) {
2230 sibling = parent[siblingName];
2238 function Node(name, type) {
2243 this.attributes = [];
2244 this.attributes.map = {};
2248 tinymce.extend(Node.prototype, {
2249 replace : function(node) {
2255 self.insert(node, self);
2261 attr : function(name, value) {
2262 var self = this, attrs, i, undef;
2264 if (typeof name !== "string") {
2266 self.attr(i, name[i]);
2271 if (attrs = self.attributes) {
2272 if (value !== undef) {
2274 if (value === null) {
2275 if (name in attrs.map) {
2276 delete attrs.map[name];
2280 if (attrs[i].name === name) {
2281 attrs = attrs.splice(i, 1);
2291 if (name in attrs.map) {
2295 if (attrs[i].name === name) {
2296 attrs[i].value = value;
2301 attrs.push({name: name, value: value});
2303 attrs.map[name] = value;
2307 return attrs.map[name];
2312 clone : function() {
2313 var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs;
2315 // Clone element attributes
2316 if (selfAttrs = self.attributes) {
2318 cloneAttrs.map = {};
2320 for (i = 0, l = selfAttrs.length; i < l; i++) {
2321 selfAttr = selfAttrs[i];
2323 // Clone everything except id
2324 if (selfAttr.name !== 'id') {
2325 cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value};
2326 cloneAttrs.map[selfAttr.name] = selfAttr.value;
2330 clone.attributes = cloneAttrs;
2333 clone.value = self.value;
2334 clone.shortEnded = self.shortEnded;
2339 wrap : function(wrapper) {
2342 self.parent.insert(wrapper, self);
2343 wrapper.append(self);
2348 unwrap : function() {
2349 var self = this, node, next;
2351 for (node = self.firstChild; node; ) {
2353 self.insert(node, self, true);
2360 remove : function() {
2361 var self = this, parent = self.parent, next = self.next, prev = self.prev;
2364 if (parent.firstChild === self) {
2365 parent.firstChild = next;
2373 if (parent.lastChild === self) {
2374 parent.lastChild = prev;
2382 self.parent = self.next = self.prev = null;
2388 append : function(node) {
2389 var self = this, last;
2394 last = self.lastChild;
2398 self.lastChild = node;
2400 self.lastChild = self.firstChild = node;
2407 insert : function(node, ref_node, before) {
2413 parent = ref_node.parent || this;
2416 if (ref_node === parent.firstChild)
2417 parent.firstChild = node;
2419 ref_node.prev.next = node;
2421 node.prev = ref_node.prev;
2422 node.next = ref_node;
2423 ref_node.prev = node;
2425 if (ref_node === parent.lastChild)
2426 parent.lastChild = node;
2428 ref_node.next.prev = node;
2430 node.next = ref_node.next;
2431 node.prev = ref_node;
2432 ref_node.next = node;
2435 node.parent = parent;
2440 getAll : function(name) {
2441 var self = this, node, collection = [];
2443 for (node = self.firstChild; node; node = walk(node, self)) {
2444 if (node.name === name)
2445 collection.push(node);
2451 empty : function() {
2452 var self = this, nodes, i, node;
2454 // Remove all children
2455 if (self.firstChild) {
2458 // Collect the children
2459 for (node = self.firstChild; node; node = walk(node, self))
2462 // Remove the children
2466 node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
2470 self.firstChild = self.lastChild = null;
2475 isEmpty : function(elements) {
2476 var self = this, node = self.firstChild, i, name;
2480 if (node.type === 1) {
2481 // Ignore bogus elements
2482 if (node.attributes.map['data-mce-bogus'])
2485 // Keep empty elements like <img />
2486 if (elements[node.name])
2489 // Keep elements with data attributes or name attribute like <a name="1"></a>
2490 i = node.attributes.length;