public static Task <(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsAsync(
     this CompletionService completionService,
     Document document,
     int caretPosition,
     CompletionTrigger trigger       = default,
     ImmutableHashSet <string>?roles = null,
     OptionSet?options = null,
     CancellationToken cancellationToken = default)
 => completionService.GetCompletionsInternalAsync(document, caretPosition, trigger, roles, options, cancellationToken);
示例#2
0
        private CompletionProvider GetCompletionProvider(CompletionService completionService, CompletionItem item)
        {
            if (completionService is CompletionServiceWithProviders completionServiceWithProviders)
            {
                return(completionServiceWithProviders.GetProvider(item));
            }

            return(null);
        }
示例#3
0
        public DescriptionModifyingPresentationItem(CompletionItem item, CompletionService completionService, bool isSuggestionModeItem = false)
        {
            Debug.Assert(item != null);
            Debug.Assert(completionService != null);

            this.Item = item;
            this.CompletionService    = completionService;
            this.IsSuggestionModeItem = isSuggestionModeItem;
        }
示例#4
0
 public CompleteData(
     CompletionItem item,
     CompletionService completionService,
     Document document)
 {
     Item = item;
     CompletionService = completionService;
     Document          = document;
 }
 public static Task <(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync(
     this CompletionService completionService,
     Document document,
     int caretPosition,
     CompletionTrigger trigger       = default,
     ImmutableHashSet <string> roles = null,
     OptionSet options = null,
     CancellationToken cancellationToken = default)
 => (Task <(CompletionList completionList, bool expandItemsAvailable)>)_getCompletionsInternalAsync.Invoke(completionService, new object[] { document, caretPosition, trigger, roles, options, cancellationToken });
 private static void prepareScript(string code)
 {
     scriptDocumentInfo = DocumentInfo.Create(
         DocumentId.CreateNewId(project), "Script",
         sourceCodeKind: SourceCodeKind.Script,
         loader: TextLoader.From(TextAndVersion.Create(SourceText.From(code), VersionStamp.Create())));
     replaceDocument(scriptDocumentInfo);
     service = CompletionService.GetService(scriptDocument);
 }
示例#7
0
        public async Task AfterSelect_ShouldShowSelectionSuggestion(int position, params string[] sourceFiles)
        {
            var document = CreateCSharpDocument(sourceFiles);
            var service  = CompletionService.GetService(document);
            var actual   = await service.GetCompletionsAsync(document, position);

            actual.Should().NotBeNull();
            actual.Items.Should().HaveCount(1);
        }
        private async Task RetrieveDescription()
        {
            if (_description != null)
            {
                var description = await Task.Run(() => CompletionService.GetService(_document).GetDescriptionAsync(_document, _item)).ConfigureAwait(true);

                _description.Child = description.TaggedParts.ToTextBlock();
            }
        }
示例#9
0
        public async Task NotADapperCall_ShouldNotShowAnyCustomItems(string source)
        {
            var document = CreateCSharpDocument <DapperCompletionProvider>(References, source);
            int position = await GetPositionAsync(document, 9, 23);

            var service = CompletionService.GetService(document);
            var actual  = await service.GetCompletionsAsync(document, position);

            actual.Should().BeNull("because it is a completion inside non-Dapper call");
        }
 RoslynCompletionSet(IMruCompletionService mruCompletionService, CompletionService completionService, ITextView textView, string moniker, string displayName, ITrackingSpan applicableTo, List <Completion> completions, List <Completion> completionBuilders, RoslynIntellisenseFilter[] filters)
     : base(moniker, displayName, applicableTo, completions, completionBuilders, filters)
 {
     this.mruCompletionService = mruCompletionService;
     this.completionService    = completionService;
     this.textView             = textView;
     originalSnapshot          = applicableTo.TextBuffer.CurrentSnapshot;
     InitializeCompletions(completions);
     InitializeCompletions(completionBuilders);
 }
        public ImmutableArray <CompletionItem> FilterCompletionItems(ImmutableArray <CompletionItem> items, string filterText)
        {
            if (CurrentDocument != null)
            {
                CompletionService completionService = CompletionService.GetService(CurrentDocument);
                return(completionService.FilterItems(CurrentDocument, items, filterText));
            }

            return(ImmutableArray <CompletionItem> .Empty);
        }
        public Task <CompletionChange?> GetCompletionChangeAsync(CompletionItem item)
        {
            if (CurrentDocument != null)
            {
                CompletionService completionService = CompletionService.GetService(CurrentDocument);
                return(completionService.GetChangeAsync(CurrentDocument, item));
            }

            return(Task.FromResult <CompletionChange?>(null));
        }
        private static async Task <string> GetInsertionTextAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
        {
            var service = CompletionService.GetService(document);
            var change  = await service.GetChangeAsync(document, item, commitCharacter : null, cancellationToken).ConfigureAwait(false);

            var text         = change.TextChange.NewText;
            var nonCharIndex = text.IndexOfAny(s_punctuation);

            return(nonCharIndex > 0
                ? text[0..nonCharIndex]
        private CompletionService GetCompletionService(Document document)
        {
            var completionService = CompletionService.GetService(document);

            if (completionService == null)
            {
                throw new Exception("Failed to retrieve the completion service.");
            }
            return(completionService);
        }
            public CompletionListUpdater(
                ITrackingSpan applicableToSpan,
                CompletionSessionData sessionData,
                AsyncCompletionSessionDataSnapshot snapshotData,
                RecentItemsManager recentItemsManager,
                IGlobalOptionService globalOptions)
            {
                _sessionData        = sessionData;
                _snapshotData       = snapshotData;
                _recentItemsManager = recentItemsManager;

                _applicableToSpan = applicableToSpan;
                _filterText       = applicableToSpan.GetText(_snapshotData.Snapshot);

                _hasSuggestedItemOptions = _sessionData.HasSuggestionItemOptions || _snapshotData.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(_snapshotData, out var intialTriggerLocation)
                    ? intialTriggerLocation.Snapshot
                    : _snapshotData.Snapshot;

                _document = snapshotForDocument?.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
                if (_document != null)
                {
                    _completionService = _document.GetLanguageService <CompletionService>();
                    _completionRules   = _completionService?.GetRules(globalOptions.GetCompletionOptions(_document.Project.Language)) ?? 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;
                }
            }
示例#16
0
 public static Task <CompletionList> GetCompletionsAsync(
     this CompletionService completionService,
     Document document,
     int caretPosition,
     CompletionTrigger trigger,
     ImmutableHashSet <string>?roles,
     OmniSharpCompletionOptions options,
     CancellationToken cancellationToken)
 {
     return(completionService.GetCompletionsAsync(document, caretPosition, options.ToCompletionOptions(), document.Project.Solution.Options, trigger, roles, cancellationToken));
 }
        public RoslynSession(SourceText sourceText, ProjectInfo projectInfo, MefHostServices hostServices, ImmutableArray <DiagnosticAnalyzer> analyzers, ImmutableDictionary <string, ImmutableArray <CodeFixProvider> > codeFixProviders, ImmutableArray <ISignatureHelpProviderWrapper> signatureHelpProviders)
        {
            _workspace         = new CustomWorkspace(hostServices);
            _sourceText        = sourceText;
            _document          = CreateProjectAndOpenNewDocument(_workspace, projectInfo, sourceText);
            _completionService = GetCompletionService(_document);

            Analyzers = analyzers;
            SignatureHelpProviders = signatureHelpProviders;
            CodeFixProviders       = codeFixProviders;
        }
示例#18
0
        public async Task <IList <CompletionItem> > GetCompletion(CompletionTriggerInfo trigger, int position)
        {
            var groups = await CompletionService.GetCompletionItemGroupsAsync(
                GetCurrentDocument(), position, trigger).ConfigureAwait(false);

            if (groups == null)
            {
                return(new CompletionItem[0]);
            }
            return(groups.SelectMany(t => t.Items).ToArray());
        }
        public void AcquireCompletionService()
        {
            var workspace = new AdhocWorkspace();

            var document = workspace
                           .AddProject("TestProject", LanguageNames.CSharp)
                           .AddDocument("TestDocument.cs", "");

            var service = CompletionService.GetService(document);

            Assert.NotNull(service);
        }
示例#20
0
        private async Task <IEnumerable <CompletionItem> > GetCompletionList(string code, int cursorPosition, ScriptState scriptState)
        {
            var metadataReferences = ImmutableArray <MetadataReference> .Empty;

            var forcedState = false;

            if (scriptState == null)
            {
                scriptState = await CSharpScript.RunAsync("", ScriptOptions);

                forcedState = true;
            }

            var compilation = scriptState.Script.GetCompilation();

            metadataReferences = metadataReferences.AddRange(compilation.References);

            var buffer = new StringBuilder(forcedState ? string.Empty : scriptState.Script.Code ?? string.Empty);

            buffer.AppendLine(code);
            var fullScriptCode   = buffer.ToString();
            var offset           = fullScriptCode.LastIndexOf(code, StringComparison.InvariantCulture);
            var absolutePosition = Math.Max(offset, 0) + cursorPosition;

            if (_fixture == null || _metadataReferences != metadataReferences)
            {
                _fixture            = new WorkspaceFixture(compilation.Options, metadataReferences);
                _metadataReferences = metadataReferences;
            }

            var document = _fixture.ForkDocument(fullScriptCode);
            var service  = CompletionService.GetService(document);

            var completionList = await service.GetCompletionsAsync(document, absolutePosition);

            var semanticModel = await document.GetSemanticModelAsync();

            var symbols = await Recommender.GetRecommendedSymbolsAtPositionAsync(semanticModel, absolutePosition, document.Project.Solution.Workspace);

            var symbolToSymbolKey = new Dictionary <(string, int), ISymbol>();

            foreach (var symbol in symbols)
            {
                var key = (symbol.Name, (int)symbol.Kind);
                if (!symbolToSymbolKey.ContainsKey(key))
                {
                    symbolToSymbolKey[key] = symbol;
                }
            }
            var items = completionList.Items.Select(item => item.ToModel(symbolToSymbolKey, document).ToDomainObject()).ToArray();

            return(items);
        }
        private async Task CreateSpellCheckCodeIssueAsync(CodeFixContext context, TSimpleName nameNode, string nameText, CancellationToken cancellationToken)
        {
            var document = context.Document;
            var service  = CompletionService.GetService(document);

            // Disable snippets from ever appearing in the completion items. It's
            // very unlikely the user would ever mispell a snippet, then use spell-
            // checking to fix it, then try to invoke the snippet.
            var originalOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);

            var options = originalOptions.WithChangedOption(CompletionOptions.SnippetsBehavior, document.Project.Language, SnippetsRule.NeverInclude);

            var completionList = await service.GetCompletionsAsync(
                document, nameNode.SpanStart, options : options, cancellationToken : cancellationToken).ConfigureAwait(false);

            if (completionList == null)
            {
                return;
            }

            var onlyConsiderGenerics = IsGeneric(nameNode);
            var results = new MultiDictionary <double, string>();

            using (var similarityChecker = new WordSimilarityChecker(nameText, substringsAreSimilar: true))
            {
                foreach (var item in completionList.Items)
                {
                    if (onlyConsiderGenerics && !IsGeneric(item))
                    {
                        continue;
                    }

                    var    candidateText = item.FilterText;
                    double matchCost;
                    if (!similarityChecker.AreSimilar(candidateText, out matchCost))
                    {
                        continue;
                    }

                    var insertionText = await GetInsertionTextAsync(document, item, cancellationToken : cancellationToken).ConfigureAwait(false);

                    results.Add(matchCost, insertionText);
                }
            }

            var matches = results.OrderBy(kvp => kvp.Key)
                          .SelectMany(kvp => kvp.Value.Order())
                          .Where(t => t != nameText)
                          .Take(3)
                          .Select(n => CreateCodeAction(nameNode, nameText, n, document));

            context.RegisterFixes(matches, context.Diagnostics);
        }
        public Task <CompletionList?> GetCompletionListAsync(int position)
        {
            if (CurrentDocument != null)
            {
                Document          document          = CurrentDocument;
                CompletionService completionService = CompletionService.GetService(document);

                return(completionService.GetCompletionsAsync(document, position));
            }

            return(Task.FromResult <CompletionList?>(null));
        }
示例#23
0
        private async Task <IEnumerable <CompletionItem> > GetCompletionList(
            string code,
            int cursorPosition)
        {
            var compilation  = ScriptState.Script.GetCompilation();
            var originalCode =
                ScriptState?.Script.Code ?? string.Empty;

            var buffer = new StringBuilder(originalCode);

            if (!string.IsNullOrWhiteSpace(originalCode) && !originalCode.EndsWith(Environment.NewLine))
            {
                buffer.AppendLine();
            }

            buffer.AppendLine(code);
            var fullScriptCode   = buffer.ToString();
            var offset           = fullScriptCode.LastIndexOf(code, StringComparison.InvariantCulture);
            var absolutePosition = Math.Max(offset, 0) + cursorPosition;

            if (_fixture == null || ShouldRebuild())
            {
                _fixture = new WorkspaceFixture(compilation.Options, compilation.References);
            }

            var document = _fixture.ForkDocument(fullScriptCode);
            var service  = CompletionService.GetService(document);

            var completionList = await service.GetCompletionsAsync(document, absolutePosition);

            var semanticModel = await document.GetSemanticModelAsync();

            var symbols = await Recommender.GetRecommendedSymbolsAtPositionAsync(semanticModel, absolutePosition, document.Project.Solution.Workspace);

            var symbolToSymbolKey = new Dictionary <(string, int), ISymbol>();

            foreach (var symbol in symbols)
            {
                var key = (symbol.Name, (int)symbol.Kind);
                if (!symbolToSymbolKey.ContainsKey(key))
                {
                    symbolToSymbolKey[key] = symbol;
                }
            }
            var items = completionList.Items.Select(item => item.ToModel(symbolToSymbolKey, document)).ToArray();

            return(items);

            bool ShouldRebuild()
            {
                return(compilation.References.Count() != _fixture.MetadataReferences.Count());
            }
        }
示例#24
0
        public async static Task Initialize()
        {
            CodeEditor ce = null;

            GenericTools.RunUI(() =>
            {
                ce          = new CodeEditor();
                ce.document = ce.Initialize();
            });
            var completionService = CompletionService.GetService(ce.document);
            var completionList    = await Task.Run(async() => await completionService.GetCompletionsAsync(ce.document, 0));
        }
示例#25
0
        public static async ValueTask <bool> ShouldTriggerCompletionAsync(
            this CompletionService completionService,
            Document document,
            int caretPosition,
            CompletionTrigger trigger,
            ImmutableHashSet <string>?roles,
            OmniSharpCompletionOptions options,
            CancellationToken cancellationToken)
        {
            var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

            return(completionService.ShouldTriggerCompletion(document.Project, document.Project.LanguageServices, text, caretPosition, trigger, options.ToCompletionOptions(), document.Project.Solution.Options, roles));
        }
示例#26
0
        /// <summary>
        /// Método utilizado para determinar se o caractere
        /// digitado pelo usuário pode ser utilizado para
        /// abrir a janela de sugestões do editor
        /// </summary>
        /// <param name="position">Posição atual do cursor</param>
        /// <returns>True se o caractere digitado é um gatilho, False do contrário</returns>
        public async Task <bool> ShouldTriggerCompletion(int position)
        {
            return(await Task.Run(() =>
            {
                if (position < 1)
                {
                    return false;
                }

                var completionService = CompletionService.GetService(document);
                return completionService.ShouldTriggerCompletion(sourceText, position, CompletionTrigger.CreateInsertionTrigger(documentCode[position - 1]));
            }));
        }
示例#27
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            try
            {
                if (!context.Document.SupportsSemanticModel || !context.Document.SupportsSyntaxTree)
                {
                    return;
                }

                var hasMoqReferenced = context.Document.Project.MetadataReferences.Any(r => r.Display.Contains(this._provider.AssemblyName));
                if (!hasMoqReferenced)
                {
                    return;
                }

                var syntaxRoot = await context.Document.GetSyntaxRootAsync();

                var token = SyntaxHelpers.GetSelectedTokens(syntaxRoot, context.Position);

                // Not in an opened method
                if (token.Parent == null)
                {
                    return;
                }

                var mockedMethodArgumentList = token.Parent as ArgumentListSyntax;
                var setupMethodInvocation    = mockedMethodArgumentList.Ancestors()
                                               .OfType <InvocationExpressionSyntax>()
                                               .Where(IsMoqSetupMethod)
                                               .FirstOrDefault();

                if (setupMethodInvocation == null)
                {
                    return;
                }

                var semanticModel = await context.Document.GetSemanticModelAsync();

                var matchingMockedMethods = SyntaxHelpers.GetCandidatesMockedMethodSignaturesForLambda(semanticModel, setupMethodInvocation);

                var completionService = new CompletionService(context, token, semanticModel, this._provider);

                foreach (IMethodSymbol matchingMockedMethodSymbol in matchingMockedMethods)
                {
                    completionService.AddSuggestionsForMethod(matchingMockedMethodSymbol, mockedMethodArgumentList);
                }
            }
            catch
            {
            }
        }
示例#28
0
        public async Task does_not_trigger_completion(string code)
        {
            var hostServices = MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(
                                                          new[]
            {
                typeof(CompletionService).Assembly,
                typeof(ResourceCompletionProvider).Assembly,
            }));

            var workspace = new AdhocWorkspace(hostServices);
            var document  = workspace
                            .AddProject("TestProject", LanguageNames.CSharp)
                            .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                            .WithMetadataReferences(Directory
                                                    .EnumerateFiles("MonoAndroid", "*.dll")
                                                    .Select(dll => MetadataReference.CreateFromFile(dll)))
                            .AddDocument("Resource.designer.cs", @"[assembly: global::Android.Runtime.ResourceDesignerAttribute(""MyApp.Resource"", IsApplication=true)]
namespace MyApp
{
    [System.CodeDom.Compiler.GeneratedCodeAttribute(""Xamarin.Android.Build.Tasks"", ""1.0.0.0"")]
    public partial class Resource
    {
        public partial class String
        {
            public const int app_name = 2130968578;
            public const int app_title = 2130968579;
        }
        public partial class Style
        {
            public const int AppTheme = 2131034114;
        }
    }
}")
                            .Project
                            .AddDocument("TestDocument.cs", code.Replace("`", ""));

            var service = CompletionService.GetService(document);

            Assert.NotNull(service);

            var caret = code.IndexOf('`');

            Assert.NotEqual(-1, caret);

            var completions = await service.GetCompletionsAsync(document, caret);

            if (completions != null)
            {
                Assert.DoesNotContain(completions.Items, x => x.Tags.Contains("Xamarin"));
            }
        }
示例#29
0
        private bool StartNewModelComputation(CompletionService completionService, CompletionTrigger trigger, bool filterItems, bool dismissIfEmptyAllowed = true)
        {
            AssertIsForeground();
            Contract.ThrowIfTrue(sessionOpt != null);

            if (this.TextView.Selection.Mode == TextSelectionMode.Box)
            {
                Trace.WriteLine("Box selection, cannot have completion");

                // No completion with multiple selection
                return(false);
            }

            // The caret may no longer be mappable into our subject buffer.
            var caret = TextView.GetCaretPoint(SubjectBuffer);

            if (!caret.HasValue)
            {
                Trace.WriteLine("Caret is not mappable to subject buffer, cannot have completion");

                return(false);
            }

            if (this.TextView.Caret.Position.VirtualBufferPosition.IsInVirtualSpace)
            {
                // Convert any virtual whitespace to real whitespace by doing an empty edit at the caret position.
                _editorOperationsFactoryService.GetEditorOperations(TextView).InsertText("");
            }

            var computation = new ModelComputation <Model>(this, PrioritizedTaskScheduler.AboveNormalInstance);

            this.sessionOpt = new Session(this, computation, Presenter.CreateSession(TextView, SubjectBuffer, null));

            sessionOpt.ComputeModel(completionService, trigger, _roles, GetOptions());

            var filterReason = trigger.Kind == CompletionTriggerKind.Deletion
                ? CompletionFilterReason.BackspaceOrDelete
                : CompletionFilterReason.TypeChar;

            if (filterItems)
            {
                sessionOpt.FilterModel(filterReason, dismissIfEmptyAllowed: dismissIfEmptyAllowed);
            }
            else
            {
                sessionOpt.IdentifyBestMatchAndFilterToAllItems(filterReason, dismissIfEmptyAllowed: dismissIfEmptyAllowed);
            }

            return(true);
        }
示例#30
0
        private static async Task <ImmutableArray <TaggedText> > GetDescriptionAsync(CompletionService completionService, Document document, CompletionItem completionItem)
        {
            try
            {
                var desc = await completionService.GetDescriptionAsync(document, completionItem);

                var res = desc.TaggedParts;
                // var res = (await Task.Run(async () => )).TaggedParts;
                return(res);
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                return(default);