- endPos = 0,
- preText, rawPreText, periText,
- rawPeriText, postText,
- // IE Support
- preFinished,
- periFinished,
- postFinished,
- // Range containing text in the selection
- periRange,
- // Range containing text before the selection
- preRange,
- // Range containing text after the selection
- postRange;
-
- if ( e && document.selection && document.selection.createRange ) {
- // IE doesn't properly report non-selected caret position through
- // the selection ranges when textarea isn't focused. This can
- // lead to saving a bogus empty selection, which then screws up
- // whatever we do later (bug 31847).
- activateElementOnIE( e );
-
- preFinished = false;
- periFinished = false;
- postFinished = false;
- periRange = document.selection.createRange().duplicate();
-
- preRange = rangeForElementIE( e );
- // Move the end where we need it
- preRange.setEndPoint( 'EndToStart', periRange );
-
- postRange = rangeForElementIE( e );
- // Move the start where we need it
- postRange.setEndPoint( 'StartToEnd', periRange );
-
- // Load the text values we need to compare
- preText = rawPreText = preRange.text;
- periText = rawPeriText = periRange.text;
- postText = postRange.text;
-
- /*
- * Check each range for trimmed newlines by shrinking the range by 1
- * character and seeing if the text property has changed. If it has
- * not changed then we know that IE has trimmed a \r\n from the end.
- */
- do {
- if ( !preFinished ) {
- if ( preRange.compareEndPoints( 'StartToEnd', preRange ) === 0 ) {
- preFinished = true;
- } else {
- preRange.moveEnd( 'character', -1 );
- if ( preRange.text === preText ) {
- rawPreText += '\r\n';
- } else {
- preFinished = true;
- }
- }
- }
- if ( !periFinished ) {
- if ( periRange.compareEndPoints( 'StartToEnd', periRange ) === 0 ) {
- periFinished = true;
- } else {
- periRange.moveEnd( 'character', -1 );
- if ( periRange.text === periText ) {
- rawPeriText += '\r\n';
- } else {
- periFinished = true;
- }
- }
- }
- if ( !postFinished ) {
- if ( postRange.compareEndPoints( 'StartToEnd', postRange ) === 0 ) {
- postFinished = true;
- } else {
- postRange.moveEnd( 'character', -1 );
- if ( postRange.text !== postText ) {
- postFinished = true;
- }
- }
- }
- } while ( ( !preFinished || !periFinished || !postFinished ) );
- caretPos = rawPreText.replace( /\r\n/g, '\n' ).length;
- endPos = caretPos + rawPeriText.replace( /\r\n/g, '\n' ).length;
- } else if ( e && ( e.selectionStart || e.selectionStart === 0 ) ) {
- // Firefox support