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