Change regex replacement methods to allow for replacement at cursor

This commit is contained in:
Eston Bond
2010-12-06 16:10:58 -08:00
parent c5631ae376
commit add9402b7e
@@ -453,6 +453,7 @@
var selText = FunctionBar.getFieldSelection( $('#gollum-editor-body') );
var repText = selText;
var reselect = true;
var cursor = null;
// execute a replacement function if one exists
if ( definitionObject.exec &&
@@ -469,12 +470,36 @@
searchExp = definitionObject.search;
debug( searchExp );
}
debug(repText);
// replace text
if ( definitionObject.replace &&
typeof definitionObject.replace == 'string' ) {
debug('Running replacement - using ' + definitionObject.replace);
repText = repText.replace( searchExp, definitionObject.replace );
var rt = definitionObject.replace;
var matches = searchExp.exec( repText );
if ( matches && matches.length > 1 ) {
debug(matches);
for ( var i = 1; i < matches.length; i++ ) {
var searchStr = '$' + i;
debug('searching for ' + searchStr + ' to replace with ' + matches[i]);
rt = rt.replace( searchStr, matches[i] );
}
repText = rt;
} else if ( repText == '' ) {
debug('Search string is empty');
// find position of $1 - this is where we will place the cursor
var cursor = rt.indexOf('$1');
// we have an empty string, so just remove backreferences
repText = rt.replace( /\$[\d]/g, '' );
// if the position of $1 doesn't exist, stick the cursor in
// the middle
if ( cursor == -1 ) {
cursor = Math.floor( rt.length / 2 );
}
}
}
// append if necessary
@@ -485,10 +510,10 @@
}
repText += definitionObject.append;
}
if (repText)
if ( repText )
FunctionBar.replaceFieldSelection( $('#gollum-editor-body'),
repText, reselect );
repText, reselect, cursor );
},
@@ -607,7 +632,7 @@
* @param string The string to replace the current selection with.
* @param boolean Reselect the new text range.
*/
replaceFieldSelection: function( $field, replaceText, reselect ) {
replaceFieldSelection: function( $field, replaceText, reselect, cursorOffset ) {
var selPos = FunctionBar.getFieldSelectionPosition( $field );
var fullStr = $field.val();
var selectNew = true;
@@ -626,13 +651,25 @@
if ( selectNew ) {
if ( $field[0].setSelectionRange ) {
$field[0].setSelectionRange( selPos.start,
selPos.start + replaceText.length );
if ( cursorOffset ) {
$field[0].setSelectionRange(
selPos.start + cursorOffset,
selPos.start + cursorOffset
);
} else {
$field[0].setSelectionRange( selPos.start,
selPos.start + replaceText.length );
}
} else if ( $field[0].createTextRange ) {
var range = $field[0].createTextRange();
range.collapse( true );
range.moveEnd( 'character', selPos.start + replaceText.length );
range.moveStart( 'character', selPos.start );
if ( cursorOffset ) {
range.moveEnd( selPos.start + cursorOffset );
range.moveStart( selPos.start + cursorOffset );
} else {
range.moveEnd( 'character', selPos.start + replaceText.length );
range.moveStart( 'character', selPos.start );
}
range.select();
}
}