/**
 * Emulate GNU Emacs's (fixup-whitespace) function (typically bound to
 * Ctrl-SPACE. Not a complete emulation. Emacs docs for this function:
 *
 *     Fixup white space between objects around caret.
 *     Leave one space or none, according to the context.
 */

source (MiscUtilities.constructPath(dirname(scriptPath), "EmacsUtil.bsh"));

void emacsFixupWhitespace()
{
    caret = textArea.getCaretPosition();
    caretLine = textArea.getCaretLine();
    lineStart = textArea.getLineStartOffset (caretLine);
    lineEnd = textArea.getLineEndOffset (caretLine);
           
    // Determine whether there's white space at the caret.
    
    ch = charAtCaret();
    chPrev = '\0';
    if (caret > lineStart)
        chPrev = charAt (caret - 1);

    if (Character.isWhitespace (ch) || Character.isWhitespace (chPrev))
    {
        // Collapse white space behind and in front of caret, leaving just
        // one. NOTE: For compatibility with Emacs,p if the caret is in the
        // first column, we don't leave any spaces.

        // First, the characters behind the caret:
        
        if (Character.isWhitespace (chPrev))
        {
            origCaret = caret;
            caret = caret--;
            textArea.goToPrevCharacter (false);
            chPrev = charAtCaret();
            while ((caret > lineStart) && (Character.isWhitespace (chPrev)))
            {
                textArea.delete();
                caret = caret - 1;
                textArea.goToPrevCharacter (false);
                chPrev = charAtCaret();
            }
            
            // Caret is now one character behind where we want it.
            
            textArea.goToNextCharacter (false);
        }

        if (Character.isWhitespace (ch) && (ch != '\n'))
        {
            ch = charAtCaret();
            while ((caret <= lineEnd) &&
                (Character.isWhitespace (ch)) &&
                (ch != '\n'))
            {
                textArea.delete();
                ch = charAtCaret();
                caret = textArea.getCaretPosition();
            }
 
            // Make sure there's one blank left--unless:
            //
            // a) we're in column 1, or
            // b) the next character is not a letter or digit, or
            // c) the previous character is not a letter or digit.

           if (caret > lineStart)
            {
                chPrev = charAt (caret - 1);

                if (Character.isLetterOrDigit (ch) &&
                    Character.isLetterOrDigit (chPrev))
                {
                    buffer.insert (caret, " ");
                }
            }
        }
    }
 
    else if ((caret + 1) != lineEnd)
    {
        // Insert one blank.
 
        buffer.insert (caret, " ");
    }
}

emacsFixupWhitespace();

