2 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
3 For licensing, see LICENSE.html or http://ckeditor.com/license
10 function findEvaluator( node )
12 return node.type == CKEDITOR.NODE_TEXT && node.getLength() > 0 && ( !isReplace || !node.isReadOnly() );
16 * Elements which break characters been considered as sequence.
18 function nonCharactersBoundary( node )
20 return !( node.type == CKEDITOR.NODE_ELEMENT && node.isBlockBoundary(
21 CKEDITOR.tools.extend( {}, CKEDITOR.dtd.$empty, CKEDITOR.dtd.$nonEditable ) ) );
25 * Get the cursor object which represent both current character and it's dom
28 var cursorStep = function()
31 textNode : this.textNode,
33 character : this.textNode ?
34 this.textNode.getText().charAt( this.offset ) : null,
35 hitMatchBoundary : this._.matchBoundary
39 var pages = [ 'find', 'replace' ],
41 [ 'txtFindFind', 'txtFindReplace' ],
42 [ 'txtFindCaseChk', 'txtReplaceCaseChk' ],
43 [ 'txtFindWordChk', 'txtReplaceWordChk' ],
44 [ 'txtFindCyclic', 'txtReplaceCyclic' ] ];
47 * Synchronize corresponding filed values between 'replace' and 'find' pages.
48 * @param {String} currentPageId The page id which receive values.
50 function syncFieldsBetweenTabs( currentPageId )
52 var sourceIndex, targetIndex,
53 sourceField, targetField;
55 sourceIndex = currentPageId === 'find' ? 1 : 0;
56 targetIndex = 1 - sourceIndex;
57 var i, l = fieldsMapping.length;
58 for ( i = 0 ; i < l ; i++ )
60 sourceField = this.getContentElement( pages[ sourceIndex ],
61 fieldsMapping[ i ][ sourceIndex ] );
62 targetField = this.getContentElement( pages[ targetIndex ],
63 fieldsMapping[ i ][ targetIndex ] );
65 targetField.setValue( sourceField.getValue() );
69 var findDialog = function( editor, startupPage )
71 // Style object for highlights: (#5018)
72 // 1. Defined as full match style to avoid compromising ordinary text color styles.
73 // 2. Must be apply onto inner-most text to avoid conflicting with ordinary text color styles visually.
74 var highlightStyle = new CKEDITOR.style(
75 CKEDITOR.tools.extend( { attributes : { 'data-cke-highlight': 1 }, fullMatch : 1, ignoreReadonly : 1, childRule : function(){ return 0; } },
76 editor.config.find_highlight, true ) );
79 * Iterator which walk through the specified range char by char. By
80 * default the walking will not stop at the character boundaries, until
81 * the end of the range is encountered.
82 * @param { CKEDITOR.dom.range } range
83 * @param {Boolean} matchWord Whether the walking will stop at character boundary.
85 var characterWalker = function( range , matchWord )
89 new CKEDITOR.dom.walker( range );
90 walker.guard = matchWord ? nonCharactersBoundary : function( node )
92 !nonCharactersBoundary( node ) && ( self._.matchBoundary = true );
94 walker[ 'evaluator' ] = findEvaluator;
95 walker.breakOnFalse = 1;
97 if ( range.startContainer.type == CKEDITOR.NODE_TEXT )
99 this.textNode = range.startContainer;
100 this.offset = range.startOffset - 1;
104 matchWord : matchWord,
106 matchBoundary : false
110 characterWalker.prototype = {
118 return this.move( true );
121 move : function( rtl )
123 var currentTextNode = this.textNode;
124 // Already at the end of document, no more character available.
125 if ( currentTextNode === null )
126 return cursorStep.call( this );
128 this._.matchBoundary = false;
130 // There are more characters in the text node, step forward.
136 return cursorStep.call( this );
138 else if ( currentTextNode
139 && this.offset < currentTextNode.getLength() - 1 )
142 return cursorStep.call( this );
146 currentTextNode = null;
147 // At the end of the text node, walking foward for the next.
148 while ( !currentTextNode )
151 this._.walker[ rtl ? 'previous' : 'next' ].call( this._.walker );
153 // Stop searching if we're need full word match OR
154 // already reach document end.
155 if ( this._.matchWord && !currentTextNode
156 || this._.walker._.end )
159 // Found a fresh text node.
160 this.textNode = currentTextNode;
161 if ( currentTextNode )
162 this.offset = rtl ? currentTextNode.getLength() - 1 : 0;
167 return cursorStep.call( this );
173 * A range of cursors which represent a trunk of characters which try to
174 * match, it has the same length as the pattern string.
176 var characterRange = function( characterWalker, rangeLength )
179 walker : characterWalker,
181 rangeLength : rangeLength,
182 highlightRange : null,
187 characterRange.prototype = {
189 * Translate this range to {@link CKEDITOR.dom.range}
191 toDomRange : function()
193 var range = new CKEDITOR.dom.range( editor.document );
194 var cursors = this._.cursors;
195 if ( cursors.length < 1 )
197 var textNode = this._.walker.textNode;
199 range.setStartAfter( textNode );
205 var first = cursors[0],
206 last = cursors[ cursors.length - 1 ];
208 range.setStart( first.textNode, first.offset );
209 range.setEnd( last.textNode, last.offset + 1 );
215 * Reflect the latest changes from dom range.
217 updateFromDomRange : function( domRange )
220 walker = new characterWalker( domRange );
224 cursor = walker.next();
225 if ( cursor.character )
226 this._.cursors.push( cursor );
228 while ( cursor.character );
229 this._.rangeLength = this._.cursors.length;
232 setMatched : function()
234 this._.isMatched = true;
237 clearMatched : function()
239 this._.isMatched = false;
242 isMatched : function()
244 return this._.isMatched;
248 * Hightlight the current matched chunk of text.
250 highlight : function()
252 // Do not apply if nothing is found.
253 if ( this._.cursors.length < 1 )
256 // Remove the previous highlight if there's one.
257 if ( this._.highlightRange )
258 this.removeHighlight();
260 // Apply the highlight.
261 var range = this.toDomRange(),
262 bookmark = range.createBookmark();
263 highlightStyle.applyToRange( range );
264 range.moveToBookmark( bookmark );
265 this._.highlightRange = range;
267 // Scroll the editor to the highlighted area.
268 var element = range.startContainer;
269 if ( element.type != CKEDITOR.NODE_ELEMENT )
270 element = element.getParent();
271 element.scrollIntoView();
273 // Update the character cursors.
274 this.updateFromDomRange( range );
278 * Remove highlighted find result.
280 removeHighlight : function()
282 if ( !this._.highlightRange )
285 var bookmark = this._.highlightRange.createBookmark();
286 highlightStyle.removeFromRange( this._.highlightRange );
287 this._.highlightRange.moveToBookmark( bookmark );
288 this.updateFromDomRange( this._.highlightRange );
289 this._.highlightRange = null;
292 isReadOnly : function()
294 if ( !this._.highlightRange )
297 return this._.highlightRange.startContainer.isReadOnly();
300 moveBack : function()
302 var retval = this._.walker.back(),
303 cursors = this._.cursors;
305 if ( retval.hitMatchBoundary )
306 this._.cursors = cursors = [];
308 cursors.unshift( retval );
309 if ( cursors.length > this._.rangeLength )
315 moveNext : function()
317 var retval = this._.walker.next(),
318 cursors = this._.cursors;
320 // Clear the cursors queue if we've crossed a match boundary.
321 if ( retval.hitMatchBoundary )
322 this._.cursors = cursors = [];
324 cursors.push( retval );
325 if ( cursors.length > this._.rangeLength )
331 getEndCharacter : function()
333 var cursors = this._.cursors;
334 if ( cursors.length < 1 )
337 return cursors[ cursors.length - 1 ].character;
340 getNextCharacterRange : function( maxLength )
344 cursors = this._.cursors;
346 if ( ( lastCursor = cursors[ cursors.length - 1 ] ) && lastCursor.textNode )
347 nextRangeWalker = new characterWalker( getRangeAfterCursor( lastCursor ) );
348 // In case it's an empty range (no cursors), figure out next range from walker (#4951).
350 nextRangeWalker = this._.walker;
352 return new characterRange( nextRangeWalker, maxLength );
355 getCursors : function()
357 return this._.cursors;
362 // The remaining document range after the character cursor.
363 function getRangeAfterCursor( cursor , inclusive )
365 var range = new CKEDITOR.dom.range();
366 range.setStart( cursor.textNode,
367 ( inclusive ? cursor.offset : cursor.offset + 1 ) );
368 range.setEndAt( editor.document.getBody(),
369 CKEDITOR.POSITION_BEFORE_END );
373 // The document range before the character cursor.
374 function getRangeBeforeCursor( cursor )
376 var range = new CKEDITOR.dom.range();
377 range.setStartAt( editor.document.getBody(),
378 CKEDITOR.POSITION_AFTER_START );
379 range.setEnd( cursor.textNode, cursor.offset );
387 * Examination the occurrence of a word which implement KMP algorithm.
389 var kmpMatcher = function( pattern, ignoreCase )
391 var overlap = [ -1 ];
393 pattern = pattern.toLowerCase();
394 for ( var i = 0 ; i < pattern.length ; i++ )
396 overlap.push( overlap[i] + 1 );
397 while ( overlap[ i + 1 ] > 0
398 && pattern.charAt( i ) != pattern
399 .charAt( overlap[ i + 1 ] - 1 ) )
400 overlap[ i + 1 ] = overlap[ overlap[ i + 1 ] - 1 ] + 1;
406 ignoreCase : !!ignoreCase,
411 kmpMatcher.prototype =
413 feedCharacter : function( c )
415 if ( this._.ignoreCase )
420 if ( c == this._.pattern.charAt( this._.state ) )
423 if ( this._.state == this._.pattern.length )
430 else if ( !this._.state )
433 this._.state = this._.overlap[ this._.state ];
445 var wordSeparatorRegex =
446 /[.,"'?!;: \u0085\u00a0\u1680\u280e\u2028\u2029\u202f\u205f\u3000]/;
448 var isWordSeparator = function( c )
452 var code = c.charCodeAt( 0 );
453 return ( code >= 9 && code <= 0xd )
454 || ( code >= 0x2000 && code <= 0x200a )
455 || wordSeparatorRegex.test( c );
461 find : function( pattern, matchCase, matchWord, matchCyclic, highlightMatched, cyclicRerun )
463 if ( !this.matchRange )
466 new characterWalker( this.searchRange ),
470 this.matchRange.removeHighlight();
471 this.matchRange = this.matchRange.getNextCharacterRange( pattern.length );
474 var matcher = new kmpMatcher( pattern, !matchCase ),
475 matchState = KMP_NOMATCH,
478 while ( character !== null )
480 this.matchRange.moveNext();
481 while ( ( character = this.matchRange.getEndCharacter() ) )
483 matchState = matcher.feedCharacter( character );
484 if ( matchState == KMP_MATCHED )
486 if ( this.matchRange.moveNext().hitMatchBoundary )
490 if ( matchState == KMP_MATCHED )
494 var cursors = this.matchRange.getCursors(),
495 tail = cursors[ cursors.length - 1 ],
498 var headWalker = new characterWalker( getRangeBeforeCursor( head ), true ),
499 tailWalker = new characterWalker( getRangeAfterCursor( tail ), true );
501 if ( ! ( isWordSeparator( headWalker.back().character )
502 && isWordSeparator( tailWalker.next().character ) ) )
505 this.matchRange.setMatched();
506 if ( highlightMatched !== false )
507 this.matchRange.highlight();
512 this.matchRange.clearMatched();
513 this.matchRange.removeHighlight();
514 // Clear current session and restart with the default search
516 // Re-run the finding once for cyclic.(#3517)
517 if ( matchCyclic && !cyclicRerun )
519 this.searchRange = getSearchRange( 1 );
520 this.matchRange = null;
521 return arguments.callee.apply( this,
522 Array.prototype.slice.call( arguments ).concat( [ true ] ) );
529 * Record how much replacement occurred toward one replacing.
533 replace : function( dialog, pattern, newString, matchCase, matchWord,
534 matchCyclic , isReplaceAll )
538 // Successiveness of current replace/find.
541 // 1. Perform the replace when there's already a match here.
542 // 2. Otherwise perform the find but don't replace it immediately.
543 if ( this.matchRange && this.matchRange.isMatched()
544 && !this.matchRange._.isReplaced && !this.matchRange.isReadOnly() )
546 // Turn off highlight for a while when saving snapshots.
547 this.matchRange.removeHighlight();
548 var domRange = this.matchRange.toDomRange();
549 var text = editor.document.createText( newString );
552 // Save undo snaps before and after the replacement.
553 var selection = editor.getSelection();
554 selection.selectRanges( [ domRange ] );
555 editor.fire( 'saveSnapshot' );
557 domRange.deleteContents();
558 domRange.insertNode( text );
561 selection.selectRanges( [ domRange ] );
562 editor.fire( 'saveSnapshot' );
564 this.matchRange.updateFromDomRange( domRange );
566 this.matchRange.highlight();
567 this.matchRange._.isReplaced = true;
568 this.replaceCounter++;
572 result = this.find( pattern, matchCase, matchWord, matchCyclic, !isReplaceAll );
581 * The range in which find/replace happened, receive from user
584 function getSearchRange( isDefault )
587 sel = editor.getSelection(),
588 body = editor.document.getBody();
589 if ( sel && !isDefault )
591 searchRange = sel.getRanges()[ 0 ].clone();
592 searchRange.collapse( true );
596 searchRange = new CKEDITOR.dom.range();
597 searchRange.setStartAt( body, CKEDITOR.POSITION_AFTER_START );
599 searchRange.setEndAt( body, CKEDITOR.POSITION_BEFORE_END );
603 var lang = editor.lang.findAndReplace;
606 resizable : CKEDITOR.DIALOG_RESIZE_NONE,
609 buttons : [ CKEDITOR.dialog.cancelButton ], // Cancel button only.
619 widths : [ '230px', '90px' ],
625 label : lang.findWhat,
627 labelLayout : 'horizontal',
634 style : 'width:100%',
638 var dialog = this.getDialog();
639 if ( !finder.find( dialog.getValueOf( 'find', 'txtFindFind' ),
640 dialog.getValueOf( 'find', 'txtFindCaseChk' ),
641 dialog.getValueOf( 'find', 'txtFindWordChk' ),
642 dialog.getValueOf( 'find', 'txtFindCyclic' ) ) )
651 label : CKEDITOR.tools.htmlEncode( lang.findOptions ),
652 style : 'margin-top:29px',
662 id : 'txtFindCaseChk',
664 label : lang.matchCase
668 id : 'txtFindWordChk',
670 label : lang.matchWord
674 id : 'txtFindCyclic',
677 label : lang.matchCyclic
687 label : lang.replace,
692 widths : [ '230px', '90px' ],
697 id : 'txtFindReplace',
698 label : lang.findWhat,
700 labelLayout : 'horizontal',
705 id : 'btnFindReplace',
707 style : 'width:100%',
708 label : lang.replace,
711 var dialog = this.getDialog();
712 if ( !finder.replace( dialog,
713 dialog.getValueOf( 'replace', 'txtFindReplace' ),
714 dialog.getValueOf( 'replace', 'txtReplace' ),
715 dialog.getValueOf( 'replace', 'txtReplaceCaseChk' ),
716 dialog.getValueOf( 'replace', 'txtReplaceWordChk' ),
717 dialog.getValueOf( 'replace', 'txtReplaceCyclic' ) ) )
726 widths : [ '230px', '90px' ],
732 label : lang.replaceWith,
734 labelLayout : 'horizontal',
739 id : 'btnReplaceAll',
741 style : 'width:100%',
742 label : lang.replaceAll,
746 var dialog = this.getDialog();
749 finder.replaceCounter = 0;
751 // Scope to full document.
752 finder.searchRange = getSearchRange( 1 );
753 if ( finder.matchRange )
755 finder.matchRange.removeHighlight();
756 finder.matchRange = null;
758 editor.fire( 'saveSnapshot' );
759 while ( finder.replace( dialog,
760 dialog.getValueOf( 'replace', 'txtFindReplace' ),
761 dialog.getValueOf( 'replace', 'txtReplace' ),
762 dialog.getValueOf( 'replace', 'txtReplaceCaseChk' ),
763 dialog.getValueOf( 'replace', 'txtReplaceWordChk' ),
767 if ( finder.replaceCounter )
769 alert( lang.replaceSuccessMsg.replace( /%1/, finder.replaceCounter ) );
770 editor.fire( 'saveSnapshot' );
773 alert( lang.notFoundMsg );
780 label : CKEDITOR.tools.htmlEncode( lang.findOptions ),
790 id : 'txtReplaceCaseChk',
792 label : lang.matchCase
796 id : 'txtReplaceWordChk',
798 label : lang.matchWord
802 id : 'txtReplaceCyclic',
805 label : lang.matchCyclic
818 // Keep track of the current pattern field in use.
819 var patternField, wholeWordChkField;
821 // Ignore initial page select on dialog show
822 var isUserSelect = 0;
823 this.on( 'hide', function()
827 this.on( 'show', function()
832 this.selectPage = CKEDITOR.tools.override( this.selectPage, function( originalFunc )
834 return function( pageId )
836 originalFunc.call( dialog, pageId );
838 var currPage = dialog._.tabs[ pageId ];
839 var patternFieldInput, patternFieldId, wholeWordChkFieldId;
840 patternFieldId = pageId === 'find' ? 'txtFindFind' : 'txtFindReplace';
841 wholeWordChkFieldId = pageId === 'find' ? 'txtFindWordChk' : 'txtReplaceWordChk';
843 patternField = dialog.getContentElement( pageId,
845 wholeWordChkField = dialog.getContentElement( pageId,
846 wholeWordChkFieldId );
848 // Prepare for check pattern text filed 'keyup' event
849 if ( !currPage.initialized )
851 patternFieldInput = CKEDITOR.document
852 .getById( patternField._.inputId );
853 currPage.initialized = true;
856 // Synchronize fields on tab switch.
858 syncFieldsBetweenTabs.call( this, pageId );
865 // Establish initial searching start position.
866 finder.searchRange = getSearchRange();
868 // Fill in the find field with selected text.
869 var selectedText = this.getParentEditor().getSelection().getSelectedText(),
870 patternFieldId = ( startupPage == 'find' ? 'txtFindFind' : 'txtFindReplace' );
872 var field = this.getContentElement( startupPage, patternFieldId );
873 field.setValue( selectedText );
876 this.selectPage( startupPage );
878 this[ ( startupPage == 'find' && this._.editor.readOnly? 'hide' : 'show' ) + 'Page' ]( 'replace');
883 if ( finder.matchRange && finder.matchRange.isMatched() )
885 finder.matchRange.removeHighlight();
888 range = finder.matchRange.toDomRange();
890 editor.getSelection().selectRanges( [ range ] );
893 // Clear current session before dialog close
894 delete finder.matchRange;
898 if ( startupPage == 'replace' )
899 return this.getContentElement( 'replace', 'txtFindReplace' );
901 return this.getContentElement( 'find', 'txtFindFind' );
906 CKEDITOR.dialog.add( 'find', function( editor )
908 return findDialog( editor, 'find' );
911 CKEDITOR.dialog.add( 'replace', function( editor )
913 return findDialog( editor, 'replace' );