Skip to content
This repository has been archived by the owner on Dec 22, 2023. It is now read-only.

Basic Autocompletion

Jad Altahan edited this page Feb 5, 2017 · 4 revisions

You are responsible for triggering autocompletion, Scintilla won't do it for you. This confuses a lot of developers who believe it should be automatic. But don't worry, it's not difficult.

The easiest way is to monitor the CharAdded event--which is triggered each time a character is inserted into the document. Your application logic may then determine if the word being keyed in is a language keyword, an identifier name, or something else, and provide the appropriate list of possible autocompletion words. That's up to you.

At its simplest, this is how it works:

private void scintilla_CharAdded(object sender, CharAddedEventArgs e)
{
    // Find the word start
    var currentPos = scintilla.CurrentPosition;
    var wordStartPos = scintilla.WordStartPosition(currentPos, true);

    // Display the autocompletion list
    var lenEntered = currentPos - wordStartPos;
    if (lenEntered > 0)
    {
        if (!scintilla.AutoCActive)
            scintilla.AutoCShow(lenEntered, "abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe using virtual while");
    }
}

When you display an autocompletion list you tell Scintilla how many characters of the word being completed have already been entered. By doing this, Scintilla will narrow down the list of possible completion words and, when the user selects one of those words with the tab or enter key, automatically complete the rest of the word and not insert the entire word. That's what the code using WordStartPosition is doing--figuring out how many characters of the current word have already been entered.

The if (lenEntered > 0) check is a way of making sure the user is entering a word and not just typing whitespace. If wordStartPos was the same as currentPos it would mean our caret is in the middle of whitespace, not a word. Another way to do that would be to check the CharAddedEventArgs.Char property.