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 occurence 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 : null ).call( this, range );
\r
143 applyToObject : function( element )
\r
145 setupElement( element, this );
\r
149 * Get the style state inside an element path. Returns "true" if the
\r
150 * element is active in the path.
\r
152 checkActive : function( elementPath )
\r
154 switch ( this.type )
\r
156 case CKEDITOR.STYLE_BLOCK :
\r
157 return this.checkElementRemovable( elementPath.block || elementPath.blockLimit, true );
\r
159 case CKEDITOR.STYLE_OBJECT :
\r
160 case CKEDITOR.STYLE_INLINE :
\r
162 var elements = elementPath.elements;
\r
164 for ( var i = 0, element ; i < elements.length ; i++ )
\r
166 element = elements[ i ];
\r
168 if ( this.type == CKEDITOR.STYLE_INLINE
\r
169 && ( element == elementPath.block || element == elementPath.blockLimit ) )
\r
172 if( this.type == CKEDITOR.STYLE_OBJECT
\r
173 && !( element.getName() in objectElements ) )
\r
176 if ( this.checkElementRemovable( element, true ) )
\r
183 checkApplicable : function( elementPath )
\r
185 switch ( this.type )
\r
187 case CKEDITOR.STYLE_INLINE :
\r
188 case CKEDITOR.STYLE_BLOCK :
\r
191 case CKEDITOR.STYLE_OBJECT :
\r
192 return elementPath.lastElement.getAscendant( this.element, true );
\r
198 // Checks if an element, or any of its attributes, is removable by the
\r
199 // current style definition.
\r
200 checkElementRemovable : function( element, fullMatch )
\r
205 var def = this._.definition,
\r
208 // If the element name is the same as the style name.
\r
209 if ( element.getName() == this.element )
\r
211 // If no attributes are defined in the element.
\r
212 if ( !fullMatch && !element.hasAttributes() )
\r
215 attribs = getAttributesForComparison( def );
\r
217 if ( attribs._length )
\r
219 for ( var attName in attribs )
\r
221 if ( attName == '_length' )
\r
224 var elementAttr = element.getAttribute( attName ) || '';
\r
225 if ( attName == 'style' ?
\r
226 compareCssText( attribs[ attName ], normalizeCssText( elementAttr, false ) )
\r
227 : attribs[ attName ] == elementAttr )
\r
232 else if ( fullMatch )
\r
242 // Check if the element can be somehow overriden.
\r
243 var override = getOverrides( this )[ element.getName() ] ;
\r
246 // If no attributes have been defined, remove the element.
\r
247 if ( !( attribs = override.attributes ) )
\r
250 for ( var i = 0 ; i < attribs.length ; i++ )
\r
252 attName = attribs[i][0];
\r
253 var actualAttrValue = element.getAttribute( attName );
\r
254 if ( actualAttrValue )
\r
256 var attValue = attribs[i][1];
\r
258 // Remove the attribute if:
\r
259 // - The override definition value is null;
\r
260 // - The override definition value is a string that
\r
261 // matches the attribute value exactly.
\r
262 // - The override definition value is a regex that
\r
263 // has matches in the attribute value.
\r
264 if ( attValue === null ||
\r
265 ( typeof attValue == 'string' && actualAttrValue == attValue ) ||
\r
266 attValue.test( actualAttrValue ) )
\r
274 // Builds the preview HTML based on the styles definition.
\r
275 buildPreview : function()
\r
277 var styleDefinition = this._.definition,
\r
279 elementName = styleDefinition.element;
\r
281 // Avoid <bdo> in the preview.
\r
282 if ( elementName == 'bdo' )
\r
283 elementName = 'span';
\r
285 html = [ '<', elementName ];
\r
287 // Assign all defined attributes.
\r
288 var attribs = styleDefinition.attributes;
\r
291 for ( var att in attribs )
\r
293 html.push( ' ', att, '="', attribs[ att ], '"' );
\r
297 // Assign the style attribute.
\r
298 var cssStyle = CKEDITOR.style.getStyleText( styleDefinition );
\r
300 html.push( ' style="', cssStyle, '"' );
\r
302 html.push( '>', styleDefinition.name, '</', elementName, '>' );
\r
304 return html.join( '' );
\r
308 // Build the cssText based on the styles definition.
\r
309 CKEDITOR.style.getStyleText = function( styleDefinition )
\r
311 // If we have already computed it, just return it.
\r
312 var stylesDef = styleDefinition._ST;
\r
316 stylesDef = styleDefinition.styles;
\r
318 // Builds the StyleText.
\r
319 var stylesText = ( styleDefinition.attributes && styleDefinition.attributes[ 'style' ] ) || '',
\r
320 specialStylesText = '';
\r
322 if ( stylesText.length )
\r
323 stylesText = stylesText.replace( semicolonFixRegex, ';' );
\r
325 for ( var style in stylesDef )
\r
327 var styleVal = stylesDef[ style ],
\r
328 text = ( style + ':' + styleVal ).replace( semicolonFixRegex, ';' );
\r
330 // Some browsers don't support 'inherit' property value, leave them intact. (#5242)
\r
331 if ( styleVal == 'inherit' )
\r
332 specialStylesText += text;
\r
334 stylesText += text;
\r
337 // Browsers make some changes to the style when applying them. So, here
\r
338 // we normalize it to the browser format.
\r
339 if ( stylesText.length )
\r
340 stylesText = normalizeCssText( stylesText );
\r
342 stylesText += specialStylesText;
\r
344 // Return it, saving it to the next request.
\r
345 return ( styleDefinition._ST = stylesText );
\r
348 function applyInlineStyle( range )
\r
350 var document = range.document;
\r
352 if ( range.collapsed )
\r
354 // Create the element to be inserted in the DOM.
\r
355 var collapsedElement = getElement( this, document );
\r
357 // Insert the empty element into the DOM at the range position.
\r
358 range.insertNode( collapsedElement );
\r
360 // Place the selection right inside the empty element.
\r
361 range.moveToPosition( collapsedElement, CKEDITOR.POSITION_BEFORE_END );
\r
366 var elementName = this.element;
\r
367 var def = this._.definition;
\r
368 var isUnknownElement;
\r
370 // Get the DTD definition for the element. Defaults to "span".
\r
371 var dtd = CKEDITOR.dtd[ elementName ] || ( isUnknownElement = true, CKEDITOR.dtd.span );
\r
373 // Bookmark the range so we can re-select it after processing.
\r
374 var bookmark = range.createBookmark();
\r
376 // Expand the range.
\r
377 range.enlarge( CKEDITOR.ENLARGE_ELEMENT );
\r
380 // Get the first node to be processed and the last, which concludes the
\r
382 var boundaryNodes = range.getBoundaryNodes();
\r
383 var firstNode = boundaryNodes.startNode;
\r
384 var lastNode = boundaryNodes.endNode.getNextSourceNode( true );
\r
386 // Probably the document end is reached, we need a marker node.
\r
390 lastNode = marker = document.createText( '' );
\r
391 lastNode.insertAfter( range.endContainer );
\r
393 // The detection algorithm below skips the contents inside bookmark nodes, so
\r
394 // we'll need to make sure lastNode isn't the inside a bookmark node.
\r
395 var lastParent = lastNode.getParent();
\r
396 if ( lastParent && lastParent.getAttribute( '_fck_bookmark' ) )
\r
397 lastNode = lastParent;
\r
399 if ( lastNode.equals( firstNode ) )
\r
401 // If the last node is the same as the the first one, we must move
\r
402 // it to the next one, otherwise the first one will not be
\r
404 lastNode = lastNode.getNextSourceNode( true );
\r
406 // It may happen that there are no more nodes after it (the end of
\r
407 // the document), so we must add something there to make our code
\r
411 lastNode = marker = document.createText( '' );
\r
412 lastNode.insertAfter( firstNode );
\r
416 var currentNode = firstNode;
\r
420 while ( currentNode )
\r
422 var applyStyle = false;
\r
424 if ( currentNode.equals( lastNode ) )
\r
426 currentNode = null;
\r
431 var nodeType = currentNode.type;
\r
432 var nodeName = nodeType == CKEDITOR.NODE_ELEMENT ? currentNode.getName() : null;
\r
434 if ( nodeName && currentNode.getAttribute( '_fck_bookmark' ) )
\r
436 currentNode = currentNode.getNextSourceNode( true );
\r
440 // Check if the current node can be a child of the style element.
\r
441 if ( !nodeName || ( dtd[ nodeName ]
\r
442 && ( currentNode.getPosition( lastNode ) | CKEDITOR.POSITION_PRECEDING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_PRECEDING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED )
\r
443 && ( !def.childRule || def.childRule( currentNode ) ) ) )
\r
445 var currentParent = currentNode.getParent();
\r
447 // Check if the style element can be a child of the current
\r
448 // node parent or if the element is not defined in the DTD.
\r
450 && ( ( currentParent.getDtd() || CKEDITOR.dtd.span )[ elementName ] || isUnknownElement )
\r
451 && ( !def.parentRule || def.parentRule( currentParent ) ) )
\r
453 // This node will be part of our range, so if it has not
\r
454 // been started, place its start right before the node.
\r
455 // In the case of an element node, it will be included
\r
456 // only if it is entirely inside the range.
\r
457 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
459 styleRange = new CKEDITOR.dom.range( document );
\r
460 styleRange.setStartBefore( currentNode );
\r
463 // Non element nodes, or empty elements can be added
\r
464 // completely to the range.
\r
465 if ( nodeType == CKEDITOR.NODE_TEXT || ( nodeType == CKEDITOR.NODE_ELEMENT && !currentNode.getChildCount() ) )
\r
467 var includedNode = currentNode;
\r
470 // This node is about to be included completelly, but,
\r
471 // if this is the last node in its parent, we must also
\r
472 // check if the parent itself can be added completelly
\r
474 while ( !includedNode.$.nextSibling
\r
475 && ( parentNode = includedNode.getParent(), dtd[ parentNode.getName() ] )
\r
476 && ( parentNode.getPosition( firstNode ) | CKEDITOR.POSITION_FOLLOWING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_FOLLOWING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED )
\r
477 && ( !def.childRule || def.childRule( parentNode ) ) )
\r
479 includedNode = parentNode;
\r
482 styleRange.setEndAfter( includedNode );
\r
484 // If the included node still is the last node in its
\r
485 // parent, it means that the parent can't be included
\r
486 // in this style DTD, so apply the style immediately.
\r
487 if ( !includedNode.$.nextSibling )
\r
498 // Get the next node to be processed.
\r
499 currentNode = currentNode.getNextSourceNode();
\r
502 // Apply the style if we have something to which apply it.
\r
503 if ( applyStyle && styleRange && !styleRange.collapsed )
\r
505 // Build the style element, based on the style object definition.
\r
506 var styleNode = getElement( this, document );
\r
508 // Get the element that holds the entire range.
\r
509 var parent = styleRange.getCommonAncestor();
\r
511 // Loop through the parents, removing the redundant attributes
\r
512 // from the element to be applied.
\r
513 while ( styleNode && parent )
\r
515 if ( parent.getName() == elementName )
\r
517 for ( var attName in def.attributes )
\r
519 if ( styleNode.getAttribute( attName ) == parent.getAttribute( attName ) )
\r
520 styleNode.removeAttribute( attName );
\r
523 for ( var styleName in def.styles )
\r
525 if ( styleNode.getStyle( styleName ) == parent.getStyle( styleName ) )
\r
526 styleNode.removeStyle( styleName );
\r
529 if ( !styleNode.hasAttributes() )
\r
536 parent = parent.getParent();
\r
541 // Move the contents of the range to the style element.
\r
542 styleRange.extractContents().appendTo( styleNode );
\r
544 // Here we do some cleanup, removing all duplicated
\r
545 // elements from the style element.
\r
546 removeFromInsideElement( this, styleNode );
\r
548 // Insert it into the range position (it is collapsed after
\r
549 // extractContents.
\r
550 styleRange.insertNode( styleNode );
\r
552 // Let's merge our new style with its neighbors, if possible.
\r
553 mergeSiblings( styleNode );
\r
555 // As the style system breaks text nodes constantly, let's normalize
\r
556 // things for performance.
\r
557 // With IE, some paragraphs get broken when calling normalize()
\r
558 // repeatedly. Also, for IE, we must normalize body, not documentElement.
\r
559 // IE is also known for having a "crash effect" with normalize().
\r
560 // We should try to normalize with IE too in some way, somewhere.
\r
561 if ( !CKEDITOR.env.ie )
\r
562 styleNode.$.normalize();
\r
565 // Style applied, let's release the range, so it gets
\r
566 // re-initialization in the next loop.
\r
571 // Remove the temporary marking node.(#4111)
\r
572 marker && marker.remove();
\r
573 range.moveToBookmark( bookmark );
\r
574 // Minimize the result range to exclude empty text nodes. (#5374)
\r
575 range.shrink( CKEDITOR.SHRINK_TEXT );
\r
578 function removeInlineStyle( range )
\r
581 * Make sure our range has included all "collpased" parent inline nodes so
\r
582 * that our operation logic can be simpler.
\r
584 range.enlarge( CKEDITOR.ENLARGE_ELEMENT );
\r
586 var bookmark = range.createBookmark(),
\r
587 startNode = bookmark.startNode;
\r
589 if ( range.collapsed )
\r
592 var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),
\r
593 // The topmost element in elementspatch which we should jump out of.
\r
597 for ( var i = 0, element ; i < startPath.elements.length
\r
598 && ( element = startPath.elements[i] ) ; i++ )
\r
601 * 1. If it's collaped inside text nodes, try to remove the style from the whole element.
\r
603 * 2. Otherwise if it's collapsed on element boundaries, moving the selection
\r
604 * outside the styles instead of removing the whole tag,
\r
605 * also make sure other inner styles were well preserverd.(#3309)
\r
607 if ( element == startPath.block || element == startPath.blockLimit )
\r
610 if ( this.checkElementRemovable( element ) )
\r
612 var endOfElement = range.checkBoundaryOfElement( element, CKEDITOR.END ),
\r
613 startOfElement = !endOfElement && range.checkBoundaryOfElement( element, CKEDITOR.START );
\r
614 if ( startOfElement || endOfElement )
\r
616 boundaryElement = element;
\r
617 boundaryElement.match = startOfElement ? 'start' : 'end';
\r
622 * Before removing the style node, there may be a sibling to the style node
\r
623 * that's exactly the same to the one to be removed. To the user, it makes
\r
624 * no difference that they're separate entities in the DOM tree. So, merge
\r
625 * them before removal.
\r
627 mergeSiblings( element );
\r
628 removeFromElement( this, element );
\r
634 // Re-create the style tree after/before the boundary element,
\r
635 // the replication start from bookmark start node to define the
\r
637 if ( boundaryElement )
\r
639 var clonedElement = startNode;
\r
640 for ( i = 0 ;; i++ )
\r
642 var newElement = startPath.elements[ i ];
\r
643 if ( newElement.equals( boundaryElement ) )
\r
645 // Avoid copying any matched element.
\r
646 else if ( newElement.match )
\r
649 newElement = newElement.clone();
\r
650 newElement.append( clonedElement );
\r
651 clonedElement = newElement;
\r
653 clonedElement[ boundaryElement.match == 'start' ?
\r
654 'insertBefore' : 'insertAfter' ]( boundaryElement );
\r
660 * Now our range isn't collapsed. Lets walk from the start node to the end
\r
661 * node via DFS and remove the styles one-by-one.
\r
663 var endNode = bookmark.endNode,
\r
667 * Find out the style ancestor that needs to be broken down at startNode
\r
670 function breakNodes()
\r
672 var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),
\r
673 endPath = new CKEDITOR.dom.elementPath( endNode.getParent() ),
\r
676 for ( var i = 0 ; i < startPath.elements.length ; i++ )
\r
678 var element = startPath.elements[ i ];
\r
680 if ( element == startPath.block || element == startPath.blockLimit )
\r
683 if ( me.checkElementRemovable( element ) )
\r
684 breakStart = element;
\r
686 for ( i = 0 ; i < endPath.elements.length ; i++ )
\r
688 element = endPath.elements[ i ];
\r
690 if ( element == endPath.block || element == endPath.blockLimit )
\r
693 if ( me.checkElementRemovable( element ) )
\r
694 breakEnd = element;
\r
698 endNode.breakParent( breakEnd );
\r
700 startNode.breakParent( breakStart );
\r
704 // Now, do the DFS walk.
\r
705 var currentNode = startNode.getNext();
\r
706 while ( !currentNode.equals( endNode ) )
\r
709 * Need to get the next node first because removeFromElement() can remove
\r
710 * the current node from DOM tree.
\r
712 var nextNode = currentNode.getNextSourceNode();
\r
713 if ( currentNode.type == CKEDITOR.NODE_ELEMENT && this.checkElementRemovable( currentNode ) )
\r
715 // Remove style from element or overriding element.
\r
716 if ( currentNode.getName() == this.element )
\r
717 removeFromElement( this, currentNode );
\r
719 removeOverrides( currentNode, getOverrides( this )[ currentNode.getName() ] );
\r
722 * removeFromElement() may have merged the next node with something before
\r
723 * the startNode via mergeSiblings(). In that case, the nextNode would
\r
724 * contain startNode and we'll have to call breakNodes() again and also
\r
725 * reassign the nextNode to something after startNode.
\r
727 if ( nextNode.type == CKEDITOR.NODE_ELEMENT && nextNode.contains( startNode ) )
\r
730 nextNode = startNode.getNext();
\r
733 currentNode = nextNode;
\r
737 range.moveToBookmark( bookmark );
\r
740 function applyObjectStyle( range )
\r
742 var root = range.getCommonAncestor( true, true ),
\r
743 element = root.getAscendant( this.element, true );
\r
744 element && setupElement( element, this );
\r
747 function applyBlockStyle( range )
\r
749 // Serializible bookmarks is needed here since
\r
750 // elements may be merged.
\r
751 var bookmark = range.createBookmark( true );
\r
753 var iterator = range.createIterator();
\r
754 iterator.enforceRealBlocks = true;
\r
757 var doc = range.document;
\r
758 var previousPreBlock;
\r
760 while ( ( block = iterator.getNextParagraph() ) ) // Only one =
\r
762 var newBlock = getElement( this, doc );
\r
763 replaceBlock( block, newBlock );
\r
766 range.moveToBookmark( bookmark );
\r
769 // Replace the original block with new one, with special treatment
\r
770 // for <pre> blocks to make sure content format is well preserved, and merging/splitting adjacent
\r
771 // when necessary.(#3188)
\r
772 function replaceBlock( block, newBlock )
\r
774 var newBlockIsPre = newBlock.is( 'pre' );
\r
775 var blockIsPre = block.is( 'pre' );
\r
777 var isToPre = newBlockIsPre && !blockIsPre;
\r
778 var isFromPre = !newBlockIsPre && blockIsPre;
\r
781 newBlock = toPre( block, newBlock );
\r
782 else if ( isFromPre )
\r
783 // Split big <pre> into pieces before start to convert.
\r
784 newBlock = fromPres( splitIntoPres( block ), newBlock );
\r
786 block.moveChildren( newBlock );
\r
788 newBlock.replace( block );
\r
790 if ( newBlockIsPre )
\r
792 // Merge previous <pre> blocks.
\r
793 mergePre( newBlock );
\r
798 * Merge a <pre> block with a previous sibling if available.
\r
800 function mergePre( preBlock )
\r
803 if ( !( ( previousBlock = preBlock.getPreviousSourceNode( true, CKEDITOR.NODE_ELEMENT ) )
\r
804 && previousBlock.is
\r
805 && previousBlock.is( 'pre') ) )
\r
808 // Merge the previous <pre> block contents into the current <pre>
\r
811 // Another thing to be careful here is that currentBlock might contain
\r
812 // a '\n' at the beginning, and previousBlock might contain a '\n'
\r
813 // towards the end. These new lines are not normally displayed but they
\r
814 // become visible after merging.
\r
815 var mergedHtml = replace( previousBlock.getHtml(), /\n$/, '' ) + '\n\n' +
\r
816 replace( preBlock.getHtml(), /^\n/, '' ) ;
\r
818 // Krugle: IE normalizes innerHTML from <pre>, breaking whitespaces.
\r
819 if ( CKEDITOR.env.ie )
\r
820 preBlock.$.outerHTML = '<pre>' + mergedHtml + '</pre>';
\r
822 preBlock.setHtml( mergedHtml );
\r
824 previousBlock.remove();
\r
828 * Split into multiple <pre> blocks separated by double line-break.
\r
831 function splitIntoPres( preBlock )
\r
833 // Exclude the ones at header OR at tail,
\r
834 // and ignore bookmark content between them.
\r
835 var duoBrRegex = /(\S\s*)\n(?:\s|(<span[^>]+_fck_bookmark.*?\/span>))*\n(?!$)/gi,
\r
836 blockName = preBlock.getName(),
\r
837 splitedHtml = replace( preBlock.getOuterHtml(),
\r
839 function( match, charBefore, bookmark )
\r
841 return charBefore + '</pre>' + bookmark + '<pre>';
\r
845 splitedHtml.replace( /<pre\b.*?>([\s\S]*?)<\/pre>/gi, function( match, preContent ){
\r
846 pres.push( preContent );
\r
851 // Wrapper function of String::replace without considering of head/tail bookmarks nodes.
\r
852 function replace( str, regexp, replacement )
\r
854 var headBookmark = '',
\r
857 str = str.replace( /(^<span[^>]+_fck_bookmark.*?\/span>)|(<span[^>]+_fck_bookmark.*?\/span>$)/gi,
\r
858 function( str, m1, m2 ){
\r
859 m1 && ( headBookmark = m1 );
\r
860 m2 && ( tailBookmark = m2 );
\r
863 return headBookmark + str.replace( regexp, replacement ) + tailBookmark;
\r
866 * Converting a list of <pre> into blocks with format well preserved.
\r
868 function fromPres( preHtmls, newBlock )
\r
870 var docFrag = new CKEDITOR.dom.documentFragment( newBlock.getDocument() );
\r
871 for ( var i = 0 ; i < preHtmls.length ; i++ )
\r
873 var blockHtml = preHtmls[ i ];
\r
875 // 1. Trim the first and last line-breaks immediately after and before <pre>,
\r
876 // they're not visible.
\r
877 blockHtml = blockHtml.replace( /(\r\n|\r)/g, '\n' ) ;
\r
878 blockHtml = replace( blockHtml, /^[ \t]*\n/, '' ) ;
\r
879 blockHtml = replace( blockHtml, /\n$/, '' ) ;
\r
880 // 2. Convert spaces or tabs at the beginning or at the end to
\r
881 blockHtml = replace( blockHtml, /^[ \t]+|[ \t]+$/g, function( match, offset, s )
\r
883 if ( match.length == 1 ) // one space, preserve it
\r
885 else if ( !offset ) // beginning of block
\r
886 return CKEDITOR.tools.repeat( ' ', match.length - 1 ) + ' ';
\r
887 else // end of block
\r
888 return ' ' + CKEDITOR.tools.repeat( ' ', match.length - 1 );
\r
891 // 3. Convert \n to <BR>.
\r
892 // 4. Convert contiguous (i.e. non-singular) spaces or tabs to
\r
893 blockHtml = blockHtml.replace( /\n/g, '<br>' ) ;
\r
894 blockHtml = blockHtml.replace( /[ \t]{2,}/g,
\r
897 return CKEDITOR.tools.repeat( ' ', match.length - 1 ) + ' ' ;
\r
900 var newBlockClone = newBlock.clone();
\r
901 newBlockClone.setHtml( blockHtml );
\r
902 docFrag.append( newBlockClone );
\r
908 * Converting from a non-PRE block to a PRE block in formatting operations.
\r
910 function toPre( block, newBlock )
\r
912 // First trim the block content.
\r
913 var preHtml = block.getHtml();
\r
915 // 1. Trim head/tail spaces, they're not visible.
\r
916 preHtml = replace( preHtml, /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '' );
\r
917 // 2. Delete ANSI whitespaces immediately before and after <BR> because
\r
918 // they are not visible.
\r
919 preHtml = preHtml.replace( /[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi, '$1' );
\r
920 // 3. Compress other ANSI whitespaces since they're only visible as one
\r
921 // single space previously.
\r
922 // 4. Convert to spaces since is no longer needed in <PRE>.
\r
923 preHtml = preHtml.replace( /([ \t\n\r]+| )/g, ' ' );
\r
924 // 5. Convert any <BR /> to \n. This must not be done earlier because
\r
925 // the \n would then get compressed.
\r
926 preHtml = preHtml.replace( /<br\b[^>]*>/gi, '\n' );
\r
928 // Krugle: IE normalizes innerHTML to <pre>, breaking whitespaces.
\r
929 if ( CKEDITOR.env.ie )
\r
931 var temp = block.getDocument().createElement( 'div' );
\r
932 temp.append( newBlock );
\r
933 newBlock.$.outerHTML = '<pre>' + preHtml + '</pre>';
\r
934 newBlock = temp.getFirst().remove();
\r
937 newBlock.setHtml( preHtml );
\r
942 // Removes a style from an element itself, don't care about its subtree.
\r
943 function removeFromElement( style, element )
\r
945 var def = style._.definition,
\r
946 attributes = CKEDITOR.tools.extend( {}, def.attributes, getOverrides( style )[ element.getName() ] ),
\r
947 styles = def.styles,
\r
948 // If the style is only about the element itself, we have to remove the element.
\r
949 removeEmpty = CKEDITOR.tools.isEmpty( attributes ) && CKEDITOR.tools.isEmpty( styles );
\r
951 // Remove definition attributes/style from the elemnt.
\r
952 for ( var attName in attributes )
\r
954 // The 'class' element value must match (#1318).
\r
955 if ( ( attName == 'class' || style._.definition.fullMatch )
\r
956 && element.getAttribute( attName ) != normalizeProperty( attName, attributes[ attName ] ) )
\r
958 removeEmpty = element.hasAttribute( attName );
\r
959 element.removeAttribute( attName );
\r
962 for ( var styleName in styles )
\r
964 // Full match style insist on having fully equivalence. (#5018)
\r
965 if ( style._.definition.fullMatch
\r
966 && element.getStyle( styleName ) != normalizeProperty( styleName, styles[ styleName ], true ) )
\r
969 removeEmpty = removeEmpty || !!element.getStyle( styleName );
\r
970 element.removeStyle( styleName );
\r
973 removeEmpty && removeNoAttribsElement( element );
\r
976 // Removes a style from inside an element.
\r
977 function removeFromInsideElement( style, element )
\r
979 var def = style._.definition,
\r
980 attribs = def.attributes,
\r
981 styles = def.styles,
\r
982 overrides = getOverrides( style );
\r
984 var innerElements = element.getElementsByTag( style.element );
\r
986 for ( var i = innerElements.count(); --i >= 0 ; )
\r
987 removeFromElement( style, innerElements.getItem( i ) );
\r
989 // Now remove any other element with different name that is
\r
990 // defined to be overriden.
\r
991 for ( var overrideElement in overrides )
\r
993 if ( overrideElement != style.element )
\r
995 innerElements = element.getElementsByTag( overrideElement ) ;
\r
996 for ( i = innerElements.count() - 1 ; i >= 0 ; i-- )
\r
998 var innerElement = innerElements.getItem( i );
\r
999 removeOverrides( innerElement, overrides[ overrideElement ] ) ;
\r
1007 * Remove overriding styles/attributes from the specific element.
\r
1008 * Note: Remove the element if no attributes remain.
\r
1009 * @param {Object} element
\r
1010 * @param {Object} overrides
\r
1012 function removeOverrides( element, overrides )
\r
1014 var attributes = overrides && overrides.attributes ;
\r
1018 for ( var i = 0 ; i < attributes.length ; i++ )
\r
1020 var attName = attributes[i][0], actualAttrValue ;
\r
1022 if ( ( actualAttrValue = element.getAttribute( attName ) ) )
\r
1024 var attValue = attributes[i][1] ;
\r
1026 // Remove the attribute if:
\r
1027 // - The override definition value is null ;
\r
1028 // - The override definition valie is a string that
\r
1029 // matches the attribute value exactly.
\r
1030 // - The override definition value is a regex that
\r
1031 // has matches in the attribute value.
\r
1032 if ( attValue === null ||
\r
1033 ( attValue.test && attValue.test( actualAttrValue ) ) ||
\r
1034 ( typeof attValue == 'string' && actualAttrValue == attValue ) )
\r
1035 element.removeAttribute( attName ) ;
\r
1040 removeNoAttribsElement( element );
\r
1043 // If the element has no more attributes, remove it.
\r
1044 function removeNoAttribsElement( element )
\r
1046 // If no more attributes remained in the element, remove it,
\r
1047 // leaving its children.
\r
1048 if ( !element.hasAttributes() )
\r
1050 // Removing elements may open points where merging is possible,
\r
1051 // so let's cache the first and last nodes for later checking.
\r
1052 var firstChild = element.getFirst();
\r
1053 var lastChild = element.getLast();
\r
1055 element.remove( true );
\r
1059 // Check the cached nodes for merging.
\r
1060 mergeSiblings( firstChild );
\r
1062 if ( lastChild && !firstChild.equals( lastChild ) )
\r
1063 mergeSiblings( lastChild );
\r
1068 function mergeSiblings( element )
\r
1070 if ( !element || element.type != CKEDITOR.NODE_ELEMENT || !CKEDITOR.dtd.$removeEmpty[ element.getName() ] )
\r
1073 mergeElements( element, element.getNext(), true );
\r
1074 mergeElements( element, element.getPrevious() );
\r
1077 function mergeElements( element, sibling, isNext )
\r
1079 if ( sibling && sibling.type == CKEDITOR.NODE_ELEMENT )
\r
1081 var hasBookmark = sibling.getAttribute( '_fck_bookmark' );
\r
1083 if ( hasBookmark )
\r
1084 sibling = isNext ? sibling.getNext() : sibling.getPrevious();
\r
1086 if ( sibling && sibling.type == CKEDITOR.NODE_ELEMENT && element.isIdentical( sibling ) )
\r
1088 // Save the last child to be checked too, to merge things like
\r
1089 // <b><i></i></b><b><i></i></b> => <b><i></i></b>
\r
1090 var innerSibling = isNext ? element.getLast() : element.getFirst();
\r
1092 if ( hasBookmark )
\r
1093 ( isNext ? sibling.getPrevious() : sibling.getNext() ).move( element, !isNext );
\r
1095 sibling.moveChildren( element, !isNext );
\r
1098 // Now check the last inner child (see two comments above).
\r
1099 if ( innerSibling )
\r
1100 mergeSiblings( innerSibling );
\r
1105 function getElement( style, targetDocument )
\r
1109 var def = style._.definition;
\r
1111 var elementName = style.element;
\r
1113 // The "*" element name will always be a span for this function.
\r
1114 if ( elementName == '*' )
\r
1115 elementName = 'span';
\r
1117 // Create the element.
\r
1118 el = new CKEDITOR.dom.element( elementName, targetDocument );
\r
1120 return setupElement( el, style );
\r
1123 function setupElement( el, style )
\r
1125 var def = style._.definition;
\r
1126 var attributes = def.attributes;
\r
1127 var styles = CKEDITOR.style.getStyleText( def );
\r
1129 // Assign all defined attributes.
\r
1132 for ( var att in attributes )
\r
1134 el.setAttribute( att, attributes[ att ] );
\r
1138 // Assign all defined styles.
\r
1140 el.setAttribute( 'style', styles );
\r
1145 var varRegex = /#\((.+?)\)/g;
\r
1146 function replaceVariables( list, variablesValues )
\r
1148 for ( var item in list )
\r
1150 list[ item ] = list[ item ].replace( varRegex, function( match, varName )
\r
1152 return variablesValues[ varName ];
\r
1158 // Returns an object that can be used for style matching comparison.
\r
1159 // Attributes names and values are all lowercased, and the styles get
\r
1160 // merged with the style attribute.
\r
1161 function getAttributesForComparison( styleDefinition )
\r
1163 // If we have already computed it, just return it.
\r
1164 var attribs = styleDefinition._AC;
\r
1172 // Loop through all defined attributes.
\r
1173 var styleAttribs = styleDefinition.attributes;
\r
1174 if ( styleAttribs )
\r
1176 for ( var styleAtt in styleAttribs )
\r
1179 attribs[ styleAtt ] = styleAttribs[ styleAtt ];
\r
1183 // Includes the style definitions.
\r
1184 var styleText = CKEDITOR.style.getStyleText( styleDefinition );
\r
1187 if ( !attribs[ 'style' ] )
\r
1189 attribs[ 'style' ] = styleText;
\r
1192 // Appends the "length" information to the object.
\r
1193 attribs._length = length;
\r
1195 // Return it, saving it to the next request.
\r
1196 return ( styleDefinition._AC = attribs );
\r
1200 * Get the the collection used to compare the elements and attributes,
\r
1201 * defined in this style overrides, with other element. All information in
\r
1202 * it is lowercased.
\r
1203 * @param {CKEDITOR.style} style
\r
1205 function getOverrides( style )
\r
1207 if ( style._.overrides )
\r
1208 return style._.overrides;
\r
1210 var overrides = ( style._.overrides = {} ),
\r
1211 definition = style._.definition.overrides;
\r
1215 // The override description can be a string, object or array.
\r
1216 // Internally, well handle arrays only, so transform it if needed.
\r
1217 if ( !CKEDITOR.tools.isArray( definition ) )
\r
1218 definition = [ definition ];
\r
1220 // Loop through all override definitions.
\r
1221 for ( var i = 0 ; i < definition.length ; i++ )
\r
1223 var override = definition[i];
\r
1228 // If can be a string with the element name.
\r
1229 if ( typeof override == 'string' )
\r
1230 elementName = override.toLowerCase();
\r
1234 elementName = override.element ? override.element.toLowerCase() : style.element;
\r
1235 attrs = override.attributes;
\r
1238 // We can have more than one override definition for the same
\r
1239 // element name, so we attempt to simply append information to
\r
1240 // it if it already exists.
\r
1241 overrideEl = overrides[ elementName ] || ( overrides[ elementName ] = {} );
\r
1245 // The returning attributes list is an array, because we
\r
1246 // could have different override definitions for the same
\r
1247 // attribute name.
\r
1248 var overrideAttrs = ( overrideEl.attributes = overrideEl.attributes || new Array() );
\r
1249 for ( var attName in attrs )
\r
1251 // Each item in the attributes array is also an array,
\r
1252 // where [0] is the attribute name and [1] is the
\r
1253 // override value.
\r
1254 overrideAttrs.push( [ attName.toLowerCase(), attrs[ attName ] ] );
\r
1263 function normalizeProperty( name, value, isStyle )
\r
1265 var temp = new CKEDITOR.dom.element( 'span' );
\r
1266 temp [ isStyle ? 'setStyle' : 'setAttribute' ]( name, value );
\r
1267 return temp[ isStyle ? 'getStyle' : 'getAttribute' ]( name );
\r
1270 function normalizeCssText( unparsedCssText, nativeNormalize )
\r
1273 if ( nativeNormalize !== false )
\r
1275 // Injects the style in a temporary span object, so the browser parses it,
\r
1276 // retrieving its final format.
\r
1277 var temp = new CKEDITOR.dom.element( 'span' );
\r
1278 temp.setAttribute( 'style', unparsedCssText );
\r
1279 styleText = temp.getAttribute( 'style' ) || '';
\r
1282 styleText = unparsedCssText;
\r
1284 // Shrinking white-spaces around colon and semi-colon (#4147).
\r
1285 // Compensate tail semi-colon.
\r
1286 return styleText.replace( /\s*([;:])\s*/, '$1' )
\r
1287 .replace( /([^\s;])$/, '$1;')
\r
1288 .replace( /,\s+/g, ',' ) // Trimming spaces after comma (e.g. font-family name)(#4107).
\r
1292 // Turn inline style text properties into one hash.
\r
1293 function parseStyleText( styleText )
\r
1297 .replace( /"/g, '"' )
\r
1298 .replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value )
\r
1300 retval[ name ] = value;
\r
1305 function compareCssText( source, target )
\r
1307 typeof source == 'string' && ( source = parseStyleText( source ) );
\r
1308 typeof target == 'string' && ( target = parseStyleText( target ) );
\r
1309 for( var name in source )
\r
1311 // Value 'inherit' is treated as a wildcard,
\r
1312 // which will match any value.
\r
1313 if ( !( name in target &&
\r
1314 ( target[ name ] == source[ name ]
\r
1315 || source[ name ] == 'inherit'
\r
1316 || target[ name ] == 'inherit' ) ) )
\r
1324 function applyStyle( document, remove )
\r
1326 // Get all ranges from the selection.
\r
1327 var selection = document.getSelection();
\r
1328 var ranges = selection.getRanges();
\r
1329 var func = remove ? this.removeFromRange : this.applyToRange;
\r
1331 // Apply the style to the ranges.
\r
1332 for ( var i = 0 ; i < ranges.length ; i++ )
\r
1333 func.call( this, ranges[ i ] );
\r
1335 // Select the ranges again.
\r
1336 selection.selectRanges( ranges );
\r
1340 CKEDITOR.styleCommand = function( style )
\r
1342 this.style = style;
\r
1345 CKEDITOR.styleCommand.prototype.exec = function( editor )
\r
1349 var doc = editor.document;
\r
1353 if ( this.state == CKEDITOR.TRISTATE_OFF )
\r
1354 this.style.apply( doc );
\r
1355 else if ( this.state == CKEDITOR.TRISTATE_ON )
\r
1356 this.style.remove( doc );
\r
1362 CKEDITOR.stylesSet = new CKEDITOR.resourceManager( '', 'stylesSet' );
\r
1364 // Backward compatibility (#5025).
\r
1365 CKEDITOR.addStylesSet = CKEDITOR.tools.bind( CKEDITOR.stylesSet.add, CKEDITOR.stylesSet );
\r
1366 CKEDITOR.loadStylesSet = function( name, url, callback )
\r
1368 CKEDITOR.stylesSet.addExternal( name, url, '' );
\r
1369 CKEDITOR.stylesSet.load( name, callback );
\r
1374 * Gets the current styleSet for this instance
\r
1375 * @param {Function} The function to be called with the styles data.
\r
1377 * editor.getStylesSet( function( stylesDefinitions ) {} );
\r
1379 CKEDITOR.editor.prototype.getStylesSet = function( callback )
\r
1381 if ( !this._.stylesDefinitions )
\r
1383 var editor = this,
\r
1384 // Respect the backwards compatible definition entry
\r
1385 configStyleSet = editor.config.stylesCombo_stylesSet || editor.config.stylesSet || 'default';
\r
1387 // #5352 Allow to define the styles directly in the config object
\r
1388 if ( configStyleSet instanceof Array )
\r
1390 editor._.stylesDefinitions = configStyleSet;
\r
1391 callback( configStyleSet );
\r
1395 var partsStylesSet = configStyleSet.split( ':' ),
\r
1396 styleSetName = partsStylesSet[ 0 ],
\r
1397 externalPath = partsStylesSet[ 1 ],
\r
1398 pluginPath = CKEDITOR.plugins.registered.styles.path;
\r
1400 CKEDITOR.stylesSet.addExternal( styleSetName,
\r
1402 partsStylesSet.slice( 1 ).join( ':' ) :
\r
1403 pluginPath + 'styles/' + styleSetName + '.js', '' );
\r
1405 CKEDITOR.stylesSet.load( styleSetName, function( stylesSet )
\r
1407 editor._.stylesDefinitions = stylesSet[ styleSetName ];
\r
1408 callback( editor._.stylesDefinitions );
\r
1412 callback( this._.stylesDefinitions );
\r
1416 * The "styles definition set" to use in the editor. They will be used in the
\r
1417 * styles combo and the Style selector of the div container. <br>
\r
1418 * The styles may be defined in the page containing the editor, or can be
\r
1419 * loaded on demand from an external file. In the second case, if this setting
\r
1420 * contains only a name, the styles definition file will be loaded from the
\r
1421 * "styles" folder inside the styles plugin folder.
\r
1422 * Otherwise, this setting has the "name:url" syntax, making it
\r
1423 * possible to set the URL from which loading the styles file.<br>
\r
1424 * Previously this setting was available as config.stylesCombo_stylesSet<br>
\r
1425 * @type String|Array
\r
1426 * @default 'default'
\r
1429 * // Load from the styles' styles folder (mystyles.js file).
\r
1430 * config.stylesSet = 'mystyles';
\r
1432 * // Load from a relative URL.
\r
1433 * config.stylesSet = 'mystyles:/editorstyles/styles.js';
\r
1435 * // Load from a full URL.
\r
1436 * config.stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js';
\r
1438 * // Load from a list of definitions.
\r
1439 * config.stylesSet = [
\r
1440 * { name : 'Strong Emphasis', element : 'strong' },
\r
1441 * { name : 'Emphasis', element : 'em' }, ... ];
\r