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