using System; using System.Collections.Generic; using System.Linq; using System.Text; using Rune = System.Rune; namespace Terminal.Gui { /// /// which suggests from a collection /// of words those that match the . You /// can update at any time to change candidates /// considered for autocomplete. /// public class SingleWordSuggestionGenerator : ISuggestionGenerator { /// /// The full set of all strings that can be suggested. /// /// public virtual List AllSuggestions { get; set; } = new List (); /// public IEnumerable GenerateSuggestions (AutocompleteContext context) { // if there is nothing to pick from if (AllSuggestions.Count == 0) { return Enumerable.Empty (); } var currentWord = IdxToWord (context.CurrentLine, context.CursorPosition); if (string.IsNullOrWhiteSpace (currentWord)) { return Enumerable.Empty (); } else { return AllSuggestions.Where (o => o.StartsWith (currentWord, StringComparison.CurrentCultureIgnoreCase) && !o.Equals (currentWord, StringComparison.CurrentCultureIgnoreCase) ).Select (o => new Suggestion (currentWord.Length, o)) .ToList ().AsReadOnly (); } } /// /// Return true if the given symbol should be considered part of a word /// and can be contained in matches. Base behavior is to use /// /// /// public virtual bool IsWordChar (Rune rune) { return Char.IsLetterOrDigit ((char)rune); } /// /// /// Given a of characters, returns the word which ends at /// or null. Also returns null if the is positioned in the middle of a word. /// /// /// /// Use this method to determine whether autocomplete should be shown when the cursor is at /// a given point in a line and to get the word from which suggestions should be generated. /// Use the to indicate if search the word at left (negative), /// at right (positive) or at the current column (zero) which is the default. /// /// /// /// /// /// protected virtual string IdxToWord (List line, int idx, int columnOffset = 0) { StringBuilder sb = new StringBuilder (); var endIdx = idx; // get the ending word index while (endIdx < line.Count) { if (IsWordChar (line [endIdx])) { endIdx++; } else { break; } } // It isn't a word char then there is no way to autocomplete that word if (endIdx == idx && columnOffset != 0) { return null; } // we are at the end of a word. Work out what has been typed so far while (endIdx-- > 0) { if (IsWordChar (line [endIdx])) { sb.Insert (0, (char)line [endIdx]); } else { break; } } return sb.ToString (); } } }