JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
vanilla ckeditor-3.6.3
[ckeditor.git] / _source / plugins / styles / plugin.js
1 /*\r
2 Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license\r
4 */\r
5 \r
6 CKEDITOR.plugins.add( 'styles',\r
7 {\r
8         requires : [ 'selection' ],\r
9         init : function( editor )\r
10         {\r
11                 // This doesn't look like correct, but it's the safest way to proper\r
12                 // pass the disableReadonlyStyling configuration to the style system\r
13                 // without having to change any method signature in the API. (#6103)\r
14                 editor.on( 'contentDom', function()\r
15                         {\r
16                                 editor.document.setCustomData( 'cke_includeReadonly', !editor.config.disableReadonlyStyling );\r
17                         });\r
18         }\r
19 });\r
20 \r
21 /**\r
22  * Registers a function to be called whenever the selection position changes in the\r
23  * editing area. The current state is passed to the function. The possible\r
24  * states are {@link CKEDITOR.TRISTATE_ON} and {@link CKEDITOR.TRISTATE_OFF}.\r
25  * @param {CKEDITOR.style} style The style to be watched.\r
26  * @param {Function} callback The function to be called.\r
27  * @example\r
28  * // Create a style object for the <b> element.\r
29  * var style = new CKEDITOR.style( { element : 'b' } );\r
30  * var editor = CKEDITOR.instances.editor1;\r
31  * editor.attachStyleStateChange( style, function( state )\r
32  *     {\r
33  *         if ( state == CKEDITOR.TRISTATE_ON )\r
34  *             alert( 'The current state for the B element is ON' );\r
35  *         else\r
36  *             alert( 'The current state for the B element is OFF' );\r
37  *     });\r
38  */\r
39 CKEDITOR.editor.prototype.attachStyleStateChange = function( style, callback )\r
40 {\r
41         // Try to get the list of attached callbacks.\r
42         var styleStateChangeCallbacks = this._.styleStateChangeCallbacks;\r
43 \r
44         // If it doesn't exist, it means this is the first call. So, let's create\r
45         // all the structure to manage the style checks and the callback calls.\r
46         if ( !styleStateChangeCallbacks )\r
47         {\r
48                 // Create the callbacks array.\r
49                 styleStateChangeCallbacks = this._.styleStateChangeCallbacks = [];\r
50 \r
51                 // Attach to the selectionChange event, so we can check the styles at\r
52                 // that point.\r
53                 this.on( 'selectionChange', function( ev )\r
54                         {\r
55                                 // Loop throw all registered callbacks.\r
56                                 for ( var i = 0 ; i < styleStateChangeCallbacks.length ; i++ )\r
57                                 {\r
58                                         var callback = styleStateChangeCallbacks[ i ];\r
59 \r
60                                         // Check the current state for the style defined for that\r
61                                         // callback.\r
62                                         var currentState = callback.style.checkActive( ev.data.path ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF;\r
63 \r
64                                         // Call the callback function, passing the current\r
65                                         // state to it.\r
66                                         callback.fn.call( this, currentState );\r
67                                 }\r
68                         });\r
69         }\r
70 \r
71         // Save the callback info, so it can be checked on the next occurrence of\r
72         // selectionChange.\r
73         styleStateChangeCallbacks.push( { style : style, fn : callback } );\r
74 };\r
75 \r
76 CKEDITOR.STYLE_BLOCK = 1;\r
77 CKEDITOR.STYLE_INLINE = 2;\r
78 CKEDITOR.STYLE_OBJECT = 3;\r
79 \r
80 (function()\r
81 {\r
82         var blockElements       = { address:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1,section:1,header:1,footer:1,nav:1,article:1,aside:1,figure:1,dialog:1,hgroup:1,time:1,meter:1,menu:1,command:1,keygen:1,output:1,progress:1,details:1,datagrid:1,datalist:1 },\r
83                 objectElements  = { a:1,embed:1,hr:1,img:1,li:1,object:1,ol:1,table:1,td:1,tr:1,th:1,ul:1,dl:1,dt:1,dd:1,form:1,audio:1,video:1 };\r
84 \r
85         var semicolonFixRegex = /\s*(?:;\s*|$)/,\r
86                 varRegex = /#\((.+?)\)/g;\r
87 \r
88         var notBookmark = CKEDITOR.dom.walker.bookmark( 0, 1 ),\r
89                 nonWhitespaces = CKEDITOR.dom.walker.whitespaces( 1 );\r
90 \r
91         CKEDITOR.style = function( styleDefinition, variablesValues )\r
92         {\r
93                 if ( variablesValues )\r
94                 {\r
95                         styleDefinition = CKEDITOR.tools.clone( styleDefinition );\r
96 \r
97                         replaceVariables( styleDefinition.attributes, variablesValues );\r
98                         replaceVariables( styleDefinition.styles, variablesValues );\r
99                 }\r
100 \r
101                 var element = this.element = styleDefinition.element ?\r
102                                 ( typeof styleDefinition.element == 'string' ? styleDefinition.element.toLowerCase() : styleDefinition.element )\r
103                                 : '*';\r
104 \r
105                 this.type =\r
106                         blockElements[ element ] ?\r
107                                 CKEDITOR.STYLE_BLOCK\r
108                         : objectElements[ element ] ?\r
109                                 CKEDITOR.STYLE_OBJECT\r
110                         :\r
111                                 CKEDITOR.STYLE_INLINE;\r
112 \r
113                 // If the 'element' property is an object with a set of possible element, it will be applied like an object style: only to existing elements\r
114                 if ( typeof this.element == 'object' )\r
115                         this.type = CKEDITOR.STYLE_OBJECT;\r
116 \r
117                 this._ =\r
118                 {\r
119                         definition : styleDefinition\r
120                 };\r
121         };\r
122 \r
123         CKEDITOR.style.prototype =\r
124         {\r
125                 apply : function( document )\r
126                 {\r
127                         applyStyle.call( this, document, false );\r
128                 },\r
129 \r
130                 remove : function( document )\r
131                 {\r
132                         applyStyle.call( this, document, true );\r
133                 },\r
134 \r
135                 applyToRange : function( range )\r
136                 {\r
137                         return ( this.applyToRange =\r
138                                                 this.type == CKEDITOR.STYLE_INLINE ?\r
139                                                         applyInlineStyle\r
140                                                 : this.type == CKEDITOR.STYLE_BLOCK ?\r
141                                                         applyBlockStyle\r
142                                                 : this.type == CKEDITOR.STYLE_OBJECT ?\r
143                                                         applyObjectStyle\r
144                                                 : null ).call( this, range );\r
145                 },\r
146 \r
147                 removeFromRange : function( range )\r
148                 {\r
149                         return ( this.removeFromRange =\r
150                                                 this.type == CKEDITOR.STYLE_INLINE ?\r
151                                                         removeInlineStyle\r
152                                                 : this.type == CKEDITOR.STYLE_BLOCK ?\r
153                                                         removeBlockStyle\r
154                                                 : this.type == CKEDITOR.STYLE_OBJECT ?\r
155                                                         removeObjectStyle\r
156                                                 : null ).call( this, range );\r
157                 },\r
158 \r
159                 applyToObject : function( element )\r
160                 {\r
161                         setupElement( element, this );\r
162                 },\r
163 \r
164                 /**\r
165                  * Get the style state inside an element path. Returns "true" if the\r
166                  * element is active in the path.\r
167                  */\r
168                 checkActive : function( elementPath )\r
169                 {\r
170                         switch ( this.type )\r
171                         {\r
172                                 case CKEDITOR.STYLE_BLOCK :\r
173                                         return this.checkElementRemovable( elementPath.block || elementPath.blockLimit, true );\r
174 \r
175                                 case CKEDITOR.STYLE_OBJECT :\r
176                                 case CKEDITOR.STYLE_INLINE :\r
177 \r
178                                         var elements = elementPath.elements;\r
179 \r
180                                         for ( var i = 0, element ; i < elements.length ; i++ )\r
181                                         {\r
182                                                 element = elements[ i ];\r
183 \r
184                                                 if ( this.type == CKEDITOR.STYLE_INLINE\r
185                                                           && ( element == elementPath.block || element == elementPath.blockLimit ) )\r
186                                                         continue;\r
187 \r
188                                                 if( this.type == CKEDITOR.STYLE_OBJECT )\r
189                                                 {\r
190                                                         var name = element.getName();\r
191                                                         if ( !( typeof this.element == 'string' ? name == this.element : name in this.element ) )\r
192                                                                 continue;\r
193                                                 }\r
194 \r
195                                                 if ( this.checkElementRemovable( element, true ) )\r
196                                                         return true;\r
197                                         }\r
198                         }\r
199                         return false;\r
200                 },\r
201 \r
202                 /**\r
203                  * Whether this style can be applied at the element path.\r
204                  * @param elementPath\r
205                  */\r
206                 checkApplicable : function( elementPath )\r
207                 {\r
208                         switch ( this.type )\r
209                         {\r
210                                 case CKEDITOR.STYLE_INLINE :\r
211                                 case CKEDITOR.STYLE_BLOCK :\r
212                                         break;\r
213 \r
214                                 case CKEDITOR.STYLE_OBJECT :\r
215                                         return elementPath.lastElement.getAscendant( this.element, true );\r
216                         }\r
217 \r
218                         return true;\r
219                 },\r
220 \r
221                 // 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 = def.attributes,\r
1136                         styles = def.styles,\r
1137                         overrides = getOverrides( style )[ element.getName() ],\r
1138                         // If the style is only about the element itself, we have to remove the element.\r
1139                         removeEmpty = CKEDITOR.tools.isEmpty( attributes ) && CKEDITOR.tools.isEmpty( styles );\r
1140 \r
1141                 // Remove definition attributes/style from the elemnt.\r
1142                 for ( var attName in attributes )\r
1143                 {\r
1144                         // The 'class' element value must match (#1318).\r
1145                         if ( ( attName == 'class' || style._.definition.fullMatch )\r
1146                                 && element.getAttribute( attName ) != normalizeProperty( attName, attributes[ attName ] ) )\r
1147                                 continue;\r
1148                         removeEmpty = element.hasAttribute( attName );\r
1149                         element.removeAttribute( attName );\r
1150                 }\r
1151 \r
1152                 for ( var styleName in styles )\r
1153                 {\r
1154                         // Full match style insist on having fully equivalence. (#5018)\r
1155                         if ( style._.definition.fullMatch\r
1156                                 && element.getStyle( styleName ) != normalizeProperty( styleName, styles[ styleName ], true ) )\r
1157                                 continue;\r
1158 \r
1159                         removeEmpty = removeEmpty || !!element.getStyle( styleName );\r
1160                         element.removeStyle( styleName );\r
1161                 }\r
1162 \r
1163                 // Remove overrides, but don't remove the element if it's a block element\r
1164                 removeOverrides( element, overrides, blockElements[ element.getName() ] ) ;\r
1165 \r
1166                 if ( removeEmpty )\r
1167                 {\r
1168                         !CKEDITOR.dtd.$block[ element.getName() ] || style._.enterMode == CKEDITOR.ENTER_BR && !element.hasAttributes() ?\r
1169                                 removeNoAttribsElement( element ) :\r
1170                                 element.renameNode( style._.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );\r
1171                 }\r
1172         }\r
1173 \r
1174         // Removes a style from inside an element.\r
1175         function removeFromInsideElement( style, element )\r
1176         {\r
1177                 var def = style._.definition,\r
1178                         attribs = def.attributes,\r
1179                         styles = def.styles,\r
1180                         overrides = getOverrides( style ),\r
1181                         innerElements = element.getElementsByTag( style.element );\r
1182 \r
1183                 for ( var i = innerElements.count(); --i >= 0 ; )\r
1184                         removeFromElement( style,  innerElements.getItem( i ) );\r
1185 \r
1186                 // Now remove any other element with different name that is\r
1187                 // defined to be overriden.\r
1188                 for ( var overrideElement in overrides )\r
1189                 {\r
1190                         if ( overrideElement != style.element )\r
1191                         {\r
1192                                 innerElements = element.getElementsByTag( overrideElement ) ;\r
1193                                 for ( i = innerElements.count() - 1 ; i >= 0 ; i-- )\r
1194                                 {\r
1195                                         var innerElement = innerElements.getItem( i );\r
1196                                         removeOverrides( innerElement, overrides[ overrideElement ] ) ;\r
1197                                 }\r
1198                         }\r
1199                 }\r
1200         }\r
1201 \r
1202         /**\r
1203          *  Remove overriding styles/attributes from the specific element.\r
1204          *  Note: Remove the element if no attributes remain.\r
1205          * @param {Object} element\r
1206          * @param {Object} overrides\r
1207          * @param {Boolean} Don't remove the element\r
1208          */\r
1209         function removeOverrides( element, overrides, dontRemove )\r
1210         {\r
1211                 var attributes = overrides && overrides.attributes ;\r
1212 \r
1213                 if ( attributes )\r
1214                 {\r
1215                         for ( var i = 0 ; i < attributes.length ; i++ )\r
1216                         {\r
1217                                 var attName = attributes[i][0], actualAttrValue ;\r
1218 \r
1219                                 if ( ( actualAttrValue = element.getAttribute( attName ) ) )\r
1220                                 {\r
1221                                         var attValue = attributes[i][1] ;\r
1222 \r
1223                                         // Remove the attribute if:\r
1224                                         //    - The override definition value is null ;\r
1225                                         //    - The override definition valie is a string that\r
1226                                         //      matches the attribute value exactly.\r
1227                                         //    - The override definition value is a regex that\r
1228                                         //      has matches in the attribute value.\r
1229                                         if ( attValue === null ||\r
1230                                                         ( attValue.test && attValue.test( actualAttrValue ) ) ||\r
1231                                                         ( typeof attValue == 'string' && actualAttrValue == attValue ) )\r
1232                                                 element.removeAttribute( attName ) ;\r
1233                                 }\r
1234                         }\r
1235                 }\r
1236 \r
1237                 if ( !dontRemove )\r
1238                         removeNoAttribsElement( element );\r
1239         }\r
1240 \r
1241         // If the element has no more attributes, remove it.\r
1242         function removeNoAttribsElement( element )\r
1243         {\r
1244                 // If no more attributes remained in the element, remove it,\r
1245                 // leaving its children.\r
1246                 if ( !element.hasAttributes() )\r
1247                 {\r
1248                         if ( CKEDITOR.dtd.$block[ element.getName() ] )\r
1249                         {\r
1250                                 var previous = element.getPrevious( nonWhitespaces ),\r
1251                                                 next = element.getNext( nonWhitespaces );\r
1252 \r
1253                                 if ( previous && ( previous.type == CKEDITOR.NODE_TEXT || !previous.isBlockBoundary( { br : 1 } ) ) )\r
1254                                         element.append( 'br', 1 );\r
1255                                 if ( next && ( next.type == CKEDITOR.NODE_TEXT || !next.isBlockBoundary( { br : 1 } ) ) )\r
1256                                         element.append( 'br' );\r
1257 \r
1258                                 element.remove( true );\r
1259                         }\r
1260                         else\r
1261                         {\r
1262                                 // Removing elements may open points where merging is possible,\r
1263                                 // so let's cache the first and last nodes for later checking.\r
1264                                 var firstChild = element.getFirst();\r
1265                                 var lastChild = element.getLast();\r
1266 \r
1267                                 element.remove( true );\r
1268 \r
1269                                 if ( firstChild )\r
1270                                 {\r
1271                                         // Check the cached nodes for merging.\r
1272                                         firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.mergeSiblings();\r
1273 \r
1274                                         if ( lastChild && !firstChild.equals( lastChild )\r
1275                                                         && lastChild.type == CKEDITOR.NODE_ELEMENT )\r
1276                                                 lastChild.mergeSiblings();\r
1277                                 }\r
1278 \r
1279                         }\r
1280                 }\r
1281         }\r
1282 \r
1283         function getElement( style, targetDocument, element )\r
1284         {\r
1285                 var el,\r
1286                         def = style._.definition,\r
1287                         elementName = style.element;\r
1288 \r
1289                 // The "*" element name will always be a span for this function.\r
1290                 if ( elementName == '*' )\r
1291                         elementName = 'span';\r
1292 \r
1293                 // Create the element.\r
1294                 el = new CKEDITOR.dom.element( elementName, targetDocument );\r
1295 \r
1296                 // #6226: attributes should be copied before the new ones are applied\r
1297                 if ( element )\r
1298                         element.copyAttributes( el );\r
1299 \r
1300                 el = setupElement( el, style );\r
1301 \r
1302                 // Avoid ID duplication.\r
1303                 if ( targetDocument.getCustomData( 'doc_processing_style' ) && el.hasAttribute( 'id' ) )\r
1304                         el.removeAttribute( 'id' );\r
1305                 else\r
1306                         targetDocument.setCustomData( 'doc_processing_style', 1 );\r
1307 \r
1308                 return el;\r
1309         }\r
1310 \r
1311         function setupElement( el, style )\r
1312         {\r
1313                 var def = style._.definition,\r
1314                         attributes = def.attributes,\r
1315                         styles = CKEDITOR.style.getStyleText( def );\r
1316 \r
1317                 // Assign all defined attributes.\r
1318                 if ( attributes )\r
1319                 {\r
1320                         for ( var att in attributes )\r
1321                         {\r
1322                                 el.setAttribute( att, attributes[ att ] );\r
1323                         }\r
1324                 }\r
1325 \r
1326                 // Assign all defined styles.\r
1327                 if( styles )\r
1328                         el.setAttribute( 'style', styles );\r
1329 \r
1330                 return el;\r
1331         }\r
1332 \r
1333         function replaceVariables( list, variablesValues )\r
1334         {\r
1335                 for ( var item in list )\r
1336                 {\r
1337                         list[ item ] = list[ item ].replace( varRegex, function( match, varName )\r
1338                                 {\r
1339                                         return variablesValues[ varName ];\r
1340                                 });\r
1341                 }\r
1342         }\r
1343 \r
1344         // Returns an object that can be used for style matching comparison.\r
1345         // Attributes names and values are all lowercased, and the styles get\r
1346         // merged with the style attribute.\r
1347         function getAttributesForComparison( styleDefinition )\r
1348         {\r
1349                 // If we have already computed it, just return it.\r
1350                 var attribs = styleDefinition._AC;\r
1351                 if ( attribs )\r
1352                         return attribs;\r
1353 \r
1354                 attribs = {};\r
1355 \r
1356                 var length = 0;\r
1357 \r
1358                 // Loop through all defined attributes.\r
1359                 var styleAttribs = styleDefinition.attributes;\r
1360                 if ( styleAttribs )\r
1361                 {\r
1362                         for ( var styleAtt in styleAttribs )\r
1363                         {\r
1364                                 length++;\r
1365                                 attribs[ styleAtt ] = styleAttribs[ styleAtt ];\r
1366                         }\r
1367                 }\r
1368 \r
1369                 // Includes the style definitions.\r
1370                 var styleText = CKEDITOR.style.getStyleText( styleDefinition );\r
1371                 if ( styleText )\r
1372                 {\r
1373                         if ( !attribs[ 'style' ] )\r
1374                                 length++;\r
1375                         attribs[ 'style' ] = styleText;\r
1376                 }\r
1377 \r
1378                 // Appends the "length" information to the object.\r
1379                 attribs._length = length;\r
1380 \r
1381                 // Return it, saving it to the next request.\r
1382                 return ( styleDefinition._AC = attribs );\r
1383         }\r
1384 \r
1385         /**\r
1386          * Get the the collection used to compare the elements and attributes,\r
1387          * defined in this style overrides, with other element. All information in\r
1388          * it is lowercased.\r
1389          * @param {CKEDITOR.style} style\r
1390          */\r
1391         function getOverrides( style )\r
1392         {\r
1393                 if ( style._.overrides )\r
1394                         return style._.overrides;\r
1395 \r
1396                 var overrides = ( style._.overrides = {} ),\r
1397                         definition = style._.definition.overrides;\r
1398 \r
1399                 if ( definition )\r
1400                 {\r
1401                         // The override description can be a string, object or array.\r
1402                         // Internally, well handle arrays only, so transform it if needed.\r
1403                         if ( !CKEDITOR.tools.isArray( definition ) )\r
1404                                 definition = [ definition ];\r
1405 \r
1406                         // Loop through all override definitions.\r
1407                         for ( var i = 0 ; i < definition.length ; i++ )\r
1408                         {\r
1409                                 var override = definition[i];\r
1410                                 var elementName;\r
1411                                 var overrideEl;\r
1412                                 var attrs;\r
1413 \r
1414                                 // If can be a string with the element name.\r
1415                                 if ( typeof override == 'string' )\r
1416                                         elementName = override.toLowerCase();\r
1417                                 // Or an object.\r
1418                                 else\r
1419                                 {\r
1420                                         elementName = override.element ? override.element.toLowerCase() : style.element;\r
1421                                         attrs = override.attributes;\r
1422                                 }\r
1423 \r
1424                                 // We can have more than one override definition for the same\r
1425                                 // element name, so we attempt to simply append information to\r
1426                                 // it if it already exists.\r
1427                                 overrideEl = overrides[ elementName ] || ( overrides[ elementName ] = {} );\r
1428 \r
1429                                 if ( attrs )\r
1430                                 {\r
1431                                         // The returning attributes list is an array, because we\r
1432                                         // could have different override definitions for the same\r
1433                                         // attribute name.\r
1434                                         var overrideAttrs = ( overrideEl.attributes = overrideEl.attributes || new Array() );\r
1435                                         for ( var attName in attrs )\r
1436                                         {\r
1437                                                 // Each item in the attributes array is also an array,\r
1438                                                 // where [0] is the attribute name and [1] is the\r
1439                                                 // override value.\r
1440                                                 overrideAttrs.push( [ attName.toLowerCase(), attrs[ attName ] ] );\r
1441                                         }\r
1442                                 }\r
1443                         }\r
1444                 }\r
1445 \r
1446                 return overrides;\r
1447         }\r
1448 \r
1449         // Make the comparison of attribute value easier by standardizing it.\r
1450         function normalizeProperty( name, value, isStyle )\r
1451         {\r
1452                 var temp = new CKEDITOR.dom.element( 'span' );\r
1453                 temp [ isStyle ? 'setStyle' : 'setAttribute' ]( name, value );\r
1454                 return temp[ isStyle ? 'getStyle' : 'getAttribute' ]( name );\r
1455         }\r
1456 \r
1457         // Make the comparison of style text easier by standardizing it.\r
1458         function normalizeCssText( unparsedCssText, nativeNormalize )\r
1459         {\r
1460                 var styleText;\r
1461                 if ( nativeNormalize !== false )\r
1462                 {\r
1463                         // Injects the style in a temporary span object, so the browser parses it,\r
1464                         // retrieving its final format.\r
1465                         var temp = new CKEDITOR.dom.element( 'span' );\r
1466                         temp.setAttribute( 'style', unparsedCssText );\r
1467                         styleText = temp.getAttribute( 'style' ) || '';\r
1468                 }\r
1469                 else\r
1470                         styleText = unparsedCssText;\r
1471 \r
1472                 // Normalize font-family property, ignore quotes and being case insensitive. (#7322)\r
1473                 // http://www.w3.org/TR/css3-fonts/#font-family-the-font-family-property\r
1474                 styleText = styleText.replace( /(font-family:)(.*?)(?=;|$)/, function ( match, prop, val )\r
1475                 {\r
1476                         var names = val.split( ',' );\r
1477                         for ( var i = 0; i < names.length; i++ )\r
1478                                 names[ i ] = CKEDITOR.tools.trim( names[ i ].replace( /["']/g, '' ) );\r
1479                         return prop + names.join( ',' );\r
1480                 });\r
1481 \r
1482                 // Shrinking white-spaces around colon and semi-colon (#4147).\r
1483                 // Compensate tail semi-colon.\r
1484                 return styleText.replace( /\s*([;:])\s*/, '$1' )\r
1485                                                          .replace( /([^\s;])$/, '$1;')\r
1486                                                         // Trimming spaces after comma(#4107),\r
1487                                                         // remove quotations(#6403),\r
1488                                                         // mostly for differences on "font-family".\r
1489                                                          .replace( /,\s+/g, ',' )\r
1490                                                          .replace( /\"/g,'' )\r
1491                                                          .toLowerCase();\r
1492         }\r
1493 \r
1494         // Turn inline style text properties into one hash.\r
1495         function parseStyleText( styleText )\r
1496         {\r
1497                 var retval = {};\r
1498                 styleText\r
1499                    .replace( /&quot;/g, '"' )\r
1500                    .replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value )\r
1501                 {\r
1502                         retval[ name ] = value;\r
1503                 } );\r
1504                 return retval;\r
1505         }\r
1506 \r
1507         /**\r
1508          * Compare two bunch of styles, with the speciality that value 'inherit'\r
1509          * is treated as a wildcard which will match any value.\r
1510          * @param {Object|String} source\r
1511          * @param {Object|String} target\r
1512          */\r
1513         function compareCssText( source, target )\r
1514         {\r
1515                 typeof source == 'string' && ( source = parseStyleText( source ) );\r
1516                 typeof target == 'string' && ( target = parseStyleText( target ) );\r
1517                 for( var name in source )\r
1518                 {\r
1519                         if ( !( name in target &&\r
1520                                         ( target[ name ] == source[ name ]\r
1521                                                 || source[ name ] == 'inherit'\r
1522                                                 || target[ name ] == 'inherit' ) ) )\r
1523                         {\r
1524                                 return false;\r
1525                         }\r
1526                 }\r
1527                 return true;\r
1528         }\r
1529 \r
1530         function applyStyle( document, remove )\r
1531         {\r
1532                 var selection = document.getSelection(),\r
1533                         // Bookmark the range so we can re-select it after processing.\r
1534                         bookmarks = selection.createBookmarks( 1 ),\r
1535                         ranges = selection.getRanges(),\r
1536                         func = remove ? this.removeFromRange : this.applyToRange,\r
1537                         range;\r
1538 \r
1539                 var iterator = ranges.createIterator();\r
1540                 while ( ( range = iterator.getNextRange() ) )\r
1541                         func.call( this, range );\r
1542 \r
1543                 if ( bookmarks.length == 1 && bookmarks[ 0 ].collapsed )\r
1544                 {\r
1545                         selection.selectRanges( ranges );\r
1546                         document.getById( bookmarks[ 0 ].startNode ).remove();\r
1547                 }\r
1548                 else\r
1549                         selection.selectBookmarks( bookmarks );\r
1550 \r
1551                 document.removeCustomData( 'doc_processing_style' );\r
1552         }\r
1553 })();\r
1554 \r
1555 CKEDITOR.styleCommand = function( style )\r
1556 {\r
1557         this.style = style;\r
1558 };\r
1559 \r
1560 CKEDITOR.styleCommand.prototype.exec = function( editor )\r
1561 {\r
1562         editor.focus();\r
1563 \r
1564         var doc = editor.document;\r
1565 \r
1566         if ( doc )\r
1567         {\r
1568                 if ( this.state == CKEDITOR.TRISTATE_OFF )\r
1569                         this.style.apply( doc );\r
1570                 else if ( this.state == CKEDITOR.TRISTATE_ON )\r
1571                         this.style.remove( doc );\r
1572         }\r
1573 \r
1574         return !!doc;\r
1575 };\r
1576 \r
1577 /**\r
1578  * Manages styles registration and loading. See also {@link CKEDITOR.config.stylesSet}.\r
1579  * @namespace\r
1580  * @augments CKEDITOR.resourceManager\r
1581  * @constructor\r
1582  * @since 3.2\r
1583  * @example\r
1584  * // The set of styles for the <b>Styles</b> combo\r
1585  * CKEDITOR.stylesSet.add( 'default',\r
1586  * [\r
1587  *      // Block Styles\r
1588  *      { name : 'Blue Title'           , element : 'h3', styles : { 'color' : 'Blue' } },\r
1589  *      { name : 'Red Title'            , element : 'h3', styles : { 'color' : 'Red' } },\r
1590  *\r
1591  *      // Inline Styles\r
1592  *      { name : 'Marker: Yellow'       , element : 'span', styles : { 'background-color' : 'Yellow' } },\r
1593  *      { name : 'Marker: Green'        , element : 'span', styles : { 'background-color' : 'Lime' } },\r
1594  *\r
1595  *      // Object Styles\r
1596  *      {\r
1597  *              name : 'Image on Left',\r
1598  *              element : 'img',\r
1599  *              attributes :\r
1600  *              {\r
1601  *                      'style' : 'padding: 5px; margin-right: 5px',\r
1602  *                      'border' : '2',\r
1603  *                      'align' : 'left'\r
1604  *              }\r
1605  *      }\r
1606  * ]);\r
1607  */\r
1608 CKEDITOR.stylesSet = new CKEDITOR.resourceManager( '', 'stylesSet' );\r
1609 \r
1610 // Backward compatibility (#5025).\r
1611 CKEDITOR.addStylesSet = CKEDITOR.tools.bind( CKEDITOR.stylesSet.add, CKEDITOR.stylesSet );\r
1612 CKEDITOR.loadStylesSet = function( name, url, callback )\r
1613         {\r
1614                 CKEDITOR.stylesSet.addExternal( name, url, '' );\r
1615                 CKEDITOR.stylesSet.load( name, callback );\r
1616         };\r
1617 \r
1618 \r
1619 /**\r
1620  * Gets the current styleSet for this instance\r
1621  * @param {Function} callback The function to be called with the styles data.\r
1622  * @example\r
1623  * editor.getStylesSet( function( stylesDefinitions ) {} );\r
1624  */\r
1625 CKEDITOR.editor.prototype.getStylesSet = function( callback )\r
1626 {\r
1627         if ( !this._.stylesDefinitions )\r
1628         {\r
1629                 var editor = this,\r
1630                         // Respect the backwards compatible definition entry\r
1631                         configStyleSet = editor.config.stylesCombo_stylesSet || editor.config.stylesSet || 'default';\r
1632 \r
1633                 // #5352 Allow to define the styles directly in the config object\r
1634                 if ( configStyleSet instanceof Array )\r
1635                 {\r
1636                         editor._.stylesDefinitions = configStyleSet;\r
1637                         callback( configStyleSet );\r
1638                         return;\r
1639                 }\r
1640 \r
1641                 var     partsStylesSet = configStyleSet.split( ':' ),\r
1642                         styleSetName = partsStylesSet[ 0 ],\r
1643                         externalPath = partsStylesSet[ 1 ],\r
1644                         pluginPath = CKEDITOR.plugins.registered.styles.path;\r
1645 \r
1646                 CKEDITOR.stylesSet.addExternal( styleSetName,\r
1647                                 externalPath ?\r
1648                                         partsStylesSet.slice( 1 ).join( ':' ) :\r
1649                                         pluginPath + 'styles/' + styleSetName + '.js', '' );\r
1650 \r
1651                 CKEDITOR.stylesSet.load( styleSetName, function( stylesSet )\r
1652                         {\r
1653                                 editor._.stylesDefinitions = stylesSet[ styleSetName ];\r
1654                                 callback( editor._.stylesDefinitions );\r
1655                         } ) ;\r
1656         }\r
1657         else\r
1658                 callback( this._.stylesDefinitions );\r
1659 };\r
1660 \r
1661 /**\r
1662  * Indicates that fully selected read-only elements will be included when\r
1663  * applying the style (for inline styles only).\r
1664  * @name CKEDITOR.style.includeReadonly\r
1665  * @type Boolean\r
1666  * @default false\r
1667  * @since 3.5\r
1668  */\r
1669 \r
1670  /**\r
1671   * Disables inline styling on read-only elements.\r
1672   * @name CKEDITOR.config.disableReadonlyStyling\r
1673   * @type Boolean\r
1674   * @default false\r
1675   * @since 3.5\r
1676   */\r
1677 \r
1678 /**\r
1679  * The "styles definition set" to use in the editor. They will be used in the\r
1680  * styles combo and the Style selector of the div container. <br>\r
1681  * The styles may be defined in the page containing the editor, or can be\r
1682  * loaded on demand from an external file. In the second case, if this setting\r
1683  * contains only a name, the styles definition file will be loaded from the\r
1684  * "styles" folder inside the styles plugin folder.\r
1685  * Otherwise, this setting has the "name:url" syntax, making it\r
1686  * possible to set the URL from which loading the styles file.<br>\r
1687  * Previously this setting was available as config.stylesCombo_stylesSet<br>\r
1688  * @name CKEDITOR.config.stylesSet\r
1689  * @type String|Array\r
1690  * @default 'default'\r
1691  * @since 3.3\r
1692  * @example\r
1693  * // Load from the styles' styles folder (mystyles.js file).\r
1694  * config.stylesSet = 'mystyles';\r
1695  * @example\r
1696  * // Load from a relative URL.\r
1697  * config.stylesSet = 'mystyles:/editorstyles/styles.js';\r
1698  * @example\r
1699  * // Load from a full URL.\r
1700  * config.stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js';\r
1701  * @example\r
1702  * // Load from a list of definitions.\r
1703  * config.stylesSet = [\r
1704  *  { name : 'Strong Emphasis', element : 'strong' },\r
1705  * { name : 'Emphasis', element : 'em' }, ... ];\r
1706  */\r