2 Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license
\r
6 CKEDITOR.plugins.add( 'styles',
\r
8 requires : [ 'selection' ]
\r
12 * Registers a function to be called whenever a style changes its state in the
\r
13 * editing area. The current state is passed to the function. The possible
\r
14 * states are {@link CKEDITOR.TRISTATE_ON} and {@link CKEDITOR.TRISTATE_OFF}.
\r
15 * @param {CKEDITOR.style} The style to be watched.
\r
16 * @param {Function} The function to be called when the style state changes.
\r
18 * // Create a style object for the <b> element.
\r
19 * var style = new CKEDITOR.style( { element : 'b' } );
\r
20 * var editor = CKEDITOR.instances.editor1;
\r
21 * editor.attachStyleStateChange( style, function( state )
\r
23 * if ( state == CKEDITOR.TRISTATE_ON )
\r
24 * alert( 'The current state for the B element is ON' );
\r
26 * alert( 'The current state for the B element is OFF' );
\r
29 CKEDITOR.editor.prototype.attachStyleStateChange = function( style, callback )
\r
31 // Try to get the list of attached callbacks.
\r
32 var styleStateChangeCallbacks = this._.styleStateChangeCallbacks;
\r
34 // If it doesn't exist, it means this is the first call. So, let's create
\r
35 // all the structure to manage the style checks and the callback calls.
\r
36 if ( !styleStateChangeCallbacks )
\r
38 // Create the callbacks array.
\r
39 styleStateChangeCallbacks = this._.styleStateChangeCallbacks = [];
\r
41 // Attach to the selectionChange event, so we can check the styles at
\r
43 this.on( 'selectionChange', function( ev )
\r
45 // Loop throw all registered callbacks.
\r
46 for ( var i = 0 ; i < styleStateChangeCallbacks.length ; i++ )
\r
48 var callback = styleStateChangeCallbacks[ i ];
\r
50 // Check the current state for the style defined for that
\r
52 var currentState = callback.style.checkActive( ev.data.path ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF;
\r
54 // If the state changed since the last check.
\r
55 if ( callback.state !== currentState )
\r
57 // Call the callback function, passing the current
\r
59 callback.fn.call( this, currentState );
\r
61 // Save the current state, so it can be compared next
\r
63 callback.state = currentState;
\r
69 // Save the callback info, so it can be checked on the next occurrence of
\r
71 styleStateChangeCallbacks.push( { style : style, fn : callback } );
\r
74 CKEDITOR.STYLE_BLOCK = 1;
\r
75 CKEDITOR.STYLE_INLINE = 2;
\r
76 CKEDITOR.STYLE_OBJECT = 3;
\r
80 var blockElements = { address:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1 };
\r
81 var objectElements = { a:1,embed:1,hr:1,img:1,li:1,object:1,ol:1,table:1,td:1,tr:1,th:1,ul:1,dl:1,dt:1,dd:1,form:1};
\r
83 var semicolonFixRegex = /\s*(?:;\s*|$)/;
\r
85 CKEDITOR.style = function( styleDefinition, variablesValues )
\r
87 if ( variablesValues )
\r
89 styleDefinition = CKEDITOR.tools.clone( styleDefinition );
\r
91 replaceVariables( styleDefinition.attributes, variablesValues );
\r
92 replaceVariables( styleDefinition.styles, variablesValues );
\r
95 var element = this.element = ( styleDefinition.element || '*' ).toLowerCase();
\r
98 ( element == '#' || blockElements[ element ] ) ?
\r
99 CKEDITOR.STYLE_BLOCK
\r
100 : objectElements[ element ] ?
\r
101 CKEDITOR.STYLE_OBJECT
\r
103 CKEDITOR.STYLE_INLINE;
\r
107 definition : styleDefinition
\r
111 CKEDITOR.style.prototype =
\r
113 apply : function( document )
\r
115 applyStyle.call( this, document, false );
\r
118 remove : function( document )
\r
120 applyStyle.call( this, document, true );
\r
123 applyToRange : function( range )
\r
125 return ( this.applyToRange =
\r
126 this.type == CKEDITOR.STYLE_INLINE ?
\r
128 : this.type == CKEDITOR.STYLE_BLOCK ?
\r
130 : this.type == CKEDITOR.STYLE_OBJECT ?
\r
132 : null ).call( this, range );
\r
135 removeFromRange : function( range )
\r
137 return ( this.removeFromRange =
\r
138 this.type == CKEDITOR.STYLE_INLINE ?
\r
140 : this.type == CKEDITOR.STYLE_OBJECT ?
\r
142 : null ).call( this, range );
\r
145 applyToObject : function( element )
\r
147 setupElement( element, this );
\r
151 * Get the style state inside an element path. Returns "true" if the
\r
152 * element is active in the path.
\r
154 checkActive : function( elementPath )
\r
156 switch ( this.type )
\r
158 case CKEDITOR.STYLE_BLOCK :
\r
159 return this.checkElementRemovable( elementPath.block || elementPath.blockLimit, true );
\r
161 case CKEDITOR.STYLE_OBJECT :
\r
162 case CKEDITOR.STYLE_INLINE :
\r
164 var elements = elementPath.elements;
\r
166 for ( var i = 0, element ; i < elements.length ; i++ )
\r
168 element = elements[ i ];
\r
170 if ( this.type == CKEDITOR.STYLE_INLINE
\r
171 && ( element == elementPath.block || element == elementPath.blockLimit ) )
\r
174 if( this.type == CKEDITOR.STYLE_OBJECT
\r
175 && !( element.getName() in objectElements ) )
\r
178 if ( this.checkElementRemovable( element, true ) )
\r
186 * Whether this style can be applied at the element path.
\r
187 * @param elementPath
\r
189 checkApplicable : function( elementPath )
\r
191 switch ( this.type )
\r
193 case CKEDITOR.STYLE_INLINE :
\r
194 case CKEDITOR.STYLE_BLOCK :
\r
197 case CKEDITOR.STYLE_OBJECT :
\r
198 return elementPath.lastElement.getAscendant( this.element, true );
\r
204 // Checks if an element, or any of its attributes, is removable by the
\r
205 // current style definition.
\r
206 checkElementRemovable : function( element, fullMatch )
\r
211 var def = this._.definition,
\r
214 // If the element name is the same as the style name.
\r
215 if ( element.getName() == this.element )
\r
217 // If no attributes are defined in the element.
\r
218 if ( !fullMatch && !element.hasAttributes() )
\r
221 attribs = getAttributesForComparison( def );
\r
223 if ( attribs._length )
\r
225 for ( var attName in attribs )
\r
227 if ( attName == '_length' )
\r
230 var elementAttr = element.getAttribute( attName ) || '';
\r
232 // Special treatment for 'style' attribute is required.
\r
233 if ( attName == 'style' ?
\r
234 compareCssText( attribs[ attName ], normalizeCssText( elementAttr, false ) )
\r
235 : attribs[ attName ] == elementAttr )
\r
240 else if ( fullMatch )
\r
250 // Check if the element can be somehow overriden.
\r
251 var override = getOverrides( this )[ element.getName() ] ;
\r
254 // If no attributes have been defined, remove the element.
\r
255 if ( !( attribs = override.attributes ) )
\r
258 for ( var i = 0 ; i < attribs.length ; i++ )
\r
260 attName = attribs[i][0];
\r
261 var actualAttrValue = element.getAttribute( attName );
\r
262 if ( actualAttrValue )
\r
264 var attValue = attribs[i][1];
\r
266 // Remove the attribute if:
\r
267 // - The override definition value is null;
\r
268 // - The override definition value is a string that
\r
269 // matches the attribute value exactly.
\r
270 // - The override definition value is a regex that
\r
271 // has matches in the attribute value.
\r
272 if ( attValue === null ||
\r
273 ( typeof attValue == 'string' && actualAttrValue == attValue ) ||
\r
274 attValue.test( actualAttrValue ) )
\r
282 // Builds the preview HTML based on the styles definition.
\r
283 buildPreview : function()
\r
285 var styleDefinition = this._.definition,
\r
287 elementName = styleDefinition.element;
\r
289 // Avoid <bdo> in the preview.
\r
290 if ( elementName == 'bdo' )
\r
291 elementName = 'span';
\r
293 html = [ '<', elementName ];
\r
295 // Assign all defined attributes.
\r
296 var attribs = styleDefinition.attributes;
\r
299 for ( var att in attribs )
\r
301 html.push( ' ', att, '="', attribs[ att ], '"' );
\r
305 // Assign the style attribute.
\r
306 var cssStyle = CKEDITOR.style.getStyleText( styleDefinition );
\r
308 html.push( ' style="', cssStyle, '"' );
\r
310 html.push( '>', styleDefinition.name, '</', elementName, '>' );
\r
312 return html.join( '' );
\r
316 // Build the cssText based on the styles definition.
\r
317 CKEDITOR.style.getStyleText = function( styleDefinition )
\r
319 // If we have already computed it, just return it.
\r
320 var stylesDef = styleDefinition._ST;
\r
324 stylesDef = styleDefinition.styles;
\r
326 // Builds the StyleText.
\r
327 var stylesText = ( styleDefinition.attributes && styleDefinition.attributes[ 'style' ] ) || '',
\r
328 specialStylesText = '';
\r
330 if ( stylesText.length )
\r
331 stylesText = stylesText.replace( semicolonFixRegex, ';' );
\r
333 for ( var style in stylesDef )
\r
335 var styleVal = stylesDef[ style ],
\r
336 text = ( style + ':' + styleVal ).replace( semicolonFixRegex, ';' );
\r
338 // Some browsers don't support 'inherit' property value, leave them intact. (#5242)
\r
339 if ( styleVal == 'inherit' )
\r
340 specialStylesText += text;
\r
342 stylesText += text;
\r
345 // Browsers make some changes to the style when applying them. So, here
\r
346 // we normalize it to the browser format.
\r
347 if ( stylesText.length )
\r
348 stylesText = normalizeCssText( stylesText );
\r
350 stylesText += specialStylesText;
\r
352 // Return it, saving it to the next request.
\r
353 return ( styleDefinition._ST = stylesText );
\r
356 function applyInlineStyle( range )
\r
358 var document = range.document;
\r
360 if ( range.collapsed )
\r
362 // Create the element to be inserted in the DOM.
\r
363 var collapsedElement = getElement( this, document );
\r
365 // Insert the empty element into the DOM at the range position.
\r
366 range.insertNode( collapsedElement );
\r
368 // Place the selection right inside the empty element.
\r
369 range.moveToPosition( collapsedElement, CKEDITOR.POSITION_BEFORE_END );
\r
374 var elementName = this.element;
\r
375 var def = this._.definition;
\r
376 var isUnknownElement;
\r
378 // Get the DTD definition for the element. Defaults to "span".
\r
379 var dtd = CKEDITOR.dtd[ elementName ] || ( isUnknownElement = true, CKEDITOR.dtd.span );
\r
381 // Expand the range.
\r
382 range.enlarge( CKEDITOR.ENLARGE_ELEMENT );
\r
385 // Get the first node to be processed and the last, which concludes the
\r
387 var boundaryNodes = range.createBookmark(),
\r
388 firstNode = boundaryNodes.startNode,
\r
389 lastNode = boundaryNodes.endNode;
\r
391 var currentNode = firstNode;
\r
395 while ( currentNode )
\r
397 var applyStyle = false;
\r
399 if ( currentNode.equals( lastNode ) )
\r
401 currentNode = null;
\r
406 var nodeType = currentNode.type;
\r
407 var nodeName = nodeType == CKEDITOR.NODE_ELEMENT ? currentNode.getName() : null;
\r
409 if ( nodeName && currentNode.getAttribute( '_cke_bookmark' ) )
\r
411 currentNode = currentNode.getNextSourceNode( true );
\r
415 // Check if the current node can be a child of the style element.
\r
416 if ( !nodeName || ( dtd[ nodeName ]
\r
417 && ( currentNode.getPosition( lastNode ) | CKEDITOR.POSITION_PRECEDING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_PRECEDING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED )
\r
418 && ( !def.childRule || def.childRule( currentNode ) ) ) )
\r
420 var currentParent = currentNode.getParent();
\r
422 // Check if the style element can be a child of the current
\r
423 // node parent or if the element is not defined in the DTD.
\r
425 && ( ( currentParent.getDtd() || CKEDITOR.dtd.span )[ elementName ] || isUnknownElement )
\r
426 && ( !def.parentRule || def.parentRule( currentParent ) ) )
\r
428 // This node will be part of our range, so if it has not
\r
429 // been started, place its start right before the node.
\r
430 // In the case of an element node, it will be included
\r
431 // only if it is entirely inside the range.
\r
432 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
434 styleRange = new CKEDITOR.dom.range( document );
\r
435 styleRange.setStartBefore( currentNode );
\r
438 // Non element nodes, or empty elements can be added
\r
439 // completely to the range.
\r
440 if ( nodeType == CKEDITOR.NODE_TEXT || ( nodeType == CKEDITOR.NODE_ELEMENT && !currentNode.getChildCount() ) )
\r
442 var includedNode = currentNode;
\r
445 // This node is about to be included completelly, but,
\r
446 // if this is the last node in its parent, we must also
\r
447 // check if the parent itself can be added completelly
\r
449 while ( !includedNode.$.nextSibling
\r
450 && ( parentNode = includedNode.getParent(), dtd[ parentNode.getName() ] )
\r
451 && ( parentNode.getPosition( firstNode ) | CKEDITOR.POSITION_FOLLOWING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_FOLLOWING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED )
\r
452 && ( !def.childRule || def.childRule( parentNode ) ) )
\r
454 includedNode = parentNode;
\r
457 styleRange.setEndAfter( includedNode );
\r
459 // If the included node still is the last node in its
\r
460 // parent, it means that the parent can't be included
\r
461 // in this style DTD, so apply the style immediately.
\r
462 if ( !includedNode.$.nextSibling )
\r
473 // Get the next node to be processed.
\r
474 currentNode = currentNode.getNextSourceNode();
\r
477 // Apply the style if we have something to which apply it.
\r
478 if ( applyStyle && styleRange && !styleRange.collapsed )
\r
480 // Build the style element, based on the style object definition.
\r
481 var styleNode = getElement( this, document );
\r
483 // Get the element that holds the entire range.
\r
484 var parent = styleRange.getCommonAncestor();
\r
486 // Loop through the parents, removing the redundant attributes
\r
487 // from the element to be applied.
\r
488 while ( styleNode && parent )
\r
490 if ( parent.getName() == elementName )
\r
492 for ( var attName in def.attributes )
\r
494 if ( styleNode.getAttribute( attName ) == parent.getAttribute( attName ) )
\r
495 styleNode.removeAttribute( attName );
\r
498 for ( var styleName in def.styles )
\r
500 if ( styleNode.getStyle( styleName ) == parent.getStyle( styleName ) )
\r
501 styleNode.removeStyle( styleName );
\r
504 if ( !styleNode.hasAttributes() )
\r
511 parent = parent.getParent();
\r
516 // Move the contents of the range to the style element.
\r
517 styleRange.extractContents().appendTo( styleNode );
\r
519 // Here we do some cleanup, removing all duplicated
\r
520 // elements from the style element.
\r
521 removeFromInsideElement( this, styleNode );
\r
523 // Insert it into the range position (it is collapsed after
\r
524 // extractContents.
\r
525 styleRange.insertNode( styleNode );
\r
527 // Let's merge our new style with its neighbors, if possible.
\r
528 styleNode.mergeSiblings();
\r
530 // As the style system breaks text nodes constantly, let's normalize
\r
531 // things for performance.
\r
532 // With IE, some paragraphs get broken when calling normalize()
\r
533 // repeatedly. Also, for IE, we must normalize body, not documentElement.
\r
534 // IE is also known for having a "crash effect" with normalize().
\r
535 // We should try to normalize with IE too in some way, somewhere.
\r
536 if ( !CKEDITOR.env.ie )
\r
537 styleNode.$.normalize();
\r
540 // Style applied, let's release the range, so it gets
\r
541 // re-initialization in the next loop.
\r
546 // Remove the bookmark nodes.
\r
547 range.moveToBookmark( boundaryNodes );
\r
549 // Minimize the result range to exclude empty text nodes. (#5374)
\r
550 range.shrink( CKEDITOR.SHRINK_TEXT );
\r
553 function removeInlineStyle( range )
\r
556 * Make sure our range has included all "collpased" parent inline nodes so
\r
557 * that our operation logic can be simpler.
\r
559 range.enlarge( CKEDITOR.ENLARGE_ELEMENT );
\r
561 var bookmark = range.createBookmark(),
\r
562 startNode = bookmark.startNode;
\r
564 if ( range.collapsed )
\r
567 var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),
\r
568 // The topmost element in elementspatch which we should jump out of.
\r
572 for ( var i = 0, element ; i < startPath.elements.length
\r
573 && ( element = startPath.elements[i] ) ; i++ )
\r
576 * 1. If it's collaped inside text nodes, try to remove the style from the whole element.
\r
578 * 2. Otherwise if it's collapsed on element boundaries, moving the selection
\r
579 * outside the styles instead of removing the whole tag,
\r
580 * also make sure other inner styles were well preserverd.(#3309)
\r
582 if ( element == startPath.block || element == startPath.blockLimit )
\r
585 if ( this.checkElementRemovable( element ) )
\r
589 if ( range.collapsed && (
\r
590 range.checkBoundaryOfElement( element, CKEDITOR.END ) ||
\r
591 ( isStart = range.checkBoundaryOfElement( element, CKEDITOR.START ) ) ) )
\r
593 boundaryElement = element;
\r
594 boundaryElement.match = isStart ? 'start' : 'end';
\r
599 * Before removing the style node, there may be a sibling to the style node
\r
600 * that's exactly the same to the one to be removed. To the user, it makes
\r
601 * no difference that they're separate entities in the DOM tree. So, merge
\r
602 * them before removal.
\r
604 element.mergeSiblings();
\r
605 removeFromElement( this, element );
\r
611 // Re-create the style tree after/before the boundary element,
\r
612 // the replication start from bookmark start node to define the
\r
614 if ( boundaryElement )
\r
616 var clonedElement = startNode;
\r
617 for ( i = 0 ;; i++ )
\r
619 var newElement = startPath.elements[ i ];
\r
620 if ( newElement.equals( boundaryElement ) )
\r
622 // Avoid copying any matched element.
\r
623 else if ( newElement.match )
\r
626 newElement = newElement.clone();
\r
627 newElement.append( clonedElement );
\r
628 clonedElement = newElement;
\r
630 clonedElement[ boundaryElement.match == 'start' ?
\r
631 'insertBefore' : 'insertAfter' ]( boundaryElement );
\r
637 * Now our range isn't collapsed. Lets walk from the start node to the end
\r
638 * node via DFS and remove the styles one-by-one.
\r
640 var endNode = bookmark.endNode,
\r
644 * Find out the style ancestor that needs to be broken down at startNode
\r
647 function breakNodes()
\r
649 var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),
\r
650 endPath = new CKEDITOR.dom.elementPath( endNode.getParent() ),
\r
653 for ( var i = 0 ; i < startPath.elements.length ; i++ )
\r
655 var element = startPath.elements[ i ];
\r
657 if ( element == startPath.block || element == startPath.blockLimit )
\r
660 if ( me.checkElementRemovable( element ) )
\r
661 breakStart = element;
\r
663 for ( i = 0 ; i < endPath.elements.length ; i++ )
\r
665 element = endPath.elements[ i ];
\r
667 if ( element == endPath.block || element == endPath.blockLimit )
\r
670 if ( me.checkElementRemovable( element ) )
\r
671 breakEnd = element;
\r
675 endNode.breakParent( breakEnd );
\r
677 startNode.breakParent( breakStart );
\r
681 // Now, do the DFS walk.
\r
682 var currentNode = startNode.getNext();
\r
683 while ( !currentNode.equals( endNode ) )
\r
686 * Need to get the next node first because removeFromElement() can remove
\r
687 * the current node from DOM tree.
\r
689 var nextNode = currentNode.getNextSourceNode();
\r
690 if ( currentNode.type == CKEDITOR.NODE_ELEMENT && this.checkElementRemovable( currentNode ) )
\r
692 // Remove style from element or overriding element.
\r
693 if ( currentNode.getName() == this.element )
\r
694 removeFromElement( this, currentNode );
\r
696 removeOverrides( currentNode, getOverrides( this )[ currentNode.getName() ] );
\r
699 * removeFromElement() may have merged the next node with something before
\r
700 * the startNode via mergeSiblings(). In that case, the nextNode would
\r
701 * contain startNode and we'll have to call breakNodes() again and also
\r
702 * reassign the nextNode to something after startNode.
\r
704 if ( nextNode.type == CKEDITOR.NODE_ELEMENT && nextNode.contains( startNode ) )
\r
707 nextNode = startNode.getNext();
\r
710 currentNode = nextNode;
\r
714 range.moveToBookmark( bookmark );
\r
717 function applyObjectStyle( range )
\r
719 var root = range.getCommonAncestor( true, true ),
\r
720 element = root.getAscendant( this.element, true );
\r
721 element && setupElement( element, this );
\r
724 function removeObjectStyle( range )
\r
726 var root = range.getCommonAncestor( true, true ),
\r
727 element = root.getAscendant( this.element, true );
\r
733 var def = style._.definition;
\r
734 var attributes = def.attributes;
\r
735 var styles = CKEDITOR.style.getStyleText( def );
\r
737 // Remove all defined attributes.
\r
740 for ( var att in attributes )
\r
742 element.removeAttribute( att, attributes[ att ] );
\r
746 // Assign all defined styles.
\r
749 for ( var i in def.styles )
\r
751 if ( !def.styles.hasOwnProperty( i ) )
\r
754 element.removeStyle( i );
\r
759 function applyBlockStyle( range )
\r
761 // Serializible bookmarks is needed here since
\r
762 // elements may be merged.
\r
763 var bookmark = range.createBookmark( true );
\r
765 var iterator = range.createIterator();
\r
766 iterator.enforceRealBlocks = true;
\r
768 // make recognize <br /> tag as a separator in ENTER_BR mode (#5121)
\r
769 if ( this._.enterMode )
\r
770 iterator.enlargeBr = ( this._.enterMode != CKEDITOR.ENTER_BR );
\r
773 var doc = range.document;
\r
774 var previousPreBlock;
\r
776 while ( ( block = iterator.getNextParagraph() ) ) // Only one =
\r
778 var newBlock = getElement( this, doc );
\r
779 replaceBlock( block, newBlock );
\r
782 range.moveToBookmark( bookmark );
\r
785 // Replace the original block with new one, with special treatment
\r
786 // for <pre> blocks to make sure content format is well preserved, and merging/splitting adjacent
\r
787 // when necessary.(#3188)
\r
788 function replaceBlock( block, newBlock )
\r
790 var newBlockIsPre = newBlock.is( 'pre' );
\r
791 var blockIsPre = block.is( 'pre' );
\r
793 var isToPre = newBlockIsPre && !blockIsPre;
\r
794 var isFromPre = !newBlockIsPre && blockIsPre;
\r
797 newBlock = toPre( block, newBlock );
\r
798 else if ( isFromPre )
\r
799 // Split big <pre> into pieces before start to convert.
\r
800 newBlock = fromPres( splitIntoPres( block ), newBlock );
\r
802 block.moveChildren( newBlock );
\r
804 newBlock.replace( block );
\r
806 if ( newBlockIsPre )
\r
808 // Merge previous <pre> blocks.
\r
809 mergePre( newBlock );
\r
813 var nonWhitespaces = CKEDITOR.dom.walker.whitespaces( true );
\r
815 * Merge a <pre> block with a previous sibling if available.
\r
817 function mergePre( preBlock )
\r
820 if ( !( ( previousBlock = preBlock.getPrevious( nonWhitespaces ) )
\r
821 && previousBlock.is
\r
822 && previousBlock.is( 'pre') ) )
\r
825 // Merge the previous <pre> block contents into the current <pre>
\r
828 // Another thing to be careful here is that currentBlock might contain
\r
829 // a '\n' at the beginning, and previousBlock might contain a '\n'
\r
830 // towards the end. These new lines are not normally displayed but they
\r
831 // become visible after merging.
\r
832 var mergedHtml = replace( previousBlock.getHtml(), /\n$/, '' ) + '\n\n' +
\r
833 replace( preBlock.getHtml(), /^\n/, '' ) ;
\r
835 // Krugle: IE normalizes innerHTML from <pre>, breaking whitespaces.
\r
836 if ( CKEDITOR.env.ie )
\r
837 preBlock.$.outerHTML = '<pre>' + mergedHtml + '</pre>';
\r
839 preBlock.setHtml( mergedHtml );
\r
841 previousBlock.remove();
\r
845 * Split into multiple <pre> blocks separated by double line-break.
\r
848 function splitIntoPres( preBlock )
\r
850 // Exclude the ones at header OR at tail,
\r
851 // and ignore bookmark content between them.
\r
852 var duoBrRegex = /(\S\s*)\n(?:\s|(<span[^>]+_cke_bookmark.*?\/span>))*\n(?!$)/gi,
\r
853 blockName = preBlock.getName(),
\r
854 splitedHtml = replace( preBlock.getOuterHtml(),
\r
856 function( match, charBefore, bookmark )
\r
858 return charBefore + '</pre>' + bookmark + '<pre>';
\r
862 splitedHtml.replace( /<pre\b.*?>([\s\S]*?)<\/pre>/gi, function( match, preContent ){
\r
863 pres.push( preContent );
\r
868 // Wrapper function of String::replace without considering of head/tail bookmarks nodes.
\r
869 function replace( str, regexp, replacement )
\r
871 var headBookmark = '',
\r
874 str = str.replace( /(^<span[^>]+_cke_bookmark.*?\/span>)|(<span[^>]+_cke_bookmark.*?\/span>$)/gi,
\r
875 function( str, m1, m2 ){
\r
876 m1 && ( headBookmark = m1 );
\r
877 m2 && ( tailBookmark = m2 );
\r
880 return headBookmark + str.replace( regexp, replacement ) + tailBookmark;
\r
883 * Converting a list of <pre> into blocks with format well preserved.
\r
885 function fromPres( preHtmls, newBlock )
\r
887 var docFrag = new CKEDITOR.dom.documentFragment( newBlock.getDocument() );
\r
888 for ( var i = 0 ; i < preHtmls.length ; i++ )
\r
890 var blockHtml = preHtmls[ i ];
\r
892 // 1. Trim the first and last line-breaks immediately after and before <pre>,
\r
893 // they're not visible.
\r
894 blockHtml = blockHtml.replace( /(\r\n|\r)/g, '\n' ) ;
\r
895 blockHtml = replace( blockHtml, /^[ \t]*\n/, '' ) ;
\r
896 blockHtml = replace( blockHtml, /\n$/, '' ) ;
\r
897 // 2. Convert spaces or tabs at the beginning or at the end to
\r
898 blockHtml = replace( blockHtml, /^[ \t]+|[ \t]+$/g, function( match, offset, s )
\r
900 if ( match.length == 1 ) // one space, preserve it
\r
902 else if ( !offset ) // beginning of block
\r
903 return CKEDITOR.tools.repeat( ' ', match.length - 1 ) + ' ';
\r
904 else // end of block
\r
905 return ' ' + CKEDITOR.tools.repeat( ' ', match.length - 1 );
\r
908 // 3. Convert \n to <BR>.
\r
909 // 4. Convert contiguous (i.e. non-singular) spaces or tabs to
\r
910 blockHtml = blockHtml.replace( /\n/g, '<br>' ) ;
\r
911 blockHtml = blockHtml.replace( /[ \t]{2,}/g,
\r
914 return CKEDITOR.tools.repeat( ' ', match.length - 1 ) + ' ' ;
\r
917 var newBlockClone = newBlock.clone();
\r
918 newBlockClone.setHtml( blockHtml );
\r
919 docFrag.append( newBlockClone );
\r
925 * Converting from a non-PRE block to a PRE block in formatting operations.
\r
927 function toPre( block, newBlock )
\r
929 // First trim the block content.
\r
930 var preHtml = block.getHtml();
\r
932 // 1. Trim head/tail spaces, they're not visible.
\r
933 preHtml = replace( preHtml, /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '' );
\r
934 // 2. Delete ANSI whitespaces immediately before and after <BR> because
\r
935 // they are not visible.
\r
936 preHtml = preHtml.replace( /[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi, '$1' );
\r
937 // 3. Compress other ANSI whitespaces since they're only visible as one
\r
938 // single space previously.
\r
939 // 4. Convert to spaces since is no longer needed in <PRE>.
\r
940 preHtml = preHtml.replace( /([ \t\n\r]+| )/g, ' ' );
\r
941 // 5. Convert any <BR /> to \n. This must not be done earlier because
\r
942 // the \n would then get compressed.
\r
943 preHtml = preHtml.replace( /<br\b[^>]*>/gi, '\n' );
\r
945 // Krugle: IE normalizes innerHTML to <pre>, breaking whitespaces.
\r
946 if ( CKEDITOR.env.ie )
\r
948 var temp = block.getDocument().createElement( 'div' );
\r
949 temp.append( newBlock );
\r
950 newBlock.$.outerHTML = '<pre>' + preHtml + '</pre>';
\r
951 newBlock = temp.getFirst().remove();
\r
954 newBlock.setHtml( preHtml );
\r
959 // Removes a style from an element itself, don't care about its subtree.
\r
960 function removeFromElement( style, element )
\r
962 var def = style._.definition,
\r
963 attributes = CKEDITOR.tools.extend( {}, def.attributes, getOverrides( style )[ element.getName() ] ),
\r
964 styles = def.styles,
\r
965 // If the style is only about the element itself, we have to remove the element.
\r
966 removeEmpty = CKEDITOR.tools.isEmpty( attributes ) && CKEDITOR.tools.isEmpty( styles );
\r
968 // Remove definition attributes/style from the elemnt.
\r
969 for ( var attName in attributes )
\r
971 // The 'class' element value must match (#1318).
\r
972 if ( ( attName == 'class' || style._.definition.fullMatch )
\r
973 && element.getAttribute( attName ) != normalizeProperty( attName, attributes[ attName ] ) )
\r
975 removeEmpty = element.hasAttribute( attName );
\r
976 element.removeAttribute( attName );
\r
979 for ( var styleName in styles )
\r
981 // Full match style insist on having fully equivalence. (#5018)
\r
982 if ( style._.definition.fullMatch
\r
983 && element.getStyle( styleName ) != normalizeProperty( styleName, styles[ styleName ], true ) )
\r
986 removeEmpty = removeEmpty || !!element.getStyle( styleName );
\r
987 element.removeStyle( styleName );
\r
990 removeEmpty && removeNoAttribsElement( element );
\r
993 // Removes a style from inside an element.
\r
994 function removeFromInsideElement( style, element )
\r
996 var def = style._.definition,
\r
997 attribs = def.attributes,
\r
998 styles = def.styles,
\r
999 overrides = getOverrides( style );
\r
1001 var innerElements = element.getElementsByTag( style.element );
\r
1003 for ( var i = innerElements.count(); --i >= 0 ; )
\r
1004 removeFromElement( style, innerElements.getItem( i ) );
\r
1006 // Now remove any other element with different name that is
\r
1007 // defined to be overriden.
\r
1008 for ( var overrideElement in overrides )
\r
1010 if ( overrideElement != style.element )
\r
1012 innerElements = element.getElementsByTag( overrideElement ) ;
\r
1013 for ( i = innerElements.count() - 1 ; i >= 0 ; i-- )
\r
1015 var innerElement = innerElements.getItem( i );
\r
1016 removeOverrides( innerElement, overrides[ overrideElement ] ) ;
\r
1024 * Remove overriding styles/attributes from the specific element.
\r
1025 * Note: Remove the element if no attributes remain.
\r
1026 * @param {Object} element
\r
1027 * @param {Object} overrides
\r
1029 function removeOverrides( element, overrides )
\r
1031 var attributes = overrides && overrides.attributes ;
\r
1035 for ( var i = 0 ; i < attributes.length ; i++ )
\r
1037 var attName = attributes[i][0], actualAttrValue ;
\r
1039 if ( ( actualAttrValue = element.getAttribute( attName ) ) )
\r
1041 var attValue = attributes[i][1] ;
\r
1043 // Remove the attribute if:
\r
1044 // - The override definition value is null ;
\r
1045 // - The override definition valie is a string that
\r
1046 // matches the attribute value exactly.
\r
1047 // - The override definition value is a regex that
\r
1048 // has matches in the attribute value.
\r
1049 if ( attValue === null ||
\r
1050 ( attValue.test && attValue.test( actualAttrValue ) ) ||
\r
1051 ( typeof attValue == 'string' && actualAttrValue == attValue ) )
\r
1052 element.removeAttribute( attName ) ;
\r
1057 removeNoAttribsElement( element );
\r
1060 // If the element has no more attributes, remove it.
\r
1061 function removeNoAttribsElement( element )
\r
1063 // If no more attributes remained in the element, remove it,
\r
1064 // leaving its children.
\r
1065 if ( !element.hasAttributes() )
\r
1067 // Removing elements may open points where merging is possible,
\r
1068 // so let's cache the first and last nodes for later checking.
\r
1069 var firstChild = element.getFirst();
\r
1070 var lastChild = element.getLast();
\r
1072 element.remove( true );
\r
1076 // Check the cached nodes for merging.
\r
1077 firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.mergeSiblings();
\r
1079 if ( lastChild && !firstChild.equals( lastChild )
\r
1080 && lastChild.type == CKEDITOR.NODE_ELEMENT )
\r
1081 lastChild.mergeSiblings();
\r
1086 function getElement( style, targetDocument )
\r
1090 var def = style._.definition;
\r
1092 var elementName = style.element;
\r
1094 // The "*" element name will always be a span for this function.
\r
1095 if ( elementName == '*' )
\r
1096 elementName = 'span';
\r
1098 // Create the element.
\r
1099 el = new CKEDITOR.dom.element( elementName, targetDocument );
\r
1101 return setupElement( el, style );
\r
1104 function setupElement( el, style )
\r
1106 var def = style._.definition;
\r
1107 var attributes = def.attributes;
\r
1108 var styles = CKEDITOR.style.getStyleText( def );
\r
1110 // Assign all defined attributes.
\r
1113 for ( var att in attributes )
\r
1115 el.setAttribute( att, attributes[ att ] );
\r
1119 // Assign all defined styles.
\r
1122 for ( var i in def.styles )
\r
1124 if ( !def.styles.hasOwnProperty( i ) )
\r
1127 el.setStyle( i, def.styles[ i ] );
\r
1134 var varRegex = /#\((.+?)\)/g;
\r
1135 function replaceVariables( list, variablesValues )
\r
1137 for ( var item in list )
\r
1139 list[ item ] = list[ item ].replace( varRegex, function( match, varName )
\r
1141 return variablesValues[ varName ];
\r
1147 // Returns an object that can be used for style matching comparison.
\r
1148 // Attributes names and values are all lowercased, and the styles get
\r
1149 // merged with the style attribute.
\r
1150 function getAttributesForComparison( styleDefinition )
\r
1152 // If we have already computed it, just return it.
\r
1153 var attribs = styleDefinition._AC;
\r
1161 // Loop through all defined attributes.
\r
1162 var styleAttribs = styleDefinition.attributes;
\r
1163 if ( styleAttribs )
\r
1165 for ( var styleAtt in styleAttribs )
\r
1168 attribs[ styleAtt ] = styleAttribs[ styleAtt ];
\r
1172 // Includes the style definitions.
\r
1173 var styleText = CKEDITOR.style.getStyleText( styleDefinition );
\r
1176 if ( !attribs[ 'style' ] )
\r
1178 attribs[ 'style' ] = styleText;
\r
1181 // Appends the "length" information to the object.
\r
1182 attribs._length = length;
\r
1184 // Return it, saving it to the next request.
\r
1185 return ( styleDefinition._AC = attribs );
\r
1189 * Get the the collection used to compare the elements and attributes,
\r
1190 * defined in this style overrides, with other element. All information in
\r
1191 * it is lowercased.
\r
1192 * @param {CKEDITOR.style} style
\r
1194 function getOverrides( style )
\r
1196 if ( style._.overrides )
\r
1197 return style._.overrides;
\r
1199 var overrides = ( style._.overrides = {} ),
\r
1200 definition = style._.definition.overrides;
\r
1204 // The override description can be a string, object or array.
\r
1205 // Internally, well handle arrays only, so transform it if needed.
\r
1206 if ( !CKEDITOR.tools.isArray( definition ) )
\r
1207 definition = [ definition ];
\r
1209 // Loop through all override definitions.
\r
1210 for ( var i = 0 ; i < definition.length ; i++ )
\r
1212 var override = definition[i];
\r
1217 // If can be a string with the element name.
\r
1218 if ( typeof override == 'string' )
\r
1219 elementName = override.toLowerCase();
\r
1223 elementName = override.element ? override.element.toLowerCase() : style.element;
\r
1224 attrs = override.attributes;
\r
1227 // We can have more than one override definition for the same
\r
1228 // element name, so we attempt to simply append information to
\r
1229 // it if it already exists.
\r
1230 overrideEl = overrides[ elementName ] || ( overrides[ elementName ] = {} );
\r
1234 // The returning attributes list is an array, because we
\r
1235 // could have different override definitions for the same
\r
1236 // attribute name.
\r
1237 var overrideAttrs = ( overrideEl.attributes = overrideEl.attributes || new Array() );
\r
1238 for ( var attName in attrs )
\r
1240 // Each item in the attributes array is also an array,
\r
1241 // where [0] is the attribute name and [1] is the
\r
1242 // override value.
\r
1243 overrideAttrs.push( [ attName.toLowerCase(), attrs[ attName ] ] );
\r
1252 // Make the comparison of attribute value easier by standardizing it.
\r
1253 function normalizeProperty( name, value, isStyle )
\r
1255 var temp = new CKEDITOR.dom.element( 'span' );
\r
1256 temp [ isStyle ? 'setStyle' : 'setAttribute' ]( name, value );
\r
1257 return temp[ isStyle ? 'getStyle' : 'getAttribute' ]( name );
\r
1260 // Make the comparison of style text easier by standardizing it.
\r
1261 function normalizeCssText( unparsedCssText, nativeNormalize )
\r
1264 if ( nativeNormalize !== false )
\r
1266 // Injects the style in a temporary span object, so the browser parses it,
\r
1267 // retrieving its final format.
\r
1268 var temp = new CKEDITOR.dom.element( 'span' );
\r
1269 temp.setAttribute( 'style', unparsedCssText );
\r
1270 styleText = temp.getAttribute( 'style' ) || '';
\r
1273 styleText = unparsedCssText;
\r
1275 // Shrinking white-spaces around colon and semi-colon (#4147).
\r
1276 // Compensate tail semi-colon.
\r
1277 return styleText.replace( /\s*([;:])\s*/, '$1' )
\r
1278 .replace( /([^\s;])$/, '$1;')
\r
1279 .replace( /,\s+/g, ',' ) // Trimming spaces after comma (e.g. font-family name)(#4107).
\r
1283 // Turn inline style text properties into one hash.
\r
1284 function parseStyleText( styleText )
\r
1288 .replace( /"/g, '"' )
\r
1289 .replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value )
\r
1291 retval[ name ] = value;
\r
1297 * Compare two bunch of styles, with the speciality that value 'inherit'
\r
1298 * is treated as a wildcard which will match any value.
\r
1299 * @param {Object|String} source
\r
1300 * @param {Object|String} target
\r
1302 function compareCssText( source, target )
\r
1304 typeof source == 'string' && ( source = parseStyleText( source ) );
\r
1305 typeof target == 'string' && ( target = parseStyleText( target ) );
\r
1306 for( var name in source )
\r
1308 if ( !( name in target &&
\r
1309 ( target[ name ] == source[ name ]
\r
1310 || source[ name ] == 'inherit'
\r
1311 || target[ name ] == 'inherit' ) ) )
\r
1319 function applyStyle( document, remove )
\r
1321 var selection = document.getSelection(),
\r
1322 // Bookmark the range so we can re-select it after processing.
\r
1323 bookmarks = selection.createBookmarks(),
\r
1324 ranges = selection.getRanges( true ),
\r
1325 func = remove ? this.removeFromRange : this.applyToRange,
\r
1328 var iterator = ranges.createIterator();
\r
1329 while ( ( range = iterator.getNextRange() ) )
\r
1330 func.call( this, range );
\r
1332 if ( bookmarks.length == 1 && bookmarks[0].collapsed )
\r
1334 selection.selectRanges( ranges );
\r
1335 bookmarks[0].startNode.remove();
\r
1338 selection.selectBookmarks( bookmarks );
\r
1342 CKEDITOR.styleCommand = function( style )
\r
1344 this.style = style;
\r
1347 CKEDITOR.styleCommand.prototype.exec = function( editor )
\r
1351 var doc = editor.document;
\r
1355 if ( this.state == CKEDITOR.TRISTATE_OFF )
\r
1356 this.style.apply( doc );
\r
1357 else if ( this.state == CKEDITOR.TRISTATE_ON )
\r
1358 this.style.remove( doc );
\r
1364 CKEDITOR.stylesSet = new CKEDITOR.resourceManager( '', 'stylesSet' );
\r
1366 // Backward compatibility (#5025).
\r
1367 CKEDITOR.addStylesSet = CKEDITOR.tools.bind( CKEDITOR.stylesSet.add, CKEDITOR.stylesSet );
\r
1368 CKEDITOR.loadStylesSet = function( name, url, callback )
\r
1370 CKEDITOR.stylesSet.addExternal( name, url, '' );
\r
1371 CKEDITOR.stylesSet.load( name, callback );
\r
1376 * Gets the current styleSet for this instance
\r
1377 * @param {Function} The function to be called with the styles data.
\r
1379 * editor.getStylesSet( function( stylesDefinitions ) {} );
\r
1381 CKEDITOR.editor.prototype.getStylesSet = function( callback )
\r
1383 if ( !this._.stylesDefinitions )
\r
1385 var editor = this,
\r
1386 // Respect the backwards compatible definition entry
\r
1387 configStyleSet = editor.config.stylesCombo_stylesSet || editor.config.stylesSet || 'default';
\r
1389 // #5352 Allow to define the styles directly in the config object
\r
1390 if ( configStyleSet instanceof Array )
\r
1392 editor._.stylesDefinitions = configStyleSet;
\r
1393 callback( configStyleSet );
\r
1397 var partsStylesSet = configStyleSet.split( ':' ),
\r
1398 styleSetName = partsStylesSet[ 0 ],
\r
1399 externalPath = partsStylesSet[ 1 ],
\r
1400 pluginPath = CKEDITOR.plugins.registered.styles.path;
\r
1402 CKEDITOR.stylesSet.addExternal( styleSetName,
\r
1404 partsStylesSet.slice( 1 ).join( ':' ) :
\r
1405 pluginPath + 'styles/' + styleSetName + '.js', '' );
\r
1407 CKEDITOR.stylesSet.load( styleSetName, function( stylesSet )
\r
1409 editor._.stylesDefinitions = stylesSet[ styleSetName ];
\r
1410 callback( editor._.stylesDefinitions );
\r
1414 callback( this._.stylesDefinitions );
\r
1418 * The "styles definition set" to use in the editor. They will be used in the
\r
1419 * styles combo and the Style selector of the div container. <br>
\r
1420 * The styles may be defined in the page containing the editor, or can be
\r
1421 * loaded on demand from an external file. In the second case, if this setting
\r
1422 * contains only a name, the styles definition file will be loaded from the
\r
1423 * "styles" folder inside the styles plugin folder.
\r
1424 * Otherwise, this setting has the "name:url" syntax, making it
\r
1425 * possible to set the URL from which loading the styles file.<br>
\r
1426 * Previously this setting was available as config.stylesCombo_stylesSet<br>
\r
1427 * @name CKEDITOR.config.stylesSet
\r
1428 * @type String|Array
\r
1429 * @default 'default'
\r
1432 * // Load from the styles' styles folder (mystyles.js file).
\r
1433 * config.stylesSet = 'mystyles';
\r
1435 * // Load from a relative URL.
\r
1436 * config.stylesSet = 'mystyles:/editorstyles/styles.js';
\r
1438 * // Load from a full URL.
\r
1439 * config.stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js';
\r
1441 * // Load from a list of definitions.
\r
1442 * config.stylesSet = [
\r
1443 * { name : 'Strong Emphasis', element : 'strong' },
\r
1444 * { name : 'Emphasis', element : 'em' }, ... ];
\r