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