2 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
3 For licensing, see LICENSE.html or http://ckeditor.com/license
7 * @file Insert and remove numbered and bulleted lists.
12 var listNodeNames = { ol : 1, ul : 1 },
13 emptyTextRegex = /^[\n\r\t ]*$/;
15 var whitespaces = CKEDITOR.dom.walker.whitespaces(),
16 bookmarks = CKEDITOR.dom.walker.bookmark(),
17 nonEmpty = function( node ){ return !( whitespaces( node ) || bookmarks( node ) ); };
19 CKEDITOR.plugins.list = {
21 * Convert a DOM list tree into a data structure that is easier to
22 * manipulate. This operation should be non-intrusive in the sense that it
23 * does not change the DOM tree, with the exception that it may add some
24 * markers to the list item nodes when database is specified.
26 listToArray : function( listNode, database, baseArray, baseIndentLevel, grandparentNode )
28 if ( !listNodeNames[ listNode.getName() ] )
31 if ( !baseIndentLevel )
36 // Iterate over all list items to and look for inner lists.
37 for ( var i = 0, count = listNode.getChildCount() ; i < count ; i++ )
39 var listItem = listNode.getChild( i );
41 // It may be a text node or some funny stuff.
42 if ( listItem.$.nodeName.toLowerCase() != 'li' )
45 var itemObj = { 'parent' : listNode, indent : baseIndentLevel, element : listItem, contents : [] };
46 if ( !grandparentNode )
48 itemObj.grandparent = listNode.getParent();
49 if ( itemObj.grandparent && itemObj.grandparent.$.nodeName.toLowerCase() == 'li' )
50 itemObj.grandparent = itemObj.grandparent.getParent();
53 itemObj.grandparent = grandparentNode;
56 CKEDITOR.dom.element.setMarker( database, listItem, 'listarray_index', baseArray.length );
57 baseArray.push( itemObj );
59 for ( var j = 0, itemChildCount = listItem.getChildCount(), child; j < itemChildCount ; j++ )
61 child = listItem.getChild( j );
62 if ( child.type == CKEDITOR.NODE_ELEMENT && listNodeNames[ child.getName() ] )
63 // Note the recursion here, it pushes inner list items with
64 // +1 indentation in the correct order.
65 CKEDITOR.plugins.list.listToArray( child, database, baseArray, baseIndentLevel + 1, itemObj.grandparent );
67 itemObj.contents.push( child );
73 // Convert our internal representation of a list back to a DOM forest.
74 arrayToList : function( listArray, database, baseIndex, paragraphMode, dir )
78 if ( !listArray || listArray.length < baseIndex + 1 )
80 var doc = listArray[ baseIndex ].parent.getDocument(),
81 retval = new CKEDITOR.dom.documentFragment( doc ),
83 currentIndex = baseIndex,
84 indentLevel = Math.max( listArray[ baseIndex ].indent, 0 ),
85 currentListItem = null,
86 paragraphName = ( paragraphMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
89 var item = listArray[ currentIndex ];
90 if ( item.indent == indentLevel )
92 if ( !rootNode || listArray[ currentIndex ].parent.getName() != rootNode.getName() )
94 rootNode = listArray[ currentIndex ].parent.clone( false, 1 );
95 dir && rootNode.setAttribute( 'dir', dir );
96 retval.append( rootNode );
98 currentListItem = rootNode.append( item.element.clone( 0, 1 ) );
99 for ( var i = 0 ; i < item.contents.length ; i++ )
100 currentListItem.append( item.contents[i].clone( 1, 1 ) );
103 else if ( item.indent == Math.max( indentLevel, 0 ) + 1 )
105 var listData = CKEDITOR.plugins.list.arrayToList( listArray, null, currentIndex, paragraphMode );
107 // If the next block is an <li> with another list tree as the first
108 // child, we'll need to append a filler (<br>/NBSP) or the list item
109 // wouldn't be editable. (#6724)
110 if ( !currentListItem.getChildCount() && CKEDITOR.env.ie && !( doc.$.documentMode > 7 ))
111 currentListItem.append( doc.createText( '\xa0' ) );
112 currentListItem.append( listData.listNode );
113 currentIndex = listData.nextIndex;
115 else if ( item.indent == -1 && !baseIndex && item.grandparent )
118 if ( listNodeNames[ item.grandparent.getName() ] )
119 currentListItem = item.element.clone( false, true );
122 // Create completely new blocks here.
123 if ( dir || item.element.hasAttributes() || paragraphMode != CKEDITOR.ENTER_BR )
125 currentListItem = doc.createElement( paragraphName );
126 item.element.copyAttributes( currentListItem, { type:1, value:1 } );
127 var itemDir = item.element.getDirection() || dir;
129 currentListItem.setAttribute( 'dir', itemDir );
131 // There might be a case where there are no attributes in the element after all
132 // (i.e. when "type" or "value" are the only attributes set). In this case, if enterMode = BR,
133 // the current item should be a fragment.
134 if ( !dir && paragraphMode == CKEDITOR.ENTER_BR && !currentListItem.hasAttributes() )
135 currentListItem = new CKEDITOR.dom.documentFragment( doc );
138 currentListItem = new CKEDITOR.dom.documentFragment( doc );
141 for ( i = 0 ; i < item.contents.length ; i++ )
142 currentListItem.append( item.contents[i].clone( 1, 1 ) );
144 if ( currentListItem.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT
145 && currentIndex != listArray.length - 1 )
147 var last = currentListItem.getLast();
148 //if ( last && last.type == CKEDITOR.NODE_ELEMENT
149 // && last.getAttribute( 'type' ) == '_moz' )
154 //if ( !( last = currentListItem.getLast( nonEmpty )
155 // && last.type == CKEDITOR.NODE_ELEMENT
156 // && last.getName() in CKEDITOR.dtd.$block ) )
158 // currentListItem.append( doc.createElement( 'br' ) );
162 if ( currentListItem.type == CKEDITOR.NODE_ELEMENT &&
163 currentListItem.getName() == paragraphName &&
164 currentListItem.$.firstChild )
166 currentListItem.trim();
167 var firstChild = currentListItem.getFirst();
168 if ( firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.isBlockBoundary() )
170 var tmp = new CKEDITOR.dom.documentFragment( doc );
171 currentListItem.moveChildren( tmp );
172 currentListItem = tmp;
176 var currentListItemName = currentListItem.$.nodeName.toLowerCase();
177 if ( !CKEDITOR.env.ie && ( currentListItemName == 'div' || currentListItemName == 'p' ) )
178 currentListItem.appendBogus();
179 retval.append( currentListItem );
186 if ( listArray.length <= currentIndex || Math.max( listArray[ currentIndex ].indent, 0 ) < indentLevel )
190 // Clear marker attributes for the new list tree made of cloned nodes, if any.
193 var currentNode = retval.getFirst();
194 while ( currentNode )
196 if ( currentNode.type == CKEDITOR.NODE_ELEMENT )
197 CKEDITOR.dom.element.clearMarkers( database, currentNode );
198 currentNode = currentNode.getNextSourceNode();
202 return { listNode : retval, nextIndex : currentIndex };
206 function onSelectionChange( evt )
208 var path = evt.data.path,
209 blockLimit = path.blockLimit,
210 elements = path.elements,
214 // Grouping should only happen under blockLimit.(#3940).
215 for ( i = 0 ; i < elements.length && ( element = elements[ i ] )
216 && !element.equals( blockLimit ); i++ )
218 if ( listNodeNames[ elements[i].getName() ] )
219 return this.setState( this.type == elements[i].getName() ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
222 return this.setState( CKEDITOR.TRISTATE_OFF );
225 function changeListType( editor, groupObj, database, listsCreated )
227 // This case is easy...
228 // 1. Convert the whole list into a one-dimensional array.
229 // 2. Change the list type by modifying the array.
230 // 3. Recreate the whole list by converting the array to a list.
231 // 4. Replace the original list with the recreated list.
232 var listArray = CKEDITOR.plugins.list.listToArray( groupObj.root, database ),
233 selectedListItems = [];
235 for ( var i = 0 ; i < groupObj.contents.length ; i++ )
237 var itemNode = groupObj.contents[i];
238 itemNode = itemNode.getAscendant( 'li', true );
239 if ( !itemNode || itemNode.getCustomData( 'list_item_processed' ) )
241 selectedListItems.push( itemNode );
242 CKEDITOR.dom.element.setMarker( database, itemNode, 'list_item_processed', true );
245 var root = groupObj.root,
246 fakeParent = root.getDocument().createElement( this.type );
247 // Copy all attributes, except from 'start' and 'type'.
248 root.copyAttributes( fakeParent, { start : 1, type : 1 } );
249 // The list-style-type property should be ignored.
250 fakeParent.removeStyle( 'list-style-type' );
252 for ( i = 0 ; i < selectedListItems.length ; i++ )
254 var listIndex = selectedListItems[i].getCustomData( 'listarray_index' );
255 listArray[listIndex].parent = fakeParent;
257 var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode );
258 var child, length = newList.listNode.getChildCount();
259 for ( i = 0 ; i < length && ( child = newList.listNode.getChild( i ) ) ; i++ )
261 if ( child.getName() == this.type )
262 listsCreated.push( child );
264 newList.listNode.replace( groupObj.root );
267 var headerTagRegex = /^h[1-6]$/;
269 function createList( editor, groupObj, listsCreated )
271 var contents = groupObj.contents,
272 doc = groupObj.root.getDocument(),
275 // It is possible to have the contents returned by DomRangeIterator to be the same as the root.
276 // e.g. when we're running into table cells.
277 // In such a case, enclose the childNodes of contents[0] into a <div>.
278 if ( contents.length == 1 && contents[0].equals( groupObj.root ) )
280 var divBlock = doc.createElement( 'div' );
281 contents[0].moveChildren && contents[0].moveChildren( divBlock );
282 contents[0].append( divBlock );
283 contents[0] = divBlock;
286 // Calculate the common parent node of all content blocks.
287 var commonParent = groupObj.contents[0].getParent();
288 for ( var i = 0 ; i < contents.length ; i++ )
289 commonParent = commonParent.getCommonAncestor( contents[i].getParent() );
291 var useComputedState = editor.config.useComputedState,
292 listDir, explicitDirection;
294 useComputedState = useComputedState === undefined || useComputedState;
296 // We want to insert things that are in the same tree level only, so calculate the contents again
297 // by expanding the selected blocks to the same tree level.
298 for ( i = 0 ; i < contents.length ; i++ )
300 var contentNode = contents[i],
302 while ( ( parentNode = contentNode.getParent() ) )
304 if ( parentNode.equals( commonParent ) )
306 listContents.push( contentNode );
308 // Determine the lists's direction.
309 if ( !explicitDirection && contentNode.getDirection() )
310 explicitDirection = 1;
312 var itemDir = contentNode.getDirection( useComputedState );
314 if ( listDir !== null )
316 // If at least one LI have a different direction than current listDir, we can't have listDir.
317 if ( listDir && listDir != itemDir )
325 contentNode = parentNode;
329 if ( listContents.length < 1 )
332 // Insert the list to the DOM tree.
333 var insertAnchor = listContents[ listContents.length - 1 ].getNext(),
334 listNode = doc.createElement( this.type );
336 listsCreated.push( listNode );
338 var contentBlock, listItem;
340 while ( listContents.length )
342 contentBlock = listContents.shift();
343 listItem = doc.createElement( 'li' );
345 // Preserve preformat block and heading structure when converting to list item. (#5335) (#5271)
346 if ( contentBlock.is( 'pre' ) || headerTagRegex.test( contentBlock.getName() ) )
347 contentBlock.appendTo( listItem );
350 // Remove DIR attribute if it was merged into list root.
351 if ( listDir && contentBlock.getDirection() )
353 contentBlock.removeStyle( 'direction' );
354 contentBlock.removeAttribute( 'dir' );
357 contentBlock.copyAttributes( listItem );
358 contentBlock.moveChildren( listItem );
359 contentBlock.remove();
362 listItem.appendTo( listNode );
365 // Apply list root dir only if it has been explicitly declared.
366 if ( listDir && explicitDirection )
367 listNode.setAttribute( 'dir', listDir );
370 listNode.insertBefore( insertAnchor );
372 listNode.appendTo( commonParent );
375 function removeList( editor, groupObj, database )
377 // This is very much like the change list type operation.
378 // Except that we're changing the selected items' indent to -1 in the list array.
379 var listArray = CKEDITOR.plugins.list.listToArray( groupObj.root, database ),
380 selectedListItems = [];
382 for ( var i = 0 ; i < groupObj.contents.length ; i++ )
384 var itemNode = groupObj.contents[i];
385 itemNode = itemNode.getAscendant( 'li', true );
386 if ( !itemNode || itemNode.getCustomData( 'list_item_processed' ) )
388 selectedListItems.push( itemNode );
389 CKEDITOR.dom.element.setMarker( database, itemNode, 'list_item_processed', true );
392 var lastListIndex = null;
393 for ( i = 0 ; i < selectedListItems.length ; i++ )
395 var listIndex = selectedListItems[i].getCustomData( 'listarray_index' );
396 listArray[listIndex].indent = -1;
397 lastListIndex = listIndex;
400 // After cutting parts of the list out with indent=-1, we still have to maintain the array list
401 // model's nextItem.indent <= currentItem.indent + 1 invariant. Otherwise the array model of the
402 // list cannot be converted back to a real DOM list.
403 for ( i = lastListIndex + 1 ; i < listArray.length ; i++ )
405 if ( listArray[i].indent > listArray[i-1].indent + 1 )
407 var indentOffset = listArray[i-1].indent + 1 - listArray[i].indent;
408 var oldIndent = listArray[i].indent;
409 while ( listArray[i] && listArray[i].indent >= oldIndent )
411 listArray[i].indent += indentOffset;
418 var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode,
419 groupObj.root.getAttribute( 'dir' ) );
421 // Compensate <br> before/after the list node if the surrounds are non-blocks.(#3836)
422 var docFragment = newList.listNode, boundaryNode, siblingNode;
423 function compensateBrs( isStart )
425 if ( ( boundaryNode = docFragment[ isStart ? 'getFirst' : 'getLast' ]() )
426 && !( boundaryNode.is && boundaryNode.isBlockBoundary() )
427 && ( siblingNode = groupObj.root[ isStart ? 'getPrevious' : 'getNext' ]
428 ( CKEDITOR.dom.walker.whitespaces( true ) ) )
429 && !( siblingNode.is && siblingNode.isBlockBoundary( { br : 1 } ) ) )
430 editor.document.createElement( 'br' )[ isStart ? 'insertBefore' : 'insertAfter' ]( boundaryNode );
432 compensateBrs( true );
435 docFragment.replace( groupObj.root );
438 function listCommand( name, type )
444 listCommand.prototype = {
445 exec : function( editor )
449 var doc = editor.document,
450 selection = editor.getSelection(),
451 ranges = selection && selection.getRanges( true );
453 // There should be at least one selected range.
454 if ( !ranges || ranges.length < 1 )
457 // Midas lists rule #1 says we can create a list even in an empty document.
458 // But DOM iterator wouldn't run if the document is really empty.
459 // So create a paragraph if the document is empty and we're going to create a list.
460 if ( this.state == CKEDITOR.TRISTATE_OFF )
462 var body = doc.getBody();
464 if ( !body.getFirst() )
466 var paragraph = doc.createElement( editor.config.enterMode == CKEDITOR.ENTER_P ? 'p' :
467 ( editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'br' ) );
468 paragraph.appendTo( body );
469 ranges = new CKEDITOR.dom.rangeList( [ new CKEDITOR.dom.range( doc ) ] );
470 // IE exception on inserting anything when anchor inside <br>.
471 if ( paragraph.is( 'br' ) )
473 ranges[ 0 ].setStartBefore( paragraph );
474 ranges[ 0 ].setEndAfter( paragraph );
477 ranges[ 0 ].selectNodeContents( paragraph );
478 selection.selectRanges( ranges );
480 // Maybe a single range there enclosing the whole list,
481 // turn on the list state manually(#4129).
484 var range = ranges.length == 1 && ranges[ 0 ],
485 enclosedNode = range && range.getEnclosedNode();
486 if ( enclosedNode && enclosedNode.is
487 && this.type == enclosedNode.getName() )
488 this.setState( CKEDITOR.TRISTATE_ON );
492 var bookmarks = selection.createBookmarks( true );
494 // Group the blocks up because there are many cases where multiple lists have to be created,
495 // or multiple lists have to be cancelled.
498 rangeIterator = ranges.createIterator(),
501 while ( ( range = rangeIterator.getNextRange() ) && ++index )
503 var boundaryNodes = range.getBoundaryNodes(),
504 startNode = boundaryNodes.startNode,
505 endNode = boundaryNodes.endNode;
507 if ( startNode.type == CKEDITOR.NODE_ELEMENT && startNode.getName() == 'td' )
508 range.setStartAt( boundaryNodes.startNode, CKEDITOR.POSITION_AFTER_START );
510 if ( endNode.type == CKEDITOR.NODE_ELEMENT && endNode.getName() == 'td' )
511 range.setEndAt( boundaryNodes.endNode, CKEDITOR.POSITION_BEFORE_END );
513 var iterator = range.createIterator(),
516 iterator.forceBrBreak = ( this.state == CKEDITOR.TRISTATE_OFF );
518 while ( ( block = iterator.getNextParagraph() ) )
520 // Avoid duplicate blocks get processed across ranges.
521 if( block.getCustomData( 'list_block' ) )
524 CKEDITOR.dom.element.setMarker( database, block, 'list_block', 1 );
526 var path = new CKEDITOR.dom.elementPath( block ),
527 pathElements = path.elements,
528 pathElementsCount = pathElements.length,
531 blockLimit = path.blockLimit,
534 // First, try to group by a list ancestor.
535 for ( var i = pathElementsCount - 1; i >= 0 && ( element = pathElements[ i ] ); i-- )
537 if ( listNodeNames[ element.getName() ]
538 && blockLimit.contains( element ) ) // Don't leak outside block limit (#3940).
540 // If we've encountered a list inside a block limit
541 // The last group object of the block limit element should
542 // no longer be valid. Since paragraphs after the list
543 // should belong to a different group of paragraphs before
544 // the list. (Bug #1309)
545 blockLimit.removeCustomData( 'list_group_object_' + index );
547 var groupObj = element.getCustomData( 'list_group_object' );
549 groupObj.contents.push( block );
552 groupObj = { root : element, contents : [ block ] };
553 listGroups.push( groupObj );
554 CKEDITOR.dom.element.setMarker( database, element, 'list_group_object', groupObj );
564 // No list ancestor? Group by block limit, but don't mix contents from different ranges.
565 var root = blockLimit;
566 if ( root.getCustomData( 'list_group_object_' + index ) )
567 root.getCustomData( 'list_group_object_' + index ).contents.push( block );
570 groupObj = { root : root, contents : [ block ] };
571 CKEDITOR.dom.element.setMarker( database, root, 'list_group_object_' + index, groupObj );
572 listGroups.push( groupObj );
577 // Now we have two kinds of list groups, groups rooted at a list, and groups rooted at a block limit element.
578 // We either have to build lists or remove lists, for removing a list does not makes sense when we are looking
579 // at the group that's not rooted at lists. So we have three cases to handle.
580 var listsCreated = [];
581 while ( listGroups.length > 0 )
583 groupObj = listGroups.shift();
584 if ( this.state == CKEDITOR.TRISTATE_OFF )
586 if ( listNodeNames[ groupObj.root.getName() ] )
587 changeListType.call( this, editor, groupObj, database, listsCreated );
589 createList.call( this, editor, groupObj, listsCreated );
591 else if ( this.state == CKEDITOR.TRISTATE_ON && listNodeNames[ groupObj.root.getName() ] )
592 removeList.call( this, editor, groupObj, database );
595 // For all new lists created, merge adjacent, same type lists.
596 for ( i = 0 ; i < listsCreated.length ; i++ )
598 listNode = listsCreated[i];
599 var mergeSibling, listCommand = this;
600 ( mergeSibling = function( rtl ){
602 var sibling = listNode[ rtl ?
603 'getPrevious' : 'getNext' ]( CKEDITOR.dom.walker.whitespaces( true ) );
604 if ( sibling && sibling.getName &&
605 sibling.getName() == listCommand.type )
608 // Move children order by merge direction.(#3820)
609 sibling.moveChildren( listNode, rtl );
615 // Clean up, restore selection and update toolbar button states.
616 CKEDITOR.dom.element.clearAllMarkers( database );
617 selection.selectBookmarks( bookmarks );
622 var dtd = CKEDITOR.dtd;
623 var tailNbspRegex = /[\t\r\n ]*(?: |\xa0)$/;
625 function indexOfFirstChildElement( element, tagNameList )
628 children = element.children,
629 length = children.length;
631 for ( var i = 0 ; i < length ; i++ )
633 child = children[ i ];
634 if ( child.name && ( child.name in tagNameList ) )
641 function getExtendNestedListFilter( isHtmlFilter )
643 // An element filter function that corrects nested list start in an empty
644 // list item for better displaying/outputting. (#3165)
645 return function( listItem )
647 var children = listItem.children,
648 firstNestedListIndex = indexOfFirstChildElement( listItem, dtd.$list ),
649 firstNestedList = children[ firstNestedListIndex ],
650 nodeBefore = firstNestedList && firstNestedList.previous,
654 && ( nodeBefore.name && nodeBefore.name == 'br'
655 || nodeBefore.value && ( tailNbspmatch = nodeBefore.value.match( tailNbspRegex ) ) ) )
657 var fillerNode = nodeBefore;
659 // Always use 'nbsp' as filler node if we found a nested list appear
660 // in front of a list item.
661 if ( !( tailNbspmatch && tailNbspmatch.index ) && fillerNode == children[ 0 ] )
662 children[ 0 ] = ( isHtmlFilter || CKEDITOR.env.ie ) ?
663 new CKEDITOR.htmlParser.text( '\xa0' ) :
664 new CKEDITOR.htmlParser.element( 'br', {} );
666 // Otherwise the filler is not needed anymore.
667 else if ( fillerNode.name == 'br' )
668 children.splice( firstNestedListIndex - 1, 1 );
670 fillerNode.value = fillerNode.value.replace( tailNbspRegex, '' );
676 var defaultListDataFilterRules = { elements : {} };
677 for ( var i in dtd.$listItem )
678 defaultListDataFilterRules.elements[ i ] = getExtendNestedListFilter();
680 var defaultListHtmlFilterRules = { elements : {} };
681 for ( i in dtd.$listItem )
682 defaultListHtmlFilterRules.elements[ i ] = getExtendNestedListFilter( true );
684 CKEDITOR.plugins.add( 'list',
686 init : function( editor )
688 // Register commands.
689 var numberedListCommand = editor.addCommand( 'numberedlist', new listCommand( 'numberedlist', 'ol' ) ),
690 bulletedListCommand = editor.addCommand( 'bulletedlist', new listCommand( 'bulletedlist', 'ul' ) );
692 // Register the toolbar button.
693 editor.ui.addButton( 'NumberedList',
695 label : editor.lang.numberedlist,
696 command : 'numberedlist'
698 editor.ui.addButton( 'BulletedList',
700 label : editor.lang.bulletedlist,
701 command : 'bulletedlist'
704 // Register the state changing handlers.
705 editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, numberedListCommand ) );
706 editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, bulletedListCommand ) );
709 afterInit : function ( editor )
711 var dataProcessor = editor.dataProcessor;
714 dataProcessor.dataFilter.addRules( defaultListDataFilterRules );
715 dataProcessor.htmlFilter.addRules( defaultListHtmlFilterRules );
719 requires : [ 'domiterator' ]