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