public CompletionResult GetCompletion(IConsoleShell shell, string[] args) { if (args.Length == 1) { var hint = Loc.GetString("play-global-sound-command-arg-path"); var res = IoCManager.Resolve <IResourceManager>(); var options = CompletionHelper.ContentFilePath(args[0], res); return(CompletionResult.FromHintOptions(options, hint)); } if (args.Length == 2) { return(CompletionResult.FromHint(Loc.GetString("play-global-sound-command-arg-volume"))); } if (args.Length > 2) { var plyMgr = IoCManager.Resolve <IPlayerManager>(); var options = plyMgr.Sessions.Select(c => c.Name); return(CompletionResult.FromHintOptions( options, Loc.GetString("play-global-sound-command-arg-usern", ("user", args.Length - 2)))); } return(CompletionResult.Empty); }
private bool IsHardSelection( Model model, CompletionItem bestFilterMatch, SnapshotPoint caretPosition, CompletionHelper completionHelper, CompletionFilterReason filterReason) { var itemViewSpan = model.GetViewBufferSpan(bestFilterMatch.Span); var fullFilterText = model.GetCurrentTextInSnapshot(itemViewSpan, caretPosition.Snapshot, endPoint: null); var textSpan = itemViewSpan.TextSpan; // Switch to soft selection, if user moved caret to the start of a non-empty filter span. // This prevents commiting if user types a commit character at this position later, but // still has the list if user types filter character // i.e. blah| -> |blah -> !|blah // We want the filter span non-empty because we still want hard selection in the following case: // // A a = new | if (caretPosition == textSpan.Start && textSpan.Length > 0) { return(false); } return(ItemManager.IsHardSelection(fullFilterText, model.Trigger.Kind, bestFilterMatch, completionHelper, filterReason, this.Controller.GetRecentItems(), model.UseSuggestionMode)); }
internal virtual void VerifyCustomCommitWorker( CompletionService service, ICustomCommitCompletionProvider customCommitCompletionProvider, CompletionItem completionItem, CompletionHelper completionRules, ITextView textView, ITextBuffer textBuffer, string codeBeforeCommit, string expectedCodeAfterCommit, char?commitChar = null) { MarkupTestFile.GetPosition(expectedCodeAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); if (commitChar.HasValue && !Controller.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value, commitChar.Value.ToString())) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } customCommitCompletionProvider.Commit(completionItem, textView, textBuffer, textView.TextSnapshot, commitChar); string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); }
protected async Task VerifyCommitCharactersAsync(string initialMarkup, string textTypedSoFar, char[] validChars, char[] invalidChars = null) { Assert.NotNull(validChars); invalidChars = invalidChars ?? new[] { 'x' }; using (var workspace = await TestWorkspace.CreateCSharpAsync(initialMarkup)) { var hostDocument = workspace.DocumentWithCursor; var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; var completionList = await GetCompletionListAsync(document, position, CompletionTrigger.Default); var item = completionList.Items.First(i => i.DisplayText.StartsWith(textTypedSoFar)); var completionRules = CompletionHelper.GetHelper(document); foreach (var ch in validChars) { Assert.True(completionRules.IsCommitCharacter(item, ch, textTypedSoFar), $"Expected '{ch}' to be a commit character"); } foreach (var ch in invalidChars) { Assert.False(completionRules.IsCommitCharacter(item, ch, textTypedSoFar), $"Expected '{ch}' NOT to be a commit character"); } } }
public CompletionListUpdater( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, RecentItemsManager recentItemsManager, IGlobalOptionService globalOptions) { _session = session; _data = data; _recentItemsManager = recentItemsManager; _filterText = _session.ApplicableToSpan.GetText(_data.Snapshot); if (!_session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions)) { // This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger. // For now, the default hasSuggestedItemOptions is false. hasSuggestedItemOptions = false; } _hasSuggestedItemOptions = hasSuggestedItemOptions || _data.DisplaySuggestionItem; // We prefer using the original snapshot, which should always be available from items provided by Roslyn's CompletionSource. // Only use data.Snapshot in the theoretically possible but rare case when all items we are handling are from some non-Roslyn CompletionSource. var snapshotForDocument = TryGetInitialTriggerLocation(_data, out var intialTriggerLocation) ? intialTriggerLocation.Snapshot : _data.Snapshot; _document = snapshotForDocument?.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); if (_document != null) { _completionService = _document.GetLanguageService <CompletionService>(); _completionRules = _completionService?.GetRules(CompletionOptions.From(_document.Project)) ?? CompletionRules.Default; // Let us make the completion Helper used for non-Roslyn items case-sensitive. // We can change this if get requests from partner teams. _completionHelper = CompletionHelper.GetHelper(_document); _filterMethod = _completionService == null ? ((itemsWithPatternMatches, text) => CompletionService.FilterItems(_completionHelper, itemsWithPatternMatches, text)) : ((itemsWithPatternMatches, text) => _completionService.FilterItems(_document, itemsWithPatternMatches, text)); // Nothing to highlight if user hasn't typed anything yet. _highlightMatchingPortions = _filterText.Length > 0 && globalOptions.GetOption(CompletionViewOptions.HighlightMatchingPortionsOfCompletionListItems, _document.Project.Language); _showCompletionItemFilters = globalOptions.GetOption(CompletionViewOptions.ShowCompletionItemFilters, _document.Project.Language); } else { _completionService = null; _completionRules = CompletionRules.Default; // Let us make the completion Helper used for non-Roslyn items case-sensitive. // We can change this if get requests from partner teams. _completionHelper = new CompletionHelper(isCaseSensitive: true); _filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(_completionHelper, itemsWithPatternMatches, text); _highlightMatchingPortions = false; _showCompletionItemFilters = true; } }
public async Task TestEnter() { const string markup = @" class c { public int value {set; get; }} class d { void foo() { c foo = new c { v$$ } }"; using (var workspace = await TestWorkspace.CreateCSharpAsync(markup)) { var hostDocument = workspace.Documents.Single(); var position = hostDocument.CursorPosition.Value; var document = workspace.CurrentSolution.GetDocument(hostDocument.Id); var triggerInfo = CompletionTrigger.CreateInsertionTrigger('a'); var service = GetCompletionService(workspace); var completionList = await GetCompletionListAsync(service, document, position, triggerInfo); var item = completionList.Items.First(); var completionRules = CompletionHelper.GetHelper(document, service); Assert.False(completionRules.SendEnterThroughToEditor(item, string.Empty, workspace.Options), "Expected false from SendEnterThroughToEditor()"); } }
private static bool MatchesFilterText( CompletionHelper helper, CompletionItem item, string filterText, CompletionTrigger trigger, CompletionFilterReason filterReason, ImmutableArray <string> recentItems) { // For the deletion we bake in the core logic for how matching should work. // This way deletion feels the same across all languages that opt into deletion // as a completion trigger. // Specifically, to avoid being too aggressive when matching an item during // completion, we require that the current filter text be a prefix of the // item in the list. if (filterReason == CompletionFilterReason.Deletion && trigger.Kind == CompletionTriggerKind.Deletion) { return(item.FilterText.GetCaseInsensitivePrefixLength(filterText) > 0); } // If the user hasn't typed anything, and this item was preselected, or was in the // MRU list, then we definitely want to include it. if (filterText.Length == 0) { if (item.Rules.MatchPriority > MatchPriority.Default) { return(true); } if (!recentItems.IsDefault && GetRecentItemIndex(recentItems, item) <= 0) { return(true); } } return(helper.MatchesFilterText(item, filterText, CultureInfo.CurrentCulture)); }
internal ItemManager(RecentItemsManager recentItemsManager) { // Let us make the completion Helper used for non-Roslyn items case-sensitive. // We can change this if get requests from partner teams. _defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true); _recentItemsManager = recentItemsManager; }
public override async Task <CompletionDescription> GetDescriptionAsync(Document document, CancellationToken cancellationToken) { var languageServices = document.Project.LanguageServices; var snippetService = languageServices.GetService <ISnippetInfoService>(); var description = await this.CompletionService.GetDescriptionAsync(document, this.Item, cancellationToken).ConfigureAwait(false); var parts = description.TaggedParts; var change = await CompletionHelper.GetTextChangeAsync(this.CompletionService, document, this.Item, '\t').ConfigureAwait(false); var insertionText = change.NewText; var note = string.Empty; if (snippetService != null && snippetService.SnippetShortcutExists_NonBlocking(insertionText)) { note = string.Format(FeaturesResources.NoteTabTwiceToInsertTheSnippet, insertionText); } if (!string.IsNullOrEmpty(note)) { if (parts.Any()) { parts = parts.Add(new TaggedText(TextTags.LineBreak, Environment.NewLine)); } parts = parts.Add(new TaggedText(TextTags.Text, note)); } return(description.WithTaggedParts(parts)); }
private async Task VerifyProviderCommitCheckResultsAsync(Document document, int position, string itemToCommit, string expectedCodeAfterCommit, char?commitCharOpt, string textTypedSoFar) { var textBuffer = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().TextBuffer; var textSnapshot = textBuffer.CurrentSnapshot.AsText(); var items = (await GetCompletionListAsync(document, position, CompletionTrigger.Default)).Items; var firstItem = items.First(i => CompareItems(i.DisplayText, itemToCommit)); var completionRules = GetCompletionHelper(document); var commitChar = commitCharOpt ?? '\t'; var text = await document.GetTextAsync(); if (commitChar == '\t' || completionRules.IsCommitCharacter(firstItem, commitChar, textTypedSoFar)) { var textChange = CompletionHelper.GetTextChangeAsync(document, firstItem, commitChar).Result; // Adjust TextChange to include commit character, so long as it isn't TAB. if (commitChar != '\t') { textChange = new TextChange(textChange.Span, textChange.NewText.TrimEnd(commitChar) + commitChar); } text = text.WithChanges(textChange); } else { // nothing was committed, but we should insert the commit character. var textChange = new TextChange(new TextSpan(firstItem.Span.End, 0), commitChar.ToString()); text = text.WithChanges(textChange); } Assert.Equal(expectedCodeAfterCommit, text.ToString()); }
protected override IEnumerable <SimpleDothtmlCompletion> GetItemsCore(DothtmlCompletionContext context, string directiveName) { if (string.Equals(directiveName, Constants.ViewModelDirectiveName, StringComparison.InvariantCultureIgnoreCase) || string.Equals(directiveName, Constants.BaseTypeDirective, StringComparison.InvariantCultureIgnoreCase)) { // get icons for intellisense var classGlyph = context.GlyphService.GetGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPublic); var interfaceGlyph = context.GlyphService.GetGlyph(StandardGlyphGroup.GlyphGroupInterface, StandardGlyphItem.GlyphItemPublic); var nameFilter = string.Empty; var currentToken = context.Tokens[context.CurrentTokenIndex]; if (currentToken.Type == DothtmlTokenType.DirectiveValue) { var currentPosition = context.CompletionSession.TextView.Caret.Position.BufferPosition.Position; if (currentPosition != currentToken.StartPosition) { nameFilter = string.Concat(currentToken.Text.Take(currentPosition - currentToken.StartPosition)); } } // get list of all custom types var types = typeNames.GetOrRetrieve(() => { return(CompletionHelper.GetSyntaxTrees(context) .SelectMany(i => i.Tree.GetRoot().DescendantNodes().OfType <TypeDeclarationSyntax>() .Select(n => new { Symbol = i.SemanticModel.GetDeclaredSymbol(n), Compilation = i.Compilation, Node = n }) .Where(n => n.Symbol != null)) .Select(t => new CompletionDataWithGlyph() { CompletionData = new CompletionData( $"{t.Symbol.Name} (in namespace {t.Symbol.ContainingNamespace})", t.Symbol.ToString() + ", " + t.Compilation.AssemblyName), Glyph = t.Node is ClassDeclarationSyntax ? classGlyph : interfaceGlyph, Name = t.Symbol.Name, Namespace = t.Symbol.ContainingNamespace.ToString() }) .ToList()); }); if (!string.IsNullOrWhiteSpace(nameFilter)) { types = types.Where(w => w.Name.StartsWith(nameFilter, StringComparison.OrdinalIgnoreCase) || ($"{w.Namespace}.{w.Name}").StartsWith(nameFilter, StringComparison.OrdinalIgnoreCase)).ToList(); } // return completion items return(types.Select(t => new[] { new SimpleDothtmlCompletion(t.CompletionData.DisplayText, t.CompletionData.CompletionText, t.Glyph), new SimpleDothtmlCompletion(t.CompletionData.CompletionText, t.CompletionData.CompletionText, t.Glyph) }) .SelectMany(sm => sm)); } else { return(Enumerable.Empty <SimpleDothtmlCompletion>()); } }
public async Task <CompletionResult> GetCompletionData(int position, char?triggerChar, bool useSignatureHelp) { IList <ICompletionDataEx> completionData = null; IOverloadProviderEx overloadProvider = null; var document = _roslynHost.GetDocument(_documentId); if (useSignatureHelp || triggerChar != null) { var signatureHelpProvider = _roslynHost.GetService <ISignatureHelpProvider>(); var isSignatureHelp = useSignatureHelp || signatureHelpProvider.IsTriggerCharacter(triggerChar.Value); if (isSignatureHelp) { var signatureHelp = await signatureHelpProvider.GetItemsAsync( document, position, new SignatureHelpTriggerInfo( useSignatureHelp ? SignatureHelpTriggerReason.InvokeSignatureHelpCommand : SignatureHelpTriggerReason.TypeCharCommand, triggerChar)) .ConfigureAwait(false); if (signatureHelp != null) { overloadProvider = new RoslynOverloadProvider(signatureHelp); } } } if (overloadProvider == null) { var completionService = CompletionService.GetService(document); var completionTrigger = GetCompletionTrigger(triggerChar); var data = await completionService.GetCompletionsAsync( document, position, completionTrigger ).ConfigureAwait(false); if (data != null && data.Items.Any()) { var helper = CompletionHelper.GetHelper(document, completionService); var text = await document.GetTextAsync().ConfigureAwait(false); var textSpanToText = new Dictionary <TextSpan, string>(); completionData = data.Items .Where(item => MatchesFilterText(helper, item, text, textSpanToText, completionTrigger)) .Select(item => new RoslynCompletionData(document, item, triggerChar, _snippetService.SnippetManager)) .ToArray <ICompletionDataEx>(); } else { completionData = Array.Empty <ICompletionDataEx>(); } } return(new CompletionResult(completionData, overloadProvider)); }
private bool IsHardSelection( Model model, CompletionItem bestFilterMatch, SnapshotPoint caretPosition, CompletionHelper completionHelper, CompletionFilterReason reason) { if (bestFilterMatch == null || model.UseSuggestionMode) { return(false); } var textSnapshot = caretPosition.Snapshot; // We don't have a builder and we have a best match. Normally this will be hard // selected, except for a few cases. Specifically, if no filter text has been // provided, and this is not a preselect match then we will soft select it. This // happens when the completion list comes up implicitly and there is something in // the MRU list. In this case we do want to select it, but not with a hard // selection. Otherwise you can end up with the following problem: // // dim i as integer =<space> // // Completion will comes up after = with 'integer' selected (Because of MRU). We do // not want 'space' to commit this. var itemViewSpan = model.GetViewBufferSpan(bestFilterMatch.Span); var fullFilterText = model.GetCurrentTextInSnapshot(itemViewSpan, textSnapshot, endPoint: null); var trigger = model.Trigger; var shouldSoftSelect = ShouldSoftSelectItem(bestFilterMatch, fullFilterText, trigger); if (shouldSoftSelect) { return(false); } // If the user moved the caret left after they started typing, the 'best' match may not match at all // against the full text span that this item would be replacing. if (!MatchesFilterText(completionHelper, bestFilterMatch, fullFilterText, trigger, reason, this.Controller.GetRecentItems())) { return(false); } // Switch to soft selection, if user moved caret to the start of a non-empty filter span. // This prevents commiting if user types a commit character at this position later, but // still has the list if user types filter character // i.e. blah| -> |blah -> !|blah // We want the filter span non-empty because we still want hard selection in the following case: // // A a = new | if (caretPosition == itemViewSpan.TextSpan.Start && itemViewSpan.TextSpan.Length > 0) { return(false); } // There was either filter text, or this was a preselect match. In either case, we // can hard select this. return(true); }
public CompletionResult GetCompletion(IConsoleShell shell, string[] args) { return(args.Length switch { 1 => CompletionResult.FromHintOptions(CompletionHelper.SessionNames(), Loc.GetString("add-uplink-command-completion-1")), 2 => CompletionResult.FromHint(Loc.GetString("add-uplink-command-completion-2")), _ => CompletionResult.Empty });
void FilterModel(CompletionHelper helper) { computation.ChainTask((model, ct) => FilterModelAsync( compilationWorkspace, sourceTextContent, model, helper, ct)); }
private Model HandleNormalFiltering( Model model, Document document, CompletionFilterReason filterReason, ITextSnapshot textSnapshot, CompletionHelper helper, ImmutableArray <string> recentItems, string filterText, List <FilterResult> filterResults) { // Not deletion. Defer to the language to decide which item it thinks best // matches the text typed so far. // Ask the language to determine which of the *matched* items it wants to select. var service = this.Controller.GetCompletionService(); if (service == null) { return(null); } var matchingCompletionItems = filterResults.Where(r => r.MatchedFilterText) .Select(t => t.PresentationItem.Item) .AsImmutable(); var chosenItems = service.FilterItems( document, matchingCompletionItems, filterText); // Of the items the service returned, pick the one most recently committed var bestCompletionItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems); // If we don't have a best completion item yet, then pick the first item from the list. var bestOrFirstCompletionItem = bestCompletionItem ?? filterResults.First().PresentationItem.Item; var bestOrFirstPresentationItem = filterResults.Where( r => r.PresentationItem.Item == bestOrFirstCompletionItem).First().PresentationItem; var hardSelection = IsHardSelection( model, bestOrFirstPresentationItem, textSnapshot, helper, filterReason); // Determine if we should consider this item 'unique' or not. A unique item // will be automatically committed if the user hits the 'invoke completion' // without bringing up the completion list. An item is unique if it was the // only item to match the text typed so far, and there was at least some text // typed. i.e. if we have "Console.$$" we don't want to commit something // like "WriteLine" since no filter text has actually been provided. HOwever, // if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed. var matchingItemCount = matchingCompletionItems.Length; var isUnique = bestCompletionItem != null && matchingItemCount == 1 && filterText.Length > 0; var result = model.WithFilteredItems(filterResults.Select(r => r.PresentationItem).AsImmutable()) .WithSelectedItem(bestOrFirstPresentationItem) .WithHardSelection(hardSelection) .WithIsUnique(isUnique); return(result); }
public UIHelper(Calculator.Calculator calculator, TextEditor input, TextEditor output, ColumnDefinition outputColumn, GridSplitter splitter, Window window) { Calculator = calculator; Input = input; Output = output; BaseLineHeight = Convert.ToInt32(Properties.Settings.Default.line_height); this.outputColumn = outputColumn; this.splitter = splitter; this.window = window; LoadHighlightRule("Resources.HighlightRules.minu.xshd", "minu"); LoadHighlightRule("Resources.HighlightRules.output.xshd", "output"); input.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("minu"); output.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("output"); input.TextArea.TextView.Options.LineHeight = BaseLineHeight; output.TextArea.TextView.Options.LineHeight = BaseLineHeight; output.TextArea.TextView.Options.Alignment = TextAlignment.Right; SelectionHelper = new MouseSelectionHelper(output); SelectionHelper.OnClickEvent += (s, arg) => { Clipboard.SetText(arg.LineContent); }; tooltipHelper = new TooltipHelper(input, calculator, window); completionHelper = new CompletionHelper(input, calculator); input.SizeChanged += ReCalculateHandler; input.TextChanged += ReCalculateHandler; input.PreviewMouseWheel += previewMouseWheel; output.PreviewMouseWheel += previewMouseWheel; output.TextArea.SelectionChanged += SelectionChangedHandler; output.TextArea.MouseSelectionMode = ICSharpCode.AvalonEdit.Editing.MouseSelectionMode.None; // Debug input.Text = "square_root(x)=sqrt(x)\n" + "va = square_root(2*6.21*3.77*10^5) \n" + "pr = .01*2*va\n" + "vnew = pr/2\n" + "ta = va/6.21\n" + "g = 9.8\n" + "vland = tan(vnew^2+2*9.8*1.6*10^4)\n" + "F = 2*vland/.5\n" + "tl = (vland - vnew)/g \n" + "F/.15*100000\n" + "tpfff = (-.5*vland+ square_root((0.5*vland)^2-4*.5*g*-35))/2*.5*g\n" + "tp = sin(35/(.5*g)) \n" + ".5*vland*tp \n" + "ta+tl+tp+30+.5\n" + "va\n" + "vnew"; }
private static bool MatchesFilterText(CompletionHelper helper, CompletionItem item, SourceText text, Dictionary <TextSpan, string> textSpanToText, CompletionTrigger completionTrigger) { var filterText = GetFilterText(item, text, textSpanToText); if (string.IsNullOrEmpty(filterText)) { return(true); } return(helper.MatchesFilterText(item, filterText, completionTrigger)); }
public CompletionResult GetCompletion(IConsoleShell shell, string[] args) { return(args.Length switch { 1 => CompletionResult.FromHintOptions(CompletionHelper.SessionNames(), Loc.GetString("cmd-rolebanlist-hint-1")), 2 => CompletionResult.FromHintOptions(CompletionHelper.Booleans, Loc.GetString("cmd-rolebanlist-hint-2")), _ => CompletionResult.Empty });
private CompletionHelper GetCompletionHelper() { var document = GetDocument(); if (document != null) { return(CompletionHelper.GetHelper(document)); } return(null); }
private CompletionHelper GetCompletionHelper() { var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { return(CompletionHelper.GetHelper(document)); } return(null); }
private List <INamedTypeSymbol> ReloadAllClasses(DothtmlCompletionContext context) { return(allClasses.GetOrRetrieve(() => { var syntaxTrees = CompletionHelper.GetSyntaxTrees(context); var ownSymbols = syntaxTrees.SelectMany(t => t.Tree.GetRoot().DescendantNodes().OfType <ClassDeclarationSyntax>() .Select(c => t.SemanticModel.GetDeclaredSymbol(c))).ToList(); var referencedSymbols = CompletionHelper.GetReferencedSymbols(context); return Enumerable.Concat(referencedSymbols, ownSymbols).OfType <INamedTypeSymbol>() .Where(c => c.DeclaredAccessibility == Accessibility.Public && !c.IsAbstract) .ToList(); })); }
public async Task <CompletionResult> CompleteAsync(string sourceCode, int position, char?triggerChar) { _CancellationTokenSource?.Cancel(); _CancellationTokenSource?.Dispose(); _CancellationTokenSource = new CancellationTokenSource(); try { var workspace = new AdhocWorkspace(_Host); var projectInfo = ProjectInfo .Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Project", "Project", LanguageNames.CSharp) .WithMetadataReferences(new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }); var project = workspace.AddProject(projectInfo); var document = workspace.AddDocument(project.Id, "File.cs", SourceText.From(sourceCode)); var completionService = CompletionService.GetService(document); var completionTrigger = GetCompletionTrigger(triggerChar); var data = await completionService.GetCompletionsAsync(document, position, completionTrigger, null, null, _CancellationTokenSource.Token) .ConfigureAwait(false); if (data == null || data.Items == null) { return(new CompletionResult(Array.Empty <CompleteData>())); } var helper = CompletionHelper.GetHelper(document); var text = await document.GetTextAsync(_CancellationTokenSource.Token).ConfigureAwait(false); var textSpanToText = new Dictionary <TextSpan, string>(); var items = data.Items .Where(item => MatchesFilterText(helper, item, text, textSpanToText)) .OrderBy(x => x.DisplayText) .Distinct(x => x.DisplayText) .Select(x => new CompleteData( x, completionService, document) ).ToArray(); return(new CompletionResult(items)); } catch (OperationCanceledException) { return(new CompletionResult(Array.Empty <CompleteData>())); } }
private bool IsHardSelection( Model model, PresentationItem bestFilterMatch, ITextSnapshot textSnapshot, CompletionHelper completionRules, CompletionTrigger trigger, CompletionFilterReason reason) { if (model.SuggestionModeItem != null) { return(bestFilterMatch != null && bestFilterMatch.Item.DisplayText == model.SuggestionModeItem.Item.DisplayText); } if (bestFilterMatch == null || model.UseSuggestionMode) { return(false); } // We don't have a builder and we have a best match. Normally this will be hard // selected, except for a few cases. Specifically, if no filter text has been // provided, and this is not a preselect match then we will soft select it. This // happens when the completion list comes up implicitly and there is something in // the MRU list. In this case we do want to select it, but not with a hard // selection. Otherwise you can end up with the following problem: // // dim i as integer =<space> // // Completion will comes up after = with 'integer' selected (Because of MRU). We do // not want 'space' to commit this. var viewSpan = model.GetViewBufferSpan(bestFilterMatch.Item.Span); var fullFilterText = model.GetCurrentTextInSnapshot(viewSpan, textSnapshot, endPoint: null); var shouldSoftSelect = completionRules.ShouldSoftSelectItem(bestFilterMatch.Item, fullFilterText, trigger); if (shouldSoftSelect) { return(false); } // If the user moved the caret left after they started typing, the 'best' match may not match at all // against the full text span that this item would be replacing. if (!completionRules.MatchesFilterText(bestFilterMatch.Item, fullFilterText, trigger, reason, this.Controller.GetRecentItems())) { return(false); } // There was either filter text, or this was a preselect match. In either case, we // can hard select this. return(true); }
private CompletionHelper GetCompletionHelper() { this.AssertIsForeground(); if (_completionHelper == null) { var document = GetDocument(); if (document != null) { _completionHelper = CompletionHelper.GetHelper(document); } } return(_completionHelper); }
private async Task CheckResultsAsync( Document document, int position, string expectedItemOrNull, string expectedDescriptionOrNull, bool usePreviousCharAsTrigger, bool checkForAbsence, Glyph?glyph) { var code = (await document.GetTextAsync()).ToString(); CompletionTrigger trigger = CompletionTrigger.Default; if (usePreviousCharAsTrigger) { trigger = CompletionTrigger.CreateInsertionTrigger(insertedCharacter: code.ElementAt(position - 1)); } var completionService = GetCompletionService(document.Project.Solution.Workspace); var completionList = await GetCompletionListAsync(completionService, document, position, trigger); var items = completionList == null ? default(ImmutableArray <CompletionItem>) : completionList.Items; if (checkForAbsence) { if (items == null) { return; } if (expectedItemOrNull == null) { Assert.Empty(items); } else { AssertEx.None( items, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true)); } } else { if (expectedItemOrNull == null) { Assert.NotEmpty(items); } else { AssertEx.Any(items, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true) && (glyph.HasValue ? CompletionHelper.TagsEqual(c.Tags, GlyphTags.GetTags(glyph.Value)) : true)); } } }
private CompletionHelper GetCompletionHelper() { _foregroundObject.AssertIsForeground(); if (_completionHelper == null) { var document = _subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { _completionHelper = CompletionHelper.GetHelper(document); } } return(_completionHelper); }
// 튜토리얼 선행 조건 체크 static public bool CheckCondition(TutorialInfo info) { ETutorialCondition conditionType = (ETutorialCondition)info.GetStartData().GetCONDITION_TYPE(); string conditionValue = info.GetStartData().GetCONDITION_VALUE(); switch (conditionType) { case ETutorialCondition.EnterDungeon: // 던전 입장시 DataDungeon enterData = DataDungeon.GetByEnumID(conditionValue); if (enterData != null && BattleInfo != null) { return(enterData == BattleInfo.DataDungeon); } break; case ETutorialCondition.ClearDungeon: // 던전 클리어 DataDungeon clearData = DataDungeon.GetByEnumID(conditionValue); if (clearData != null) { return(DungeonHelper.GetDungeonRating(clearData) > 0); } break; case ETutorialCondition.ClearTutorial: // 튜토리얼 클리어 DataTutorial tutorialData = DataTutorial.GetByEnumID(conditionValue); if (tutorialData != null) { ETutorialGroup group = (ETutorialGroup)tutorialData.GetGROUP_TYPE(); return(IsClearByGroup(group)); } break; case ETutorialCondition.ClearCompletion: // 컴플리션 클리어 DataCompletion completionData = DataCompletion.GetByEnumID(conditionValue); if (completionData != null) { CompletionInfo completeInfo = CompletionHelper.GetMyCompletion(completionData.GetID()); if (completeInfo != null) { return(CompletionHelper.IsComplete(completeInfo)); } } break; case ETutorialCondition.None: return(true); } return(false); }
private CompletionHelper GetCompletionHelper() { this.AssertIsForeground(); if (_completionHelper == null) { var document = GetDocument(); if (document != null) { _completionHelper = CompletionHelper.GetHelper(document, document.Project.LanguageServices.GetService <CompletionService>()); } } return(_completionHelper); }
public CompletionResult GetCompletion(IConsoleShell shell, string[] args) { switch (args.Length) { case 1: return(CompletionResult.FromHint(Loc.GetString("cmd-hint-mapping-id"))); case 2: var res = IoCManager.Resolve <IResourceManager>(); var opts = CompletionHelper.UserFilePath(args[1], res.UserData) .Concat(CompletionHelper.ContentFilePath(args[1], res)); return(CompletionResult.FromHintOptions(opts, Loc.GetString("cmd-hint-mapping-path"))); } return(CompletionResult.Empty); }