JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
vanilla ckeditor-3.5.3
[ckeditor.git] / _source / plugins / styles / plugin.js
1 /*\r
2 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license\r
4 */\r
5 \r
6 CKEDITOR.plugins.add( 'styles',\r
7 {\r
8         requires : [ 'selection' ],\r
9         init : function( editor )\r
10         {\r
11                 // This doesn't look like correct, but it's the safest way to proper\r
12                 // pass the disableReadonlyStyling configuration to the style system\r
13                 // without having to change any method signature in the API. (#6103)\r
14                 editor.on( 'contentDom', function()\r
15                         {\r
16                                 editor.document.setCustomData( 'cke_includeReadonly', !editor.config.disableReadonlyStyling );\r
17                         });\r
18         }\r
19 });\r
20 \r
21 /**\r
22  * Registers a function to be called whenever the selection position changes in the\r
23  * editing area. The current state is passed to the function. The possible\r
24  * states are {@link CKEDITOR.TRISTATE_ON} and {@link CKEDITOR.TRISTATE_OFF}.\r
25  * @param {CKEDITOR.style} style The style to be watched.\r
26  * @param {Function} callback The function to be called.\r
27  * @example\r
28  * // Create a style object for the <b> element.\r
29  * var style = new CKEDITOR.style( { element : 'b' } );\r
30  * var editor = CKEDITOR.instances.editor1;\r
31  * editor.attachStyleStateChange( style, function( state )\r
32  *     {\r
33  *         if ( state == CKEDITOR.TRISTATE_ON )\r
34  *             alert( 'The current state for the B element is ON' );\r
35  *         else\r
36  *             alert( 'The current state for the B element is OFF' );\r
37  *     });\r
38  */\r
39 CKEDITOR.editor.prototype.attachStyleStateChange = function( style, callback )\r
40 {\r
41         // Try to get the list of attached callbacks.\r
42         var styleStateChangeCallbacks = this._.styleStateChangeCallbacks;\r
43 \r
44         // If it doesn't exist, it means this is the first call. So, let's create\r
45         // all the structure to manage the style checks and the callback calls.\r
46         if ( !styleStateChangeCallbacks )\r
47         {\r
48                 // Create the callbacks array.\r
49                 styleStateChangeCallbacks = this._.styleStateChangeCallbacks = [];\r
50 \r
51                 // Attach to the selectionChange event, so we can check the styles at\r
52                 // that point.\r
53                 this.on( 'selectionChange', function( ev )\r
54                         {\r
55                                 // Loop throw all registered callbacks.\r
56                                 for ( var i = 0 ; i < styleStateChangeCallbacks.length ; i++ )\r
57                                 {\r
58                                         var callback = styleStateChangeCallbacks[ i ];\r
59 \r
60                                         // Check the current state for the style defined for that\r
61                                         // callback.\r
62                                         var currentState = callback.style.checkActive( ev.data.path ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF;\r
63 \r
64                                         // Call the callback function, passing the current\r
65                                         // state to it.\r
66                                         callback.fn.call( this, currentState );\r
67                                 }\r
68                         });\r
69         }\r
70 \r
71         // Save the callback info, so it can be checked on the next occurrence of\r
72         // selectionChange.\r
73         styleStateChangeCallbacks.push( { style : style, fn : callback } );\r
74 };\r
75 \r
76 CKEDITOR.STYLE_BLOCK = 1;\r
77 CKEDITOR.STYLE_INLINE = 2;\r
78 CKEDITOR.STYLE_OBJECT = 3;\r
79 \r
80 (function()\r
81 {\r
82         var blockElements       = { address:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1 },\r
83                 objectElements  = { a:1,embed:1,hr:1,img:1,li:1,object:1,ol:1,table:1,td:1,tr:1,th:1,ul:1,dl:1,dt:1,dd:1,form:1};\r
84 \r
85         var semicolonFixRegex = /\s*(?:;\s*|$)/,\r
86                 varRegex = /#\((.+?)\)/g;\r
87 \r
88         var notBookmark = CKEDITOR.dom.walker.bookmark( 0, 1 ),\r
89                 nonWhitespaces = CKEDITOR.dom.walker.whitespaces( 1 );\r
90 \r
91         CKEDITOR.style = function( styleDefinition, variablesValues )\r
92         {\r
93                 if ( variablesValues )\r
94                 {\r
95                         styleDefinition = CKEDITOR.tools.clone( styleDefinition );\r
96 \r
97                         replaceVariables( styleDefinition.attributes, variablesValues );\r
98                         replaceVariables( styleDefinition.styles, variablesValues );\r
99                 }\r
100 \r
101                 var element = this.element = ( styleDefinition.element || '*' ).toLowerCase();\r
102 \r
103                 this.type =\r
104                         blockElements[ element ] ?\r
105                                 CKEDITOR.STYLE_BLOCK\r
106                         : objectElements[ element ] ?\r
107                                 CKEDITOR.STYLE_OBJECT\r
108                         :\r
109                                 CKEDITOR.STYLE_INLINE;\r
110 \r
111                 this._ =\r
112                 {\r
113                         definition : styleDefinition\r
114                 };\r
115         };\r
116 \r
117         CKEDITOR.style.prototype =\r
118         {\r
119                 apply : function( document )\r
120                 {\r
121                         applyStyle.call( this, document, false );\r
122                 },\r
123 \r
124                 remove : function( document )\r
125                 {\r
126                         applyStyle.call( this, document, true );\r
127                 },\r
128 \r
129                 applyToRange : function( range )\r
130                 {\r
131                         return ( this.applyToRange =\r
132                                                 this.type == CKEDITOR.STYLE_INLINE ?\r
133                                                         applyInlineStyle\r
134                                                 : this.type == CKEDITOR.STYLE_BLOCK ?\r
135                                                         applyBlockStyle\r
136                                                 : this.type == CKEDITOR.STYLE_OBJECT ?\r
137                                                         applyObjectStyle\r
138                                                 : null ).call( this, range );\r
139                 },\r
140 \r
141                 removeFromRange : function( range )\r
142                 {\r
143                         return ( this.removeFromRange =\r
144                                                 this.type == CKEDITOR.STYLE_INLINE ?\r
145                                                         removeInlineStyle\r
146                                                 : this.type == CKEDITOR.STYLE_BLOCK ?\r
147                                                         removeBlockStyle\r
148                                                 : this.type == CKEDITOR.STYLE_OBJECT ?\r
149                                                         removeObjectStyle\r
150                                                 : null ).call( this, range );\r
151                 },\r
152 \r
153                 applyToObject : function( element )\r
154                 {\r
155                         setupElement( element, this );\r
156                 },\r
157 \r
158                 /**\r
159                  * Get the style state inside an element path. Returns "true" if the\r
160                  * element is active in the path.\r
161                  */\r
162                 checkActive : function( elementPath )\r
163                 {\r
164                         switch ( this.type )\r
165                         {\r
166                                 case CKEDITOR.STYLE_BLOCK :\r
167                                         return this.checkElementRemovable( elementPath.block || elementPath.blockLimit, true );\r
168 \r
169                                 case CKEDITOR.STYLE_OBJECT :\r
170                                 case CKEDITOR.STYLE_INLINE :\r
171 \r
172                                         var elements = elementPath.elements;\r
173 \r
174                                         for ( var i = 0, element ; i < elements.length ; i++ )\r
175                                         {\r
176                                                 element = elements[ i ];\r
177 \r
178                                                 if ( this.type == CKEDITOR.STYLE_INLINE\r
179                                                           && ( element == elementPath.block || element == elementPath.blockLimit ) )\r
180                                                         continue;\r
181 \r
182                                                 if( this.type == CKEDITOR.STYLE_OBJECT\r
183                                                          && !( element.getName() in objectElements ) )\r
184                                                                 continue;\r
185 \r
186                                                 if ( this.checkElementRemovable( element, true ) )\r
187                                                         return true;\r
188                                         }\r
189                         }\r
190                         return false;\r
191                 },\r
192 \r
193                 /**\r
194                  * Whether this style can be applied at the element path.\r
195                  * @param elementPath\r
196                  */\r
197                 checkApplicable : function( elementPath )\r
198                 {\r
199                         switch ( this.type )\r
200                         {\r
201                                 case CKEDITOR.STYLE_INLINE :\r
202                                 case CKEDITOR.STYLE_BLOCK :\r
203                                         break;\r
204 \r
205                                 case CKEDITOR.STYLE_OBJECT :\r
206                                         return elementPath.lastElement.getAscendant( this.element, true );\r
207                         }\r
208 \r
209                         return true;\r
210                 },\r
211 \r
212                 // Checks if an element, or any of its attributes, is removable by the\r
213                 // current style definition.\r
214                 checkElementRemovable : function( element, fullMatch )\r
215                 {\r
216                         if ( !element )\r
217                                 return false;\r
218 \r
219                         var def = this._.definition,\r
220                                 attribs;\r
221 \r
222                         // If the element name is the same as the style name.\r
223                         if ( element.getName() == this.element )\r
224                         {\r
225                                 // If no attributes are defined in the element.\r
226                                 if ( !fullMatch && !element.hasAttributes() )\r
227                                         return true;\r
228 \r
229                                 attribs = getAttributesForComparison( def );\r
230 \r
231                                 if ( attribs._length )\r
232                                 {\r
233                                         for ( var attName in attribs )\r
234                                         {\r
235                                                 if ( attName == '_length' )\r
236                                                         continue;\r
237 \r
238                                                 var elementAttr = element.getAttribute( attName ) || '';\r
239 \r
240                                                 // Special treatment for 'style' attribute is required.\r
241                                                 if ( attName == 'style' ?\r
242                                                         compareCssText( attribs[ attName ], normalizeCssText( elementAttr, false ) )\r
243                                                         : attribs[ attName ] == elementAttr  )\r
244                                                 {\r
245                                                         if ( !fullMatch )\r
246                                                                 return true;\r
247                                                 }\r
248                                                 else if ( fullMatch )\r
249                                                                 return false;\r
250                                         }\r
251                                         if ( fullMatch )\r
252                                                 return true;\r
253                                 }\r
254                                 else\r
255                                         return true;\r
256                         }\r
257 \r
258                         // Check if the element can be somehow overriden.\r
259                         var override = getOverrides( this )[ element.getName() ] ;\r
260                         if ( override )\r
261                         {\r
262                                 // If no attributes have been defined, remove the element.\r
263                                 if ( !( attribs = override.attributes ) )\r
264                                         return true;\r
265 \r
266                                 for ( var i = 0 ; i < attribs.length ; i++ )\r
267                                 {\r
268                                         attName = attribs[i][0];\r
269                                         var actualAttrValue = element.getAttribute( attName );\r
270                                         if ( actualAttrValue )\r
271                                         {\r
272                                                 var attValue = attribs[i][1];\r
273 \r
274                                                 // Remove the attribute if:\r
275                                                 //    - The override definition value is null;\r
276                                                 //    - The override definition value is a string that\r
277                                                 //      matches the attribute value exactly.\r
278                                                 //    - The override definition value is a regex that\r
279                                                 //      has matches in the attribute value.\r
280                                                 if ( attValue === null ||\r
281                                                                 ( typeof attValue == 'string' && actualAttrValue == attValue ) ||\r
282                                                                 attValue.test( actualAttrValue ) )\r
283                                                         return true;\r
284                                         }\r
285                                 }\r
286                         }\r
287                         return false;\r
288                 },\r
289 \r
290                 // Builds the preview HTML based on the styles definition.\r
291                 buildPreview : function()\r
292                 {\r
293                         var styleDefinition = this._.definition,\r
294                                 html = [],\r
295                                 elementName = styleDefinition.element;\r
296 \r
297                         // Avoid <bdo> in the preview.\r
298                         if ( elementName == 'bdo' )\r
299                                 elementName = 'span';\r
300 \r
301                         html = [ '<', elementName ];\r
302 \r
303                         // Assign all defined attributes.\r
304                         var attribs     = styleDefinition.attributes;\r
305                         if ( attribs )\r
306                         {\r
307                                 for ( var att in attribs )\r
308                                 {\r
309                                         html.push( ' ', att, '="', attribs[ att ], '"' );\r
310                                 }\r
311                         }\r
312 \r
313                         // Assign the style attribute.\r
314                         var cssStyle = CKEDITOR.style.getStyleText( styleDefinition );\r
315                         if ( cssStyle )\r
316                                 html.push( ' style="', cssStyle, '"' );\r
317 \r
318                         html.push( '>', styleDefinition.name, '</', elementName, '>' );\r
319 \r
320                         return html.join( '' );\r
321                 }\r
322         };\r
323 \r
324         // Build the cssText based on the styles definition.\r
325         CKEDITOR.style.getStyleText = function( styleDefinition )\r
326         {\r
327                 // If we have already computed it, just return it.\r
328                 var stylesDef = styleDefinition._ST;\r
329                 if ( stylesDef )\r
330                         return stylesDef;\r
331 \r
332                 stylesDef = styleDefinition.styles;\r
333 \r
334                 // Builds the StyleText.\r
335                 var stylesText = ( styleDefinition.attributes && styleDefinition.attributes[ 'style' ] ) || '',\r
336                                 specialStylesText = '';\r
337 \r
338                 if ( stylesText.length )\r
339                         stylesText = stylesText.replace( semicolonFixRegex, ';' );\r
340 \r
341                 for ( var style in stylesDef )\r
342                 {\r
343                         var styleVal = stylesDef[ style ],\r
344                                         text = ( style + ':' + styleVal ).replace( semicolonFixRegex, ';' );\r
345 \r
346                         // Some browsers don't support 'inherit' property value, leave them intact. (#5242)\r
347                         if ( styleVal == 'inherit' )\r
348                                 specialStylesText += text;\r
349                         else\r
350                                 stylesText += text;\r
351                 }\r
352 \r
353                 // Browsers make some changes to the style when applying them. So, here\r
354                 // we normalize it to the browser format.\r
355                 if ( stylesText.length )\r
356                         stylesText = normalizeCssText( stylesText );\r
357 \r
358                 stylesText += specialStylesText;\r
359 \r
360                 // Return it, saving it to the next request.\r
361                 return ( styleDefinition._ST = stylesText );\r
362         };\r
363 \r
364         // Gets the parent element which blocks the styling for an element. This\r
365         // can be done through read-only elements (contenteditable=false) or\r
366         // elements with the "data-nostyle" attribute.\r
367         function getUnstylableParent( element )\r
368         {\r
369                 var unstylable,\r
370                         editable;\r
371 \r
372                 while ( ( element = element.getParent() ) )\r
373                 {\r
374                         if ( element.getName() == 'body' )\r
375                                 break;\r
376 \r
377                         if ( element.getAttribute( 'data-nostyle' ) )\r
378                                 unstylable = element;\r
379                         else if ( !editable )\r
380                         {\r
381                                 var contentEditable = element.getAttribute( 'contentEditable' );\r
382 \r
383                                 if ( contentEditable == 'false' )\r
384                                         unstylable = element;\r
385                                 else if ( contentEditable == 'true' )\r
386                                         editable = 1;\r
387                         }\r
388                 }\r
389 \r
390                 return unstylable;\r
391         }\r
392 \r
393         function applyInlineStyle( range )\r
394         {\r
395                 var document = range.document;\r
396 \r
397                 if ( range.collapsed )\r
398                 {\r
399                         // Create the element to be inserted in the DOM.\r
400                         var collapsedElement = getElement( this, document );\r
401 \r
402                         // Insert the empty element into the DOM at the range position.\r
403                         range.insertNode( collapsedElement );\r
404 \r
405                         // Place the selection right inside the empty element.\r
406                         range.moveToPosition( collapsedElement, CKEDITOR.POSITION_BEFORE_END );\r
407 \r
408                         return;\r
409                 }\r
410 \r
411                 var elementName = this.element;\r
412                 var def = this._.definition;\r
413                 var isUnknownElement;\r
414 \r
415                 // Indicates that fully selected read-only elements are to be included in the styling range.\r
416                 var includeReadonly = def.includeReadonly;\r
417 \r
418                 // If the read-only inclusion is not available in the definition, try\r
419                 // to get it from the document data.\r
420                 if ( includeReadonly == undefined )\r
421                         includeReadonly = document.getCustomData( 'cke_includeReadonly' );\r
422 \r
423                 // Get the DTD definition for the element. Defaults to "span".\r
424                 var dtd = CKEDITOR.dtd[ elementName ] || ( isUnknownElement = true, CKEDITOR.dtd.span );\r
425 \r
426                 // Expand the range.\r
427                 range.enlarge( CKEDITOR.ENLARGE_ELEMENT, 1 );\r
428                 range.trim();\r
429 \r
430                 // Get the first node to be processed and the last, which concludes the\r
431                 // processing.\r
432                 var boundaryNodes = range.createBookmark(),\r
433                         firstNode = boundaryNodes.startNode,\r
434                         lastNode = boundaryNodes.endNode;\r
435 \r
436                 var currentNode = firstNode;\r
437 \r
438                 var styleRange;\r
439 \r
440                 // Check if the boundaries are inside non stylable elements.\r
441                 var firstUnstylable = getUnstylableParent( firstNode ),\r
442                         lastUnstylable = getUnstylableParent( lastNode );\r
443 \r
444                 // If the first element can't be styled, we'll start processing right\r
445                 // after its unstylable root.\r
446                 if ( firstUnstylable )\r
447                         currentNode = firstUnstylable.getNextSourceNode( true );\r
448 \r
449                 // If the last element can't be styled, we'll stop processing on its\r
450                 // unstylable root.\r
451                 if ( lastUnstylable )\r
452                         lastNode = lastUnstylable;\r
453 \r
454                 // Do nothing if the current node now follows the last node to be processed.\r
455                 if ( currentNode.getPosition( lastNode ) == CKEDITOR.POSITION_FOLLOWING )\r
456                         currentNode = 0;\r
457 \r
458                 while ( currentNode )\r
459                 {\r
460                         var applyStyle = false;\r
461 \r
462                         if ( currentNode.equals( lastNode ) )\r
463                         {\r
464                                 currentNode = null;\r
465                                 applyStyle = true;\r
466                         }\r
467                         else\r
468                         {\r
469                                 var nodeType = currentNode.type;\r
470                                 var nodeName = nodeType == CKEDITOR.NODE_ELEMENT ? currentNode.getName() : null;\r
471                                 var nodeIsReadonly = nodeName && ( currentNode.getAttribute( 'contentEditable' ) == 'false' );\r
472                                 var nodeIsNoStyle = nodeName && currentNode.getAttribute( 'data-nostyle' );\r
473 \r
474                                 if ( nodeName && currentNode.data( 'cke-bookmark' ) )\r
475                                 {\r
476                                         currentNode = currentNode.getNextSourceNode( true );\r
477                                         continue;\r
478                                 }\r
479 \r
480                                 // Check if the current node can be a child of the style element.\r
481                                 if ( !nodeName || ( dtd[ nodeName ]\r
482                                         && !nodeIsNoStyle\r
483                                         && ( !nodeIsReadonly || includeReadonly )\r
484                                         && ( currentNode.getPosition( lastNode ) | CKEDITOR.POSITION_PRECEDING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_PRECEDING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED )\r
485                                         && ( !def.childRule || def.childRule( currentNode ) ) ) )\r
486                                 {\r
487                                         var currentParent = currentNode.getParent();\r
488 \r
489                                         // Check if the style element can be a child of the current\r
490                                         // node parent or if the element is not defined in the DTD.\r
491                                         if ( currentParent\r
492                                                 && ( ( currentParent.getDtd() || CKEDITOR.dtd.span )[ elementName ] || isUnknownElement )\r
493                                                 && ( !def.parentRule || def.parentRule( currentParent ) ) )\r
494                                         {\r
495                                                 // This node will be part of our range, so if it has not\r
496                                                 // been started, place its start right before the node.\r
497                                                 // In the case of an element node, it will be included\r
498                                                 // only if it is entirely inside the range.\r
499                                                 if ( !styleRange && ( !nodeName || !CKEDITOR.dtd.$removeEmpty[ nodeName ] || ( currentNode.getPosition( lastNode ) | CKEDITOR.POSITION_PRECEDING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_PRECEDING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED ) ) )\r
500                                                 {\r
501                                                         styleRange = new CKEDITOR.dom.range( document );\r
502                                                         styleRange.setStartBefore( currentNode );\r
503                                                 }\r
504 \r
505                                                 // Non element nodes, readonly elements, or empty\r
506                                                 // elements can be added completely to the range.\r
507                                                 if ( nodeType == CKEDITOR.NODE_TEXT || nodeIsReadonly || ( nodeType == CKEDITOR.NODE_ELEMENT && !currentNode.getChildCount() ) )\r
508                                                 {\r
509                                                         var includedNode = currentNode;\r
510                                                         var parentNode;\r
511 \r
512                                                         // This node is about to be included completelly, but,\r
513                                                         // if this is the last node in its parent, we must also\r
514                                                         // check if the parent itself can be added completelly\r
515                                                         // to the range, otherwise apply the style immediately.\r
516                                                         while ( ( applyStyle = !includedNode.getNext( notBookmark ) )\r
517                                                                 && ( parentNode = includedNode.getParent(), dtd[ parentNode.getName() ] )\r
518                                                                 && ( parentNode.getPosition( firstNode ) | CKEDITOR.POSITION_FOLLOWING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_FOLLOWING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED )\r
519                                                                 && ( !def.childRule || def.childRule( parentNode ) ) )\r
520                                                         {\r
521                                                                 includedNode = parentNode;\r
522                                                         }\r
523 \r
524                                                         styleRange.setEndAfter( includedNode );\r
525 \r
526                                                 }\r
527                                         }\r
528                                         else\r
529                                                 applyStyle = true;\r
530                                 }\r
531                                 else\r
532                                         applyStyle = true;\r
533 \r
534                                 // Get the next node to be processed.\r
535                                 currentNode = currentNode.getNextSourceNode( nodeIsNoStyle || nodeIsReadonly );\r
536                         }\r
537 \r
538                         // Apply the style if we have something to which apply it.\r
539                         if ( applyStyle && styleRange && !styleRange.collapsed )\r
540                         {\r
541                                 // Build the style element, based on the style object definition.\r
542                                 var styleNode = getElement( this, document ),\r
543                                         styleHasAttrs = styleNode.hasAttributes();\r
544 \r
545                                 // Get the element that holds the entire range.\r
546                                 var parent = styleRange.getCommonAncestor();\r
547 \r
548                                 var removeList = {\r
549                                         styles : {},\r
550                                         attrs : {},\r
551                                         // Styles cannot be removed.\r
552                                         blockedStyles : {},\r
553                                         // Attrs cannot be removed.\r
554                                         blockedAttrs : {}\r
555                                 };\r
556 \r
557                                 var attName, styleName, value;\r
558 \r
559                                 // Loop through the parents, removing the redundant attributes\r
560                                 // from the element to be applied.\r
561                                 while ( styleNode && parent )\r
562                                 {\r
563                                         if ( parent.getName() == elementName )\r
564                                         {\r
565                                                 for ( attName in def.attributes )\r
566                                                 {\r
567                                                         if ( removeList.blockedAttrs[ attName ] || !( value = parent.getAttribute( styleName ) ) )\r
568                                                                 continue;\r
569 \r
570                                                         if ( styleNode.getAttribute( attName ) == value )\r
571                                                                 removeList.attrs[ attName ] = 1;\r
572                                                         else\r
573                                                                 removeList.blockedAttrs[ attName ] = 1;\r
574                                                 }\r
575 \r
576                                                 for ( styleName in def.styles )\r
577                                                 {\r
578                                                         if ( removeList.blockedStyles[ styleName ] || !( value = parent.getStyle( styleName ) ) )\r
579                                                                 continue;\r
580 \r
581                                                         if ( styleNode.getStyle( styleName ) == value )\r
582                                                                 removeList.styles[ styleName ] = 1;\r
583                                                         else\r
584                                                                 removeList.blockedStyles[ styleName ] = 1;\r
585                                                 }\r
586                                         }\r
587 \r
588                                         parent = parent.getParent();\r
589                                 }\r
590 \r
591                                 for ( attName in removeList.attrs )\r
592                                         styleNode.removeAttribute( attName );\r
593 \r
594                                 for ( styleName in removeList.styles )\r
595                                         styleNode.removeStyle( styleName );\r
596 \r
597                                 if ( styleHasAttrs && !styleNode.hasAttributes() )\r
598                                         styleNode = null;\r
599 \r
600                                 if ( styleNode )\r
601                                 {\r
602                                         // Move the contents of the range to the style element.\r
603                                         styleRange.extractContents().appendTo( styleNode );\r
604 \r
605                                         // Here we do some cleanup, removing all duplicated\r
606                                         // elements from the style element.\r
607                                         removeFromInsideElement( this, styleNode );\r
608 \r
609                                         // Insert it into the range position (it is collapsed after\r
610                                         // extractContents.\r
611                                         styleRange.insertNode( styleNode );\r
612 \r
613                                         // Let's merge our new style with its neighbors, if possible.\r
614                                         styleNode.mergeSiblings();\r
615 \r
616                                         // As the style system breaks text nodes constantly, let's normalize\r
617                                         // things for performance.\r
618                                         // With IE, some paragraphs get broken when calling normalize()\r
619                                         // repeatedly. Also, for IE, we must normalize body, not documentElement.\r
620                                         // IE is also known for having a "crash effect" with normalize().\r
621                                         // We should try to normalize with IE too in some way, somewhere.\r
622                                         if ( !CKEDITOR.env.ie )\r
623                                                 styleNode.$.normalize();\r
624                                 }\r
625                                 // Style already inherit from parents, left just to clear up any internal overrides. (#5931)\r
626                                 else\r
627                                 {\r
628                                         styleNode = new CKEDITOR.dom.element( 'span' );\r
629                                         styleRange.extractContents().appendTo( styleNode );\r
630                                         styleRange.insertNode( styleNode );\r
631                                         removeFromInsideElement( this, styleNode );\r
632                                         styleNode.remove( true );\r
633                                 }\r
634 \r
635                                 // Style applied, let's release the range, so it gets\r
636                                 // re-initialization in the next loop.\r
637                                 styleRange = null;\r
638                         }\r
639                 }\r
640 \r
641                 // Remove the bookmark nodes.\r
642                 range.moveToBookmark( boundaryNodes );\r
643 \r
644                 // Minimize the result range to exclude empty text nodes. (#5374)\r
645                 range.shrink( CKEDITOR.SHRINK_TEXT );\r
646         }\r
647 \r
648         function removeInlineStyle( range )\r
649         {\r
650                 /*\r
651                  * Make sure our range has included all "collpased" parent inline nodes so\r
652                  * that our operation logic can be simpler.\r
653                  */\r
654                 range.enlarge( CKEDITOR.ENLARGE_ELEMENT, 1 );\r
655 \r
656                 var bookmark = range.createBookmark(),\r
657                         startNode = bookmark.startNode;\r
658 \r
659                 if ( range.collapsed )\r
660                 {\r
661 \r
662                         var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),\r
663                                 // The topmost element in elementspatch which we should jump out of.\r
664                                 boundaryElement;\r
665 \r
666 \r
667                         for ( var i = 0, element ; i < startPath.elements.length\r
668                                         && ( element = startPath.elements[i] ) ; i++ )\r
669                         {\r
670                                 /*\r
671                                  * 1. If it's collaped inside text nodes, try to remove the style from the whole element.\r
672                                  *\r
673                                  * 2. Otherwise if it's collapsed on element boundaries, moving the selection\r
674                                  *  outside the styles instead of removing the whole tag,\r
675                                  *  also make sure other inner styles were well preserverd.(#3309)\r
676                                  */\r
677                                 if ( element == startPath.block || element == startPath.blockLimit )\r
678                                         break;\r
679 \r
680                                 if ( this.checkElementRemovable( element ) )\r
681                                 {\r
682                                         var isStart;\r
683 \r
684                                         if ( range.collapsed && (\r
685                                                  range.checkBoundaryOfElement( element, CKEDITOR.END ) ||\r
686                                                  ( isStart = range.checkBoundaryOfElement( element, CKEDITOR.START ) ) ) )\r
687                                         {\r
688                                                 boundaryElement = element;\r
689                                                 boundaryElement.match = isStart ? 'start' : 'end';\r
690                                         }\r
691                                         else\r
692                                         {\r
693                                                 /*\r
694                                                  * Before removing the style node, there may be a sibling to the style node\r
695                                                  * that's exactly the same to the one to be removed. To the user, it makes\r
696                                                  * no difference that they're separate entities in the DOM tree. So, merge\r
697                                                  * them before removal.\r
698                                                  */\r
699                                                 element.mergeSiblings();\r
700                                                 if ( element.getName() == this.element )\r
701                                                         removeFromElement( this, element );\r
702                                                 else\r
703                                                         removeOverrides( element, getOverrides( this )[ element.getName() ] );\r
704                                         }\r
705                                 }\r
706                         }\r
707 \r
708                         // Re-create the style tree after/before the boundary element,\r
709                         // the replication start from bookmark start node to define the\r
710                         // new range.\r
711                         if ( boundaryElement )\r
712                         {\r
713                                 var clonedElement = startNode;\r
714                                 for ( i = 0 ;; i++ )\r
715                                 {\r
716                                         var newElement = startPath.elements[ i ];\r
717                                         if ( newElement.equals( boundaryElement ) )\r
718                                                 break;\r
719                                         // Avoid copying any matched element.\r
720                                         else if ( newElement.match )\r
721                                                 continue;\r
722                                         else\r
723                                                 newElement = newElement.clone();\r
724                                         newElement.append( clonedElement );\r
725                                         clonedElement = newElement;\r
726                                 }\r
727                                 clonedElement[ boundaryElement.match == 'start' ?\r
728                                                         'insertBefore' : 'insertAfter' ]( boundaryElement );\r
729                         }\r
730                 }\r
731                 else\r
732                 {\r
733                         /*\r
734                          * Now our range isn't collapsed. Lets walk from the start node to the end\r
735                          * node via DFS and remove the styles one-by-one.\r
736                          */\r
737                         var endNode = bookmark.endNode,\r
738                                 me = this;\r
739 \r
740                         /*\r
741                          * Find out the style ancestor that needs to be broken down at startNode\r
742                          * and endNode.\r
743                          */\r
744                         function breakNodes()\r
745                         {\r
746                                 var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),\r
747                                         endPath = new CKEDITOR.dom.elementPath( endNode.getParent() ),\r
748                                         breakStart = null,\r
749                                         breakEnd = null;\r
750                                 for ( var i = 0 ; i < startPath.elements.length ; i++ )\r
751                                 {\r
752                                         var element = startPath.elements[ i ];\r
753 \r
754                                         if ( element == startPath.block || element == startPath.blockLimit )\r
755                                                 break;\r
756 \r
757                                         if ( me.checkElementRemovable( element ) )\r
758                                                 breakStart = element;\r
759                                 }\r
760                                 for ( i = 0 ; i < endPath.elements.length ; i++ )\r
761                                 {\r
762                                         element = endPath.elements[ i ];\r
763 \r
764                                         if ( element == endPath.block || element == endPath.blockLimit )\r
765                                                 break;\r
766 \r
767                                         if ( me.checkElementRemovable( element ) )\r
768                                                 breakEnd = element;\r
769                                 }\r
770 \r
771                                 if ( breakEnd )\r
772                                         endNode.breakParent( breakEnd );\r
773                                 if ( breakStart )\r
774                                         startNode.breakParent( breakStart );\r
775                         }\r
776                         breakNodes();\r
777 \r
778                         // Now, do the DFS walk.\r
779                         var currentNode = startNode.getNext();\r
780                         while ( !currentNode.equals( endNode ) )\r
781                         {\r
782                                 /*\r
783                                  * Need to get the next node first because removeFromElement() can remove\r
784                                  * the current node from DOM tree.\r
785                                  */\r
786                                 var nextNode = currentNode.getNextSourceNode();\r
787                                 if ( currentNode.type == CKEDITOR.NODE_ELEMENT && this.checkElementRemovable( currentNode ) )\r
788                                 {\r
789                                         // Remove style from element or overriding element.\r
790                                         if ( currentNode.getName() == this.element )\r
791                                                 removeFromElement( this, currentNode );\r
792                                         else\r
793                                                 removeOverrides( currentNode, getOverrides( this )[ currentNode.getName() ] );\r
794 \r
795                                         /*\r
796                                          * removeFromElement() may have merged the next node with something before\r
797                                          * the startNode via mergeSiblings(). In that case, the nextNode would\r
798                                          * contain startNode and we'll have to call breakNodes() again and also\r
799                                          * reassign the nextNode to something after startNode.\r
800                                          */\r
801                                         if ( nextNode.type == CKEDITOR.NODE_ELEMENT && nextNode.contains( startNode ) )\r
802                                         {\r
803                                                 breakNodes();\r
804                                                 nextNode = startNode.getNext();\r
805                                         }\r
806                                 }\r
807                                 currentNode = nextNode;\r
808                         }\r
809                 }\r
810 \r
811                 range.moveToBookmark( bookmark );\r
812         }\r
813 \r
814         function applyObjectStyle( range )\r
815         {\r
816                 var root = range.getCommonAncestor( true, true ),\r
817                         element = root.getAscendant( this.element, true );\r
818                 element && setupElement( element, this );\r
819         }\r
820 \r
821         function removeObjectStyle( range )\r
822         {\r
823                 var root = range.getCommonAncestor( true, true ),\r
824                         element = root.getAscendant( this.element, true );\r
825 \r
826                 if ( !element )\r
827                         return;\r
828 \r
829                 var style = this,\r
830                         def = style._.definition,\r
831                         attributes = def.attributes;\r
832                 var styles = CKEDITOR.style.getStyleText( def );\r
833 \r
834                 // Remove all defined attributes.\r
835                 if ( attributes )\r
836                 {\r
837                         for ( var att in attributes )\r
838                         {\r
839                                 element.removeAttribute( att, attributes[ att ] );\r
840                         }\r
841                 }\r
842 \r
843                 // Assign all defined styles.\r
844                 if ( def.styles )\r
845                 {\r
846                         for ( var i in def.styles )\r
847                         {\r
848                                 if ( !def.styles.hasOwnProperty( i ) )\r
849                                         continue;\r
850 \r
851                                 element.removeStyle( i );\r
852                         }\r
853                 }\r
854         }\r
855 \r
856         function applyBlockStyle( range )\r
857         {\r
858                 // Serializible bookmarks is needed here since\r
859                 // elements may be merged.\r
860                 var bookmark = range.createBookmark( true );\r
861 \r
862                 var iterator = range.createIterator();\r
863                 iterator.enforceRealBlocks = true;\r
864 \r
865                 // make recognize <br /> tag as a separator in ENTER_BR mode (#5121)\r
866                 if ( this._.enterMode )\r
867                         iterator.enlargeBr = ( this._.enterMode != CKEDITOR.ENTER_BR );\r
868 \r
869                 var block;\r
870                 var doc = range.document;\r
871                 var previousPreBlock;\r
872 \r
873                 while ( ( block = iterator.getNextParagraph() ) )               // Only one =\r
874                 {\r
875                         var newBlock = getElement( this, doc, block );\r
876                         replaceBlock( block, newBlock );\r
877                 }\r
878 \r
879                 range.moveToBookmark( bookmark );\r
880         }\r
881 \r
882         function removeBlockStyle( range )\r
883         {\r
884                 // Serializible bookmarks is needed here since\r
885                 // elements may be merged.\r
886                 var bookmark = range.createBookmark( 1 );\r
887 \r
888                 var iterator = range.createIterator();\r
889                 iterator.enforceRealBlocks = true;\r
890                 iterator.enlargeBr = this._.enterMode != CKEDITOR.ENTER_BR;\r
891 \r
892                 var block;\r
893                 while ( ( block = iterator.getNextParagraph() ) )\r
894                 {\r
895                         if ( this.checkElementRemovable( block ) )\r
896                         {\r
897                                 // <pre> get special treatment.\r
898                                 if ( block.is( 'pre' ) )\r
899                                 {\r
900                                         var newBlock = this._.enterMode == CKEDITOR.ENTER_BR ?\r
901                                                                 null : range.document.createElement(\r
902                                                                         this._.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );\r
903 \r
904                                         newBlock && block.copyAttributes( newBlock );\r
905                                         replaceBlock( block, newBlock );\r
906                                 }\r
907                                 else\r
908                                          removeFromElement( this, block, 1 );\r
909                         }\r
910                 }\r
911 \r
912                 range.moveToBookmark( bookmark );\r
913         }\r
914 \r
915         // Replace the original block with new one, with special treatment\r
916         // for <pre> blocks to make sure content format is well preserved, and merging/splitting adjacent\r
917         // when necessary.(#3188)\r
918         function replaceBlock( block, newBlock )\r
919         {\r
920                 // Block is to be removed, create a temp element to\r
921                 // save contents.\r
922                 var removeBlock = !newBlock;\r
923                 if ( removeBlock )\r
924                 {\r
925                         newBlock = block.getDocument().createElement( 'div' );\r
926                         block.copyAttributes( newBlock );\r
927                 }\r
928 \r
929                 var newBlockIsPre       = newBlock && newBlock.is( 'pre' );\r
930                 var blockIsPre  = block.is( 'pre' );\r
931 \r
932                 var isToPre     = newBlockIsPre && !blockIsPre;\r
933                 var isFromPre   = !newBlockIsPre && blockIsPre;\r
934 \r
935                 if ( isToPre )\r
936                         newBlock = toPre( block, newBlock );\r
937                 else if ( isFromPre )\r
938                         // Split big <pre> into pieces before start to convert.\r
939                         newBlock = fromPres( removeBlock ?\r
940                                                 [ block.getHtml() ] : splitIntoPres( block ), newBlock );\r
941                 else\r
942                         block.moveChildren( newBlock );\r
943 \r
944                 newBlock.replace( block );\r
945 \r
946                 if ( newBlockIsPre )\r
947                 {\r
948                         // Merge previous <pre> blocks.\r
949                         mergePre( newBlock );\r
950                 }\r
951                 else if ( removeBlock )\r
952                         removeNoAttribsElement( newBlock );\r
953         }\r
954 \r
955         /**\r
956          * Merge a <pre> block with a previous sibling if available.\r
957          */\r
958         function mergePre( preBlock )\r
959         {\r
960                 var previousBlock;\r
961                 if ( !( ( previousBlock = preBlock.getPrevious( nonWhitespaces ) )\r
962                                  && previousBlock.is\r
963                                  && previousBlock.is( 'pre') ) )\r
964                         return;\r
965 \r
966                 // Merge the previous <pre> block contents into the current <pre>\r
967                 // block.\r
968                 //\r
969                 // Another thing to be careful here is that currentBlock might contain\r
970                 // a '\n' at the beginning, and previousBlock might contain a '\n'\r
971                 // towards the end. These new lines are not normally displayed but they\r
972                 // become visible after merging.\r
973                 var mergedHtml = replace( previousBlock.getHtml(), /\n$/, '' ) + '\n\n' +\r
974                                 replace( preBlock.getHtml(), /^\n/, '' ) ;\r
975 \r
976                 // Krugle: IE normalizes innerHTML from <pre>, breaking whitespaces.\r
977                 if ( CKEDITOR.env.ie )\r
978                         preBlock.$.outerHTML = '<pre>' + mergedHtml + '</pre>';\r
979                 else\r
980                         preBlock.setHtml( mergedHtml );\r
981 \r
982                 previousBlock.remove();\r
983         }\r
984 \r
985         /**\r
986          * Split into multiple <pre> blocks separated by double line-break.\r
987          * @param preBlock\r
988          */\r
989         function splitIntoPres( preBlock )\r
990         {\r
991                 // Exclude the ones at header OR at tail,\r
992                 // and ignore bookmark content between them.\r
993                 var duoBrRegex = /(\S\s*)\n(?:\s|(<span[^>]+data-cke-bookmark.*?\/span>))*\n(?!$)/gi,\r
994                         blockName = preBlock.getName(),\r
995                         splitedHtml = replace( preBlock.getOuterHtml(),\r
996                                 duoBrRegex,\r
997                                 function( match, charBefore, bookmark )\r
998                                 {\r
999                                   return charBefore + '</pre>' + bookmark + '<pre>';\r
1000                                 } );\r
1001 \r
1002                 var pres = [];\r
1003                 splitedHtml.replace( /<pre\b.*?>([\s\S]*?)<\/pre>/gi, function( match, preContent ){\r
1004                         pres.push( preContent );\r
1005                 } );\r
1006                 return pres;\r
1007         }\r
1008 \r
1009         // Wrapper function of String::replace without considering of head/tail bookmarks nodes.\r
1010         function replace( str, regexp, replacement )\r
1011         {\r
1012                 var headBookmark = '',\r
1013                         tailBookmark = '';\r
1014 \r
1015                 str = str.replace( /(^<span[^>]+data-cke-bookmark.*?\/span>)|(<span[^>]+data-cke-bookmark.*?\/span>$)/gi,\r
1016                         function( str, m1, m2 ){\r
1017                                         m1 && ( headBookmark = m1 );\r
1018                                         m2 && ( tailBookmark = m2 );\r
1019                                 return '';\r
1020                         } );\r
1021                 return headBookmark + str.replace( regexp, replacement ) + tailBookmark;\r
1022         }\r
1023 \r
1024         /**\r
1025          * Converting a list of <pre> into blocks with format well preserved.\r
1026          */\r
1027         function fromPres( preHtmls, newBlock )\r
1028         {\r
1029                 var docFrag;\r
1030                 if ( preHtmls.length > 1 )\r
1031                         docFrag = new CKEDITOR.dom.documentFragment( newBlock.getDocument() );\r
1032 \r
1033                 for ( var i = 0 ; i < preHtmls.length ; i++ )\r
1034                 {\r
1035                         var blockHtml = preHtmls[ i ];\r
1036 \r
1037                         // 1. Trim the first and last line-breaks immediately after and before <pre>,\r
1038                         // they're not visible.\r
1039                          blockHtml =  blockHtml.replace( /(\r\n|\r)/g, '\n' ) ;\r
1040                          blockHtml = replace(  blockHtml, /^[ \t]*\n/, '' ) ;\r
1041                          blockHtml = replace(  blockHtml, /\n$/, '' ) ;\r
1042                         // 2. Convert spaces or tabs at the beginning or at the end to &nbsp;\r
1043                          blockHtml = replace(  blockHtml, /^[ \t]+|[ \t]+$/g, function( match, offset, s )\r
1044                                         {\r
1045                                                 if ( match.length == 1 )        // one space, preserve it\r
1046                                                         return '&nbsp;' ;\r
1047                                                 else if ( !offset )             // beginning of block\r
1048                                                         return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' ';\r
1049                                                 else                            // end of block\r
1050                                                         return ' ' + CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 );\r
1051                                         } ) ;\r
1052 \r
1053                         // 3. Convert \n to <BR>.\r
1054                         // 4. Convert contiguous (i.e. non-singular) spaces or tabs to &nbsp;\r
1055                          blockHtml =  blockHtml.replace( /\n/g, '<br>' ) ;\r
1056                          blockHtml =  blockHtml.replace( /[ \t]{2,}/g,\r
1057                                         function ( match )\r
1058                                         {\r
1059                                                 return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' ' ;\r
1060                                         } ) ;\r
1061 \r
1062                         if ( docFrag )\r
1063                         {\r
1064                                 var newBlockClone = newBlock.clone();\r
1065                                 newBlockClone.setHtml(  blockHtml );\r
1066                                 docFrag.append( newBlockClone );\r
1067                         }\r
1068                         else\r
1069                                 newBlock.setHtml( blockHtml );\r
1070                 }\r
1071 \r
1072                 return docFrag || newBlock;\r
1073         }\r
1074 \r
1075         /**\r
1076          * Converting from a non-PRE block to a PRE block in formatting operations.\r
1077          */\r
1078         function toPre( block, newBlock )\r
1079         {\r
1080                 var bogus = block.getBogus();\r
1081                 bogus && bogus.remove();\r
1082 \r
1083                 // First trim the block content.\r
1084                 var preHtml = block.getHtml();\r
1085 \r
1086                 // 1. Trim head/tail spaces, they're not visible.\r
1087                 preHtml = replace( preHtml, /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '' );\r
1088                 // 2. Delete ANSI whitespaces immediately before and after <BR> because\r
1089                 //    they are not visible.\r
1090                 preHtml = preHtml.replace( /[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi, '$1' );\r
1091                 // 3. Compress other ANSI whitespaces since they're only visible as one\r
1092                 //    single space previously.\r
1093                 // 4. Convert &nbsp; to spaces since &nbsp; is no longer needed in <PRE>.\r
1094                 preHtml = preHtml.replace( /([ \t\n\r]+|&nbsp;)/g, ' ' );\r
1095                 // 5. Convert any <BR /> to \n. This must not be done earlier because\r
1096                 //    the \n would then get compressed.\r
1097                 preHtml = preHtml.replace( /<br\b[^>]*>/gi, '\n' );\r
1098 \r
1099                 // Krugle: IE normalizes innerHTML to <pre>, breaking whitespaces.\r
1100                 if ( CKEDITOR.env.ie )\r
1101                 {\r
1102                         var temp = block.getDocument().createElement( 'div' );\r
1103                         temp.append( newBlock );\r
1104                         newBlock.$.outerHTML =  '<pre>' + preHtml + '</pre>';\r
1105                         newBlock.copyAttributes( temp.getFirst() );\r
1106                         newBlock = temp.getFirst().remove();\r
1107                 }\r
1108                 else\r
1109                         newBlock.setHtml( preHtml );\r
1110 \r
1111                 return newBlock;\r
1112         }\r
1113 \r
1114         // Removes a style from an element itself, don't care about its subtree.\r
1115         function removeFromElement( style, element )\r
1116         {\r
1117                 var def = style._.definition,\r
1118                         attributes = CKEDITOR.tools.extend( {}, def.attributes, getOverrides( style )[ element.getName() ] ),\r
1119                         styles = def.styles,\r
1120                         // If the style is only about the element itself, we have to remove the element.\r
1121                         removeEmpty = CKEDITOR.tools.isEmpty( attributes ) && CKEDITOR.tools.isEmpty( styles );\r
1122 \r
1123                 // Remove definition attributes/style from the elemnt.\r
1124                 for ( var attName in attributes )\r
1125                 {\r
1126                         // The 'class' element value must match (#1318).\r
1127                         if ( ( attName == 'class' || style._.definition.fullMatch )\r
1128                                 && element.getAttribute( attName ) != normalizeProperty( attName, attributes[ attName ] ) )\r
1129                                 continue;\r
1130                         removeEmpty = element.hasAttribute( attName );\r
1131                         element.removeAttribute( attName );\r
1132                 }\r
1133 \r
1134                 for ( var styleName in styles )\r
1135                 {\r
1136                         // Full match style insist on having fully equivalence. (#5018)\r
1137                         if ( style._.definition.fullMatch\r
1138                                 && element.getStyle( styleName ) != normalizeProperty( styleName, styles[ styleName ], true ) )\r
1139                                 continue;\r
1140 \r
1141                         removeEmpty = removeEmpty || !!element.getStyle( styleName );\r
1142                         element.removeStyle( styleName );\r
1143                 }\r
1144 \r
1145                 if ( removeEmpty )\r
1146                 {\r
1147                         !CKEDITOR.dtd.$block[ element.getName() ] || style._.enterMode == CKEDITOR.ENTER_BR && !element.hasAttributes() ?\r
1148                                 removeNoAttribsElement( element ) :\r
1149                                 element.renameNode( style._.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );\r
1150                 }\r
1151         }\r
1152 \r
1153         // Removes a style from inside an element.\r
1154         function removeFromInsideElement( style, element )\r
1155         {\r
1156                 var def = style._.definition,\r
1157                         attribs = def.attributes,\r
1158                         styles = def.styles,\r
1159                         overrides = getOverrides( style ),\r
1160                         innerElements = element.getElementsByTag( style.element );\r
1161 \r
1162                 for ( var i = innerElements.count(); --i >= 0 ; )\r
1163                         removeFromElement( style,  innerElements.getItem( i ) );\r
1164 \r
1165                 // Now remove any other element with different name that is\r
1166                 // defined to be overriden.\r
1167                 for ( var overrideElement in overrides )\r
1168                 {\r
1169                         if ( overrideElement != style.element )\r
1170                         {\r
1171                                 innerElements = element.getElementsByTag( overrideElement ) ;\r
1172                                 for ( i = innerElements.count() - 1 ; i >= 0 ; i-- )\r
1173                                 {\r
1174                                         var innerElement = innerElements.getItem( i );\r
1175                                         removeOverrides( innerElement, overrides[ overrideElement ] ) ;\r
1176                                 }\r
1177                         }\r
1178                 }\r
1179         }\r
1180 \r
1181         /**\r
1182          *  Remove overriding styles/attributes from the specific element.\r
1183          *  Note: Remove the element if no attributes remain.\r
1184          * @param {Object} element\r
1185          * @param {Object} overrides\r
1186          */\r
1187         function removeOverrides( element, overrides )\r
1188         {\r
1189                 var attributes = overrides && overrides.attributes ;\r
1190 \r
1191                 if ( attributes )\r
1192                 {\r
1193                         for ( var i = 0 ; i < attributes.length ; i++ )\r
1194                         {\r
1195                                 var attName = attributes[i][0], actualAttrValue ;\r
1196 \r
1197                                 if ( ( actualAttrValue = element.getAttribute( attName ) ) )\r
1198                                 {\r
1199                                         var attValue = attributes[i][1] ;\r
1200 \r
1201                                         // Remove the attribute if:\r
1202                                         //    - The override definition value is null ;\r
1203                                         //    - The override definition valie is a string that\r
1204                                         //      matches the attribute value exactly.\r
1205                                         //    - The override definition value is a regex that\r
1206                                         //      has matches in the attribute value.\r
1207                                         if ( attValue === null ||\r
1208                                                         ( attValue.test && attValue.test( actualAttrValue ) ) ||\r
1209                                                         ( typeof attValue == 'string' && actualAttrValue == attValue ) )\r
1210                                                 element.removeAttribute( attName ) ;\r
1211                                 }\r
1212                         }\r
1213                 }\r
1214 \r
1215                 removeNoAttribsElement( element );\r
1216         }\r
1217 \r
1218         // If the element has no more attributes, remove it.\r
1219         function removeNoAttribsElement( element )\r
1220         {\r
1221                 // If no more attributes remained in the element, remove it,\r
1222                 // leaving its children.\r
1223                 if ( !element.hasAttributes() )\r
1224                 {\r
1225                         if ( CKEDITOR.dtd.$block[ element.getName() ] )\r
1226                         {\r
1227                                 var previous = element.getPrevious( nonWhitespaces ),\r
1228                                                 next = element.getNext( nonWhitespaces );\r
1229 \r
1230                                 if ( previous && ( previous.type == CKEDITOR.NODE_TEXT || !previous.isBlockBoundary( { br : 1 } ) ) )\r
1231                                         element.append( 'br', 1 );\r
1232                                 if ( next && ( next.type == CKEDITOR.NODE_TEXT || !next.isBlockBoundary( { br : 1 } ) ) )\r
1233                                         element.append( 'br' );\r
1234 \r
1235                                 element.remove( true );\r
1236                         }\r
1237                         else\r
1238                         {\r
1239                                 // Removing elements may open points where merging is possible,\r
1240                                 // so let's cache the first and last nodes for later checking.\r
1241                                 var firstChild = element.getFirst();\r
1242                                 var lastChild = element.getLast();\r
1243 \r
1244                                 element.remove( true );\r
1245 \r
1246                                 if ( firstChild )\r
1247                                 {\r
1248                                         // Check the cached nodes for merging.\r
1249                                         firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.mergeSiblings();\r
1250 \r
1251                                         if ( lastChild && !firstChild.equals( lastChild )\r
1252                                                         && lastChild.type == CKEDITOR.NODE_ELEMENT )\r
1253                                                 lastChild.mergeSiblings();\r
1254                                 }\r
1255 \r
1256                         }\r
1257                 }\r
1258         }\r
1259 \r
1260         function getElement( style, targetDocument, element )\r
1261         {\r
1262                 var el,\r
1263                         def = style._.definition,\r
1264                         elementName = style.element;\r
1265 \r
1266                 // The "*" element name will always be a span for this function.\r
1267                 if ( elementName == '*' )\r
1268                         elementName = 'span';\r
1269 \r
1270                 // Create the element.\r
1271                 el = new CKEDITOR.dom.element( elementName, targetDocument );\r
1272 \r
1273                 // #6226: attributes should be copied before the new ones are applied\r
1274                 if ( element )\r
1275                         element.copyAttributes( el );\r
1276 \r
1277                 el = setupElement( el, style );\r
1278 \r
1279                 // Avoid ID duplication.\r
1280                 if ( targetDocument.getCustomData( 'doc_processing_style' ) && el.hasAttribute( 'id' ) )\r
1281                         el.removeAttribute( 'id' );\r
1282                 else\r
1283                         targetDocument.setCustomData( 'doc_processing_style', 1 );\r
1284 \r
1285                 return el;\r
1286         }\r
1287 \r
1288         function setupElement( el, style )\r
1289         {\r
1290                 var def = style._.definition,\r
1291                         attributes = def.attributes,\r
1292                         styles = CKEDITOR.style.getStyleText( def );\r
1293 \r
1294                 // Assign all defined attributes.\r
1295                 if ( attributes )\r
1296                 {\r
1297                         for ( var att in attributes )\r
1298                         {\r
1299                                 el.setAttribute( att, attributes[ att ] );\r
1300                         }\r
1301                 }\r
1302 \r
1303                 // Assign all defined styles.\r
1304                 if( styles )\r
1305                         el.setAttribute( 'style', styles );\r
1306 \r
1307                 return el;\r
1308         }\r
1309 \r
1310         function replaceVariables( list, variablesValues )\r
1311         {\r
1312                 for ( var item in list )\r
1313                 {\r
1314                         list[ item ] = list[ item ].replace( varRegex, function( match, varName )\r
1315                                 {\r
1316                                         return variablesValues[ varName ];\r
1317                                 });\r
1318                 }\r
1319         }\r
1320 \r
1321         // Returns an object that can be used for style matching comparison.\r
1322         // Attributes names and values are all lowercased, and the styles get\r
1323         // merged with the style attribute.\r
1324         function getAttributesForComparison( styleDefinition )\r
1325         {\r
1326                 // If we have already computed it, just return it.\r
1327                 var attribs = styleDefinition._AC;\r
1328                 if ( attribs )\r
1329                         return attribs;\r
1330 \r
1331                 attribs = {};\r
1332 \r
1333                 var length = 0;\r
1334 \r
1335                 // Loop through all defined attributes.\r
1336                 var styleAttribs = styleDefinition.attributes;\r
1337                 if ( styleAttribs )\r
1338                 {\r
1339                         for ( var styleAtt in styleAttribs )\r
1340                         {\r
1341                                 length++;\r
1342                                 attribs[ styleAtt ] = styleAttribs[ styleAtt ];\r
1343                         }\r
1344                 }\r
1345 \r
1346                 // Includes the style definitions.\r
1347                 var styleText = CKEDITOR.style.getStyleText( styleDefinition );\r
1348                 if ( styleText )\r
1349                 {\r
1350                         if ( !attribs[ 'style' ] )\r
1351                                 length++;\r
1352                         attribs[ 'style' ] = styleText;\r
1353                 }\r
1354 \r
1355                 // Appends the "length" information to the object.\r
1356                 attribs._length = length;\r
1357 \r
1358                 // Return it, saving it to the next request.\r
1359                 return ( styleDefinition._AC = attribs );\r
1360         }\r
1361 \r
1362         /**\r
1363          * Get the the collection used to compare the elements and attributes,\r
1364          * defined in this style overrides, with other element. All information in\r
1365          * it is lowercased.\r
1366          * @param {CKEDITOR.style} style\r
1367          */\r
1368         function getOverrides( style )\r
1369         {\r
1370                 if ( style._.overrides )\r
1371                         return style._.overrides;\r
1372 \r
1373                 var overrides = ( style._.overrides = {} ),\r
1374                         definition = style._.definition.overrides;\r
1375 \r
1376                 if ( definition )\r
1377                 {\r
1378                         // The override description can be a string, object or array.\r
1379                         // Internally, well handle arrays only, so transform it if needed.\r
1380                         if ( !CKEDITOR.tools.isArray( definition ) )\r
1381                                 definition = [ definition ];\r
1382 \r
1383                         // Loop through all override definitions.\r
1384                         for ( var i = 0 ; i < definition.length ; i++ )\r
1385                         {\r
1386                                 var override = definition[i];\r
1387                                 var elementName;\r
1388                                 var overrideEl;\r
1389                                 var attrs;\r
1390 \r
1391                                 // If can be a string with the element name.\r
1392                                 if ( typeof override == 'string' )\r
1393                                         elementName = override.toLowerCase();\r
1394                                 // Or an object.\r
1395                                 else\r
1396                                 {\r
1397                                         elementName = override.element ? override.element.toLowerCase() : style.element;\r
1398                                         attrs = override.attributes;\r
1399                                 }\r
1400 \r
1401                                 // We can have more than one override definition for the same\r
1402                                 // element name, so we attempt to simply append information to\r
1403                                 // it if it already exists.\r
1404                                 overrideEl = overrides[ elementName ] || ( overrides[ elementName ] = {} );\r
1405 \r
1406                                 if ( attrs )\r
1407                                 {\r
1408                                         // The returning attributes list is an array, because we\r
1409                                         // could have different override definitions for the same\r
1410                                         // attribute name.\r
1411                                         var overrideAttrs = ( overrideEl.attributes = overrideEl.attributes || new Array() );\r
1412                                         for ( var attName in attrs )\r
1413                                         {\r
1414                                                 // Each item in the attributes array is also an array,\r
1415                                                 // where [0] is the attribute name and [1] is the\r
1416                                                 // override value.\r
1417                                                 overrideAttrs.push( [ attName.toLowerCase(), attrs[ attName ] ] );\r
1418                                         }\r
1419                                 }\r
1420                         }\r
1421                 }\r
1422 \r
1423                 return overrides;\r
1424         }\r
1425 \r
1426         // Make the comparison of attribute value easier by standardizing it.\r
1427         function normalizeProperty( name, value, isStyle )\r
1428         {\r
1429                 var temp = new CKEDITOR.dom.element( 'span' );\r
1430                 temp [ isStyle ? 'setStyle' : 'setAttribute' ]( name, value );\r
1431                 return temp[ isStyle ? 'getStyle' : 'getAttribute' ]( name );\r
1432         }\r
1433 \r
1434         // Make the comparison of style text easier by standardizing it.\r
1435         function normalizeCssText( unparsedCssText, nativeNormalize )\r
1436         {\r
1437                 var styleText;\r
1438                 if ( nativeNormalize !== false )\r
1439                 {\r
1440                         // Injects the style in a temporary span object, so the browser parses it,\r
1441                         // retrieving its final format.\r
1442                         var temp = new CKEDITOR.dom.element( 'span' );\r
1443                         temp.setAttribute( 'style', unparsedCssText );\r
1444                         styleText = temp.getAttribute( 'style' ) || '';\r
1445                 }\r
1446                 else\r
1447                         styleText = unparsedCssText;\r
1448 \r
1449                 // Shrinking white-spaces around colon and semi-colon (#4147).\r
1450                 // Compensate tail semi-colon.\r
1451                 return styleText.replace( /\s*([;:])\s*/, '$1' )\r
1452                                                          .replace( /([^\s;])$/, '$1;')\r
1453                                                         // Trimming spaces after comma(#4107),\r
1454                                                         // remove quotations(#6403),\r
1455                                                         // mostly for differences on "font-family".\r
1456                                                          .replace( /,\s+/g, ',' )\r
1457                                                          .replace( /\"/g,'' )\r
1458                                                          .toLowerCase();\r
1459         }\r
1460 \r
1461         // Turn inline style text properties into one hash.\r
1462         function parseStyleText( styleText )\r
1463         {\r
1464                 var retval = {};\r
1465                 styleText\r
1466                    .replace( /&quot;/g, '"' )\r
1467                    .replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value )\r
1468                 {\r
1469                         retval[ name ] = value;\r
1470                 } );\r
1471                 return retval;\r
1472         }\r
1473 \r
1474         /**\r
1475          * Compare two bunch of styles, with the speciality that value 'inherit'\r
1476          * is treated as a wildcard which will match any value.\r
1477          * @param {Object|String} source\r
1478          * @param {Object|String} target\r
1479          */\r
1480         function compareCssText( source, target )\r
1481         {\r
1482                 typeof source == 'string' && ( source = parseStyleText( source ) );\r
1483                 typeof target == 'string' && ( target = parseStyleText( target ) );\r
1484                 for( var name in source )\r
1485                 {\r
1486                         if ( !( name in target &&\r
1487                                         ( target[ name ] == source[ name ]\r
1488                                                 || source[ name ] == 'inherit'\r
1489                                                 || target[ name ] == 'inherit' ) ) )\r
1490                         {\r
1491                                 return false;\r
1492                         }\r
1493                 }\r
1494                 return true;\r
1495         }\r
1496 \r
1497         function applyStyle( document, remove )\r
1498         {\r
1499                 var selection = document.getSelection(),\r
1500                         ranges = selection.getRanges(),\r
1501                         func = remove ? this.removeFromRange : this.applyToRange,\r
1502                         range;\r
1503 \r
1504                 var iterator = ranges.createIterator();\r
1505                 while ( ( range = iterator.getNextRange() ) )\r
1506                         func.call( this, range );\r
1507 \r
1508                 selection.selectRanges( ranges );\r
1509 \r
1510                 document.removeCustomData( 'doc_processing_style' );\r
1511         }\r
1512 })();\r
1513 \r
1514 CKEDITOR.styleCommand = function( style )\r
1515 {\r
1516         this.style = style;\r
1517 };\r
1518 \r
1519 CKEDITOR.styleCommand.prototype.exec = function( editor )\r
1520 {\r
1521         editor.focus();\r
1522 \r
1523         var doc = editor.document;\r
1524 \r
1525         if ( doc )\r
1526         {\r
1527                 if ( this.state == CKEDITOR.TRISTATE_OFF )\r
1528                         this.style.apply( doc );\r
1529                 else if ( this.state == CKEDITOR.TRISTATE_ON )\r
1530                         this.style.remove( doc );\r
1531         }\r
1532 \r
1533         return !!doc;\r
1534 };\r
1535 \r
1536 /**\r
1537  * Manages styles registration and loading. See also {@link CKEDITOR.config.stylesSet}.\r
1538  * @namespace\r
1539  * @augments CKEDITOR.resourceManager\r
1540  * @constructor\r
1541  * @since 3.2\r
1542  * @example\r
1543  * // The set of styles for the <b>Styles</b> combo\r
1544  * CKEDITOR.stylesSet.add( 'default',\r
1545  * [\r
1546  *      // Block Styles\r
1547  *      { name : 'Blue Title'           , element : 'h3', styles : { 'color' : 'Blue' } },\r
1548  *      { name : 'Red Title'            , element : 'h3', styles : { 'color' : 'Red' } },\r
1549  *\r
1550  *      // Inline Styles\r
1551  *      { name : 'Marker: Yellow'       , element : 'span', styles : { 'background-color' : 'Yellow' } },\r
1552  *      { name : 'Marker: Green'        , element : 'span', styles : { 'background-color' : 'Lime' } },\r
1553  *\r
1554  *      // Object Styles\r
1555  *      {\r
1556  *              name : 'Image on Left',\r
1557  *              element : 'img',\r
1558  *              attributes :\r
1559  *              {\r
1560  *                      'style' : 'padding: 5px; margin-right: 5px',\r
1561  *                      'border' : '2',\r
1562  *                      'align' : 'left'\r
1563  *              }\r
1564  *      }\r
1565  * ]);\r
1566  */\r
1567 CKEDITOR.stylesSet = new CKEDITOR.resourceManager( '', 'stylesSet' );\r
1568 \r
1569 // Backward compatibility (#5025).\r
1570 CKEDITOR.addStylesSet = CKEDITOR.tools.bind( CKEDITOR.stylesSet.add, CKEDITOR.stylesSet );\r
1571 CKEDITOR.loadStylesSet = function( name, url, callback )\r
1572         {\r
1573                 CKEDITOR.stylesSet.addExternal( name, url, '' );\r
1574                 CKEDITOR.stylesSet.load( name, callback );\r
1575         };\r
1576 \r
1577 \r
1578 /**\r
1579  * Gets the current styleSet for this instance\r
1580  * @param {Function} callback The function to be called with the styles data.\r
1581  * @example\r
1582  * editor.getStylesSet( function( stylesDefinitions ) {} );\r
1583  */\r
1584 CKEDITOR.editor.prototype.getStylesSet = function( callback )\r
1585 {\r
1586         if ( !this._.stylesDefinitions )\r
1587         {\r
1588                 var editor = this,\r
1589                         // Respect the backwards compatible definition entry\r
1590                         configStyleSet = editor.config.stylesCombo_stylesSet || editor.config.stylesSet || 'default';\r
1591 \r
1592                 // #5352 Allow to define the styles directly in the config object\r
1593                 if ( configStyleSet instanceof Array )\r
1594                 {\r
1595                         editor._.stylesDefinitions = configStyleSet;\r
1596                         callback( configStyleSet );\r
1597                         return;\r
1598                 }\r
1599 \r
1600                 var     partsStylesSet = configStyleSet.split( ':' ),\r
1601                         styleSetName = partsStylesSet[ 0 ],\r
1602                         externalPath = partsStylesSet[ 1 ],\r
1603                         pluginPath = CKEDITOR.plugins.registered.styles.path;\r
1604 \r
1605                 CKEDITOR.stylesSet.addExternal( styleSetName,\r
1606                                 externalPath ?\r
1607                                         partsStylesSet.slice( 1 ).join( ':' ) :\r
1608                                         pluginPath + 'styles/' + styleSetName + '.js', '' );\r
1609 \r
1610                 CKEDITOR.stylesSet.load( styleSetName, function( stylesSet )\r
1611                         {\r
1612                                 editor._.stylesDefinitions = stylesSet[ styleSetName ];\r
1613                                 callback( editor._.stylesDefinitions );\r
1614                         } ) ;\r
1615         }\r
1616         else\r
1617                 callback( this._.stylesDefinitions );\r
1618 };\r
1619 \r
1620 /**\r
1621  * Indicates that fully selected read-only elements will be included when\r
1622  * applying the style (for inline styles only).\r
1623  * @name CKEDITOR.style.includeReadonly\r
1624  * @type Boolean\r
1625  * @default false\r
1626  * @since 3.5\r
1627  */\r
1628 \r
1629  /**\r
1630   * Disables inline styling on read-only elements.\r
1631   * @name CKEDITOR.config.disableReadonlyStyling\r
1632   * @type Boolean\r
1633   * @default false\r
1634   * @since 3.5\r
1635   */\r
1636 \r
1637 /**\r
1638  * The "styles definition set" to use in the editor. They will be used in the\r
1639  * styles combo and the Style selector of the div container. <br>\r
1640  * The styles may be defined in the page containing the editor, or can be\r
1641  * loaded on demand from an external file. In the second case, if this setting\r
1642  * contains only a name, the styles definition file will be loaded from the\r
1643  * "styles" folder inside the styles plugin folder.\r
1644  * Otherwise, this setting has the "name:url" syntax, making it\r
1645  * possible to set the URL from which loading the styles file.<br>\r
1646  * Previously this setting was available as config.stylesCombo_stylesSet<br>\r
1647  * @name CKEDITOR.config.stylesSet\r
1648  * @type String|Array\r
1649  * @default 'default'\r
1650  * @since 3.3\r
1651  * @example\r
1652  * // Load from the styles' styles folder (mystyles.js file).\r
1653  * config.stylesSet = 'mystyles';\r
1654  * @example\r
1655  * // Load from a relative URL.\r
1656  * config.stylesSet = 'mystyles:/editorstyles/styles.js';\r
1657  * @example\r
1658  * // Load from a full URL.\r
1659  * config.stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js';\r
1660  * @example\r
1661  * // Load from a list of definitions.\r
1662  * config.stylesSet = [\r
1663  *  { name : 'Strong Emphasis', element : 'strong' },\r
1664  * { name : 'Emphasis', element : 'em' }, ... ];\r
1665  */\r