Exemplo n.º 1
0
 public static Task <(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync(
     this Microsoft.CodeAnalysis.Completion.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 });
Exemplo n.º 2
0
		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);
		}
        /// <summary>
        /// Internal for testing purposes only.
        /// </summary>
        internal static async Task<TextChange> GetTextChangeAsync(
            CompletionService service, Document document, CompletionItem item,
            char? commitKey = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var change = await service.GetChangeAsync(document, item, commitKey, cancellationToken).ConfigureAwait(false);

            // normally the items that produce multiple changes are not expecting to trigger the behaviors that rely on looking at the text
            return change.TextChange;
        }
Exemplo n.º 4
0
        public SimplePresentationItem(CompletionItem item, CompletionService completionService, bool isSuggestionModeItem = false)
        {
            Debug.Assert(item != null);
            Debug.Assert(completionService != null);

            this.Item = item;
            this.CompletionService = completionService;
            this.IsSuggestionModeItem = isSuggestionModeItem;
        }
Exemplo n.º 5
0
        public static async Task <CompletionList> GetCompletionListAsync(Document document, int position,
                                                                         CompletionTriggerInfo triggerInfo, OptionSet options = null,
                                                                         CancellationToken cancellationToken = default(CancellationToken))
        {
            var providers = GetCompletionListProviders(document);
            var list      = await InnerCompletionService.GetCompletionListAsync(document, position, triggerInfo.Inner, options, providers,
                                                                                cancellationToken).ConfigureAwait(false);

            return(list == null ? null : new CompletionList(list));
        }
Exemplo n.º 6
0
        private static IEnumerable <CompletionListProvider> GetCompletionListProviders(Document document)
        {
            var languageService = document.GetLanguageService <ICompletionService>();
            IEnumerable <CompletionListProvider> providers = null;

            if (languageService != null)
            {
                providers = InnerCompletionService.GetDefaultCompletionListProviders(document);
                if (_additionalProviders != null)
                {
                    providers = providers.Concat(_additionalProviders);
                }
            }
            return(providers);
        }
        public async Task <IEnumerable <AutoCompleteResponse> > Handle(AutoCompleteRequest request)
        {
            var documents      = _workspace.GetDocuments(request.FileName);
            var wordToComplete = request.WordToComplete;
            var completions    = new HashSet <AutoCompleteResponse>();

            foreach (var document in documents)
            {
                var sourceText = await document.GetTextAsync();

                var position = sourceText.GetTextPosition(request);
                var service  = CompletionService.GetService(document);
                var options  = new OmniSharpCompletionOptions(
                    ShowItemsFromUnimportedNamespaces: _omniSharpOptions.RoslynExtensionsOptions.EnableImportCompletion,
                    ForceExpandedCompletionIndexCreation: false);
                var completionList = await OmniSharpCompletionService.GetCompletionsAsync(service, document, position, trigger : default, roles : null, options, CancellationToken.None);
            public void ComputeModel(
                CompletionService completionService,
                CompletionTrigger trigger,
                ImmutableHashSet<string> roles,
                OptionSet options)
            {
                AssertIsForeground();

                // If we've already computed a model then we can just ignore this request and not
                // generate any tasks.
                if (this.Computation.InitialUnfilteredModel != null)
                {
                    return;
                }

                new ModelComputer(this, completionService, trigger, roles, options).Do();
            }
Exemplo n.º 9
0
        public static CompletionHelper GetHelper(
            Workspace workspace, string language, CompletionService completionService)
        {
            var ls = workspace.Services.GetLanguageServices(language);
            if (ls != null)
            {
                var factory = ls.GetService<CompletionHelperFactory>();
                if (factory != null)
                {
                    return factory.CreateCompletionHelper(completionService);
                }

                if (completionService != null)
                {
                    return new CompletionHelper(completionService);
                }
            }

            return null;
        }
                public ModelComputer(
                    Session session,
                    CompletionService completionService,
                    CompletionTrigger trigger,
                    ImmutableHashSet<string> roles,
                    OptionSet options)
                {
                    _session = session;
                    _completionService = completionService;
                    _options = options;
                    _trigger = trigger;
                    _subjectBufferCaretPosition = session.Controller.TextView.GetCaretPoint(session.Controller.SubjectBuffer).Value;
                    _roles = roles;

                    _text = _subjectBufferCaretPosition.Snapshot.AsText();

                    _useSuggestionMode = session.Controller.SubjectBuffer.GetFeatureOnOffOption(Options.EditorCompletionOptions.UseSuggestionMode);

                    _disconnectedBufferGraph = new DisconnectedBufferGraph(session.Controller.SubjectBuffer, session.Controller.TextView.TextBuffer);
                }
Exemplo n.º 11
0
		public static RoslynCompletionSet Create(IImageMonikerService imageMonikerService, IMruCompletionService mruCompletionService, CompletionList completionList, CompletionService completionService, ITextView textView, string moniker, string displayName, ITrackingSpan applicableTo) {
			if (imageMonikerService == null)
				throw new ArgumentNullException(nameof(imageMonikerService));
			if (mruCompletionService == null)
				throw new ArgumentNullException(nameof(mruCompletionService));
			if (completionList == null)
				throw new ArgumentNullException(nameof(completionList));
			if (completionService == null)
				throw new ArgumentNullException(nameof(completionService));
			if (textView == null)
				throw new ArgumentNullException(nameof(textView));
			if (moniker == null)
				throw new ArgumentNullException(nameof(moniker));
			if (displayName == null)
				throw new ArgumentNullException(nameof(displayName));
			if (applicableTo == null)
				throw new ArgumentNullException(nameof(applicableTo));
			var completions = new List<Completion>(completionList.Items.Length);
			var remainingFilters = new List<KeyValuePair<RoslynIntellisenseFilter, int>>(RoslynIntellisenseFilters.CreateFilters(imageMonikerService).Select((a, index) => new KeyValuePair<RoslynIntellisenseFilter, int>(a, index)));
			var filters = new List<KeyValuePair<RoslynIntellisenseFilter, int>>(remainingFilters.Count);
			foreach (var item in completionList.Items) {
				if (string.IsNullOrEmpty(item.DisplayText))
					continue;
				for (int i = remainingFilters.Count - 1; i >= 0; i--) {
					var kv = remainingFilters[i];
					foreach (var tag in kv.Key.Tags) {
						if (item.Tags.Contains(tag)) {
							remainingFilters.RemoveAt(i);
							filters.Add(kv);
							break;
						}
					}
				}
				completions.Add(new RoslynCompletion(imageMonikerService, item));
			}
			filters.Sort((a, b) => a.Value - b.Value);
			var completionBuilders = new List<Completion>();
			return new RoslynCompletionSet(mruCompletionService, completionService, textView, moniker, displayName, applicableTo, completions, completionBuilders, filters.Select(a => a.Key).ToArray());
		}
        internal static async Task <(IReadOnlyList <CompletionItem>, bool)> BuildCompletionItemsSync(
            Document document,
            SourceText sourceText,
            long cacheId,
            int position,
            CSharpCompletionService completionService,
            CSharpCompletionList completions,
            TextSpan typedSpan,
            bool expectingImportedItems,
            bool isSuggestionMode)
        {
            var completionsBuilder         = new List <CompletionItem>(completions.Items.Length);
            var seenUnimportedCompletions  = false;
            var commitCharacterRuleCache   = new Dictionary <ImmutableArray <CharacterSetModificationRule>, IReadOnlyList <char> >();
            var commitCharacterRuleBuilder = new HashSet <char>();

            var completionTasksAndProviderNames = completions.Items.SelectAsArray((document, completionService), (completion, arg) =>
            {
                var providerName = completion.GetProviderName();
                if (providerName is TypeImportCompletionProvider or
                    ExtensionMethodImportCompletionProvider)
                {
                    return(null, providerName);
                }
Exemplo n.º 13
0
        public static CompletionRules GetCompletionRules(Document document)
        {
            var rules = InnerCompletionService.GetCompletionRules(document);

            return(new CompletionRules(rules));
        }
Exemplo n.º 14
0
 private static async Task<ImmutableArray<TaggedText>> GetDescriptionAsync(CompletionService completionService, Document document, CompletionItem completionItem)
 {
     return (await Task.Run(async () => await completionService.GetDescriptionAsync(document, completionItem))).TaggedParts;
 }
Exemplo n.º 15
0
 public static Task <bool> IsCompletionTriggerCharacterAsync(Document document, int characterPosition,
                                                             CancellationToken cancellationToken = default(CancellationToken))
 {
     return(InnerCompletionService.IsCompletionTriggerCharacterAsync(document, characterPosition, null, cancellationToken));
 }
Exemplo n.º 16
0
        public static Model CreateModel(
            Document triggerDocument,
            DisconnectedBufferGraph disconnectedBufferGraph,
            CompletionList originalList,
            CompletionItem selectedItem,
            bool isHardSelection,
            bool isUnique,
            bool useSuggestionMode,
            CompletionTrigger trigger,
            CompletionService completionService,
            Workspace workspace)
        {
            ImmutableArray<PresentationItem> totalItems;
            CompletionItem suggestionModeItem = originalList.SuggestionModeItem;
            PresentationItem suggestionModePresentationItem;
            PresentationItem defaultSuggestionModePresentationItem;

            // Get the set of actual filters used by all the completion items 
            // that are in the list.
            var actualFiltersSeen = new HashSet<CompletionItemFilter>();
            foreach (var item in originalList.Items)
            {
                foreach (var filter in CompletionItemFilter.AllFilters)
                {
                    if (filter.Matches(item))
                    {
                        actualFiltersSeen.Add(filter);
                    }
                }
            }

            // The set of filters we'll want to show the user are the filters that are actually
            // used by our completion items.  i.e. there's no reason to show the "field" filter
            // if none of completion items is actually a field.
            var actualItemFilters = CompletionItemFilter.AllFilters.Where(actualFiltersSeen.Contains)
                                                                   .ToImmutableArray();

            // By default we do not filter anything out.
            ImmutableDictionary<CompletionItemFilter, bool> filterState = null;

            if (completionService != null &&
                workspace != null &&
                workspace.Kind != WorkspaceKind.Interactive && // TODO (https://github.com/dotnet/roslyn/issues/5107): support in interactive
                workspace.Options.GetOption(InternalFeatureOnOffOptions.Snippets) &&
                trigger.Kind != CompletionTriggerKind.Snippets)
            {
                // In order to add snippet expansion notes to completion item descriptions, update
                // all of the provided CompletionItems to DescriptionModifyingCompletionItem which will proxy
                // requests to the original completion items and add the snippet expansion note to
                // the description if necessary. We won't do this if the list was triggered to show
                // snippet shortcuts.

                var totalItemsBuilder = ArrayBuilder<PresentationItem>.GetInstance();
                foreach (var item in originalList.Items)
                {
                    totalItemsBuilder.Add(new DescriptionModifyingPresentationItem(item, completionService));
                }

                totalItems = totalItemsBuilder.ToImmutableAndFree();
                defaultSuggestionModePresentationItem = new DescriptionModifyingPresentationItem(
                    CreateDefaultSuggestionModeItem(), completionService, isSuggestionModeItem: true);
                suggestionModePresentationItem = suggestionModeItem != null ? new DescriptionModifyingPresentationItem(suggestionModeItem, completionService, isSuggestionModeItem: true) : null;
            }
            else
            {
                totalItems = originalList.Items.Select(item => new SimplePresentationItem(item, completionService)).ToImmutableArray<PresentationItem>();
                defaultSuggestionModePresentationItem = new SimplePresentationItem(CreateDefaultSuggestionModeItem(), completionService, isSuggestionModeItem: true);
                suggestionModePresentationItem = suggestionModeItem != null ? new SimplePresentationItem(suggestionModeItem, completionService, isSuggestionModeItem: true) : null;
            }

            var selectedPresentationItem = totalItems.FirstOrDefault(it => it.Item == selectedItem);

            return new Model(
                triggerDocument,
                disconnectedBufferGraph,
                originalList,
                totalItems,
                totalItems,
                selectedPresentationItem,
                actualItemFilters,
                filterState,
                "",
                isHardSelection,
                isUnique,
                useSuggestionMode,
                suggestionModePresentationItem,
                defaultSuggestionModePresentationItem,
                trigger,
                GetDefaultTrackingSpanEnd(originalList.Span, disconnectedBufferGraph),
                originalList.Rules.DismissIfEmpty);
        }
 private async Task<CompletionList> GetCompletionListAsync(CompletionService completionService, CompletionTrigger trigger, CancellationToken cancellationToken)
 {
     return _documentOpt != null
         ? await completionService.GetCompletionsAsync(_documentOpt, _subjectBufferCaretPosition, trigger, _roles, _options, cancellationToken).ConfigureAwait(false)
         : null;
 }
Exemplo n.º 18
0
 protected CompletionHelper(CompletionService completionService)
 {
     CompletionService = completionService;
     _language = CompletionService.Language;
     _rules = CompletionService.GetRules();
 }
Exemplo n.º 19
0
 public static CompletionHelper GetHelper(Document document, CompletionService service)
 {
     return GetHelper(document.Project.Solution.Workspace, document.Project.Language, service);
 }
Exemplo n.º 20
0
		CompletionInfo(CompletionService completionService, Document document, SourceText sourceText, ITextSnapshot snapshot) {
			CompletionService = completionService;
			Document = document;
			SourceText = sourceText;
			Snapshot = snapshot;
		}
        public async Task <IEnumerable <AutoCompleteResponse> > Handle(AutoCompleteRequest request)
        {
            var documents      = _workspace.GetDocuments(request.FileName);
            var wordToComplete = request.WordToComplete;
            var completions    = new HashSet <AutoCompleteResponse>();

            foreach (var document in documents)
            {
                var sourceText = await document.GetTextAsync();

                var position       = sourceText.GetTextPosition(request);
                var service        = CompletionService.GetService(document);
                var completionList = await service.GetCompletionsAsync(document, position);

                if (completionList != null)
                {
                    // Only trigger on space if Roslyn has object creation items
                    if (request.TriggerCharacter == " " && !completionList.Items.Any(i => i.GetProviderName() is CompletionListBuilder.ObjectCreationCompletionProvider))
                    {
                        return(completions);
                    }

                    // get recommended symbols to match them up later with SymbolCompletionProvider
                    var semanticModel = await document.GetSemanticModelAsync();

                    var recommendedSymbols = (await Recommender.GetRecommendedSymbolsAtPositionAsync(semanticModel, position, _workspace)).ToArray();

                    var isSuggestionMode = completionList.SuggestionModeItem != null;
                    foreach (var item in completionList.Items)
                    {
                        var completionText = item.DisplayText;
                        var preselect      = item.Rules.MatchPriority == MatchPriority.Preselect;
                        if (completionText.IsValidCompletionFor(wordToComplete))
                        {
                            var symbols = await item.GetCompletionSymbolsAsync(recommendedSymbols, document);

                            if (symbols.Any())
                            {
                                foreach (var symbol in symbols)
                                {
                                    if (item.UseDisplayTextAsCompletionText())
                                    {
                                        completionText = item.DisplayText;
                                    }
                                    else if (item.TryGetInsertionText(out var insertionText))
                                    {
                                        completionText = insertionText;
                                    }
                                    else
                                    {
                                        completionText = symbol.Name;
                                    }

                                    if (symbol != null)
                                    {
                                        if (request.WantSnippet)
                                        {
                                            foreach (var completion in MakeSnippetedResponses(request, symbol, completionText, preselect, isSuggestionMode))
                                            {
                                                completions.Add(completion);
                                            }
                                        }
                                        else
                                        {
                                            completions.Add(MakeAutoCompleteResponse(request, symbol, completionText, preselect, isSuggestionMode));
                                        }
                                    }
                                }

                                // if we had any symbols from the completion, we can continue, otherwise it means
                                // the completion didn't have an associated symbol so we'll add it manually
                                continue;
                            }

                            // for other completions, i.e. keywords or em, create a simple AutoCompleteResponse
                            var response = item.ToAutoCompleteResponse(request.WantKind, isSuggestionMode, preselect);
                            completions.Add(response);
                        }
                    }
                }
            }

            return(completions
                   .OrderByDescending(c => c.CompletionText.IsValidCompletionStartsWithExactCase(wordToComplete))
                   .ThenByDescending(c => c.CompletionText.IsValidCompletionStartsWithIgnoreCase(wordToComplete))
                   .ThenByDescending(c => c.CompletionText.IsCamelCaseMatch(wordToComplete))
                   .ThenByDescending(c => c.CompletionText.IsSubsequenceMatch(wordToComplete))
                   .ThenBy(c => c.DisplayText, StringComparer.OrdinalIgnoreCase)
                   .ThenBy(c => c.CompletionText, StringComparer.OrdinalIgnoreCase));
        }
Exemplo n.º 22
0
 public abstract CompletionHelper CreateCompletionHelper(CompletionService completionService);
Exemplo n.º 23
-1
        public static async Task<TextChange> GetTextChangeAsync(
            CompletionService service, Document document, CompletionItem item, 
            char? commitKey = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var change = await service.GetChangeAsync(document, item, commitKey, cancellationToken).ConfigureAwait(false);

            // normally the items that produce multiple changes are not expecting to trigger the behaviors that rely on looking at the text
            if (change.TextChanges.Length == 1)
            {
                return change.TextChanges[0];
            }
            else
            {
                return new TextChange(item.Span, item.DisplayText);
            }
        }
        internal static async Task <(IReadOnlyList <CompletionItem>, bool)> BuildCompletionItemsAsync(
            Document document,
            SourceText sourceText,
            long cacheId,
            int position,
            CSharpCompletionService completionService,
            CSharpCompletionList completions,
            TextSpan typedSpan,
            bool expectingImportedItems, bool isSuggestionMode)
        {
            var completionsBuilder            = new List <CompletionItem>(completions.Items.Length);
            var seenUnimportedCompletions     = false;
            var commitCharacterRuleCache      = new Dictionary <ImmutableArray <CharacterSetModificationRule>, IReadOnlyList <char> >();
            var commitCharacterRuleBuilder    = new HashSet <char>();
            var isOverrideOrPartialCompletion = completions.Items.Length > 0 &&
                                                completions.Items[0].GetProviderName() is OverrideCompletionProvider or PartialMethodCompletionProvider;

            for (int i = 0; i < completions.Items.Length; i++)
            {
                var    completion = completions.Items[i];
                string labelText  = completion.DisplayTextPrefix + completion.DisplayText + completion.DisplayTextSuffix;
                string?insertText;
                string?filterText = null;
                List <LinePositionSpanTextChange>?additionalTextEdits = null;
                InsertTextFormat insertTextFormat = InsertTextFormat.PlainText;
                TextSpan         changeSpan;
                string?          sortText;
                bool             hasAfterInsertStep = false;
                if (completion.IsComplexTextEdit)
                {
                    // The completion is somehow expensive. Currently, this one of two categories: import completion, or override/partial
                    // completion.
                    Debug.Assert(completion.GetProviderName() is OverrideCompletionProvider or PartialMethodCompletionProvider
                                 or TypeImportCompletionProvider or ExtensionMethodImportCompletionProvider);

                    changeSpan = typedSpan;

                    if (isOverrideOrPartialCompletion)
                    {
                        // For override and partial completion, we don't want to use the DisplayText as the insert text because they contain
                        // characters that will affect our ability to asynchronously resolve the change later.
                        insertText         = completion.FilterText;
                        sortText           = GetSortText(completion, labelText, expectingImportedItems);
                        hasAfterInsertStep = true;
                    }
                    else
                    {
                        insertText = completion.DisplayText;
                        sortText   = '1' + completion.SortText;
                        seenUnimportedCompletions = true;
                    }
                }
                else
                {
                    // For non-complex completions, just await the text edit. It's cheap enough that it doesn't impact our ability
                    // to pop completions quickly

                    // If the completion item is the misc project name, skip it.
                    if (completion.DisplayText == Configuration.OmniSharpMiscProjectName)
                    {
                        continue;
                    }

                    GetCompletionInfo(
                        sourceText,
                        position,
                        completion,
                        await completionService.GetChangeAsync(document, completion),
                        typedSpan,
                        labelText,
                        expectingImportedItems,
                        out insertText, out filterText, out sortText, out insertTextFormat, out changeSpan, out additionalTextEdits);
                }

                var commitCharacters = BuildCommitCharacters(completion.Rules.CommitCharacterRules, isSuggestionMode, commitCharacterRuleCache, commitCharacterRuleBuilder);

                completionsBuilder.Add(new CompletionItem
                {
                    Label               = labelText,
                    TextEdit            = GetChangeForTextAndSpan(insertText !, changeSpan, sourceText),
                    InsertTextFormat    = insertTextFormat,
                    AdditionalTextEdits = additionalTextEdits,
                    SortText            = sortText,
                    FilterText          = filterText,
                    Kind               = GetCompletionItemKind(completion.Tags),
                    Detail             = completion.InlineDescription,
                    Data               = (cacheId, i),
                    Preselect          = completion.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection,
                    CommitCharacters   = commitCharacters,
                    HasAfterInsertStep = hasAfterInsertStep,
                });