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