public FrameworkElement Create(CompletionSet completionSet, Completion completion, CompletionClassifierKind kind, bool colorize) {
			if (completionSet == null)
				throw new ArgumentNullException(nameof(completionSet));
			if (completion == null)
				throw new ArgumentNullException(nameof(completion));
			Debug.Assert(completionSet.Completions.Contains(completion));

			CompletionClassifierContext context;
			string defaultContentType;
			switch (kind) {
			case CompletionClassifierKind.DisplayText:
				var inputText = completionSet.ApplicableTo.GetText(completionSet.ApplicableTo.TextBuffer.CurrentSnapshot);
				context = new CompletionDisplayTextClassifierContext(completionSet, completion, completion.DisplayText, inputText, colorize);
				defaultContentType = ContentTypes.CompletionDisplayText;
				break;

			case CompletionClassifierKind.Suffix:
				var suffix = (completion as Completion4)?.Suffix ?? string.Empty;
				context = new CompletionSuffixClassifierContext(completionSet, completion, suffix, colorize);
				defaultContentType = ContentTypes.CompletionSuffix;
				break;

			default:
				throw new ArgumentOutOfRangeException(nameof(kind));
			}

			var contentType = (completionSet as ICompletionSetContentTypeProvider)?.GetContentType(contentTypeRegistryService, kind);
			if (contentType == null)
				contentType = contentTypeRegistryService.GetContentType(defaultContentType);
			var classifier = GetTextClassifier(contentType);
			return TextBlockFactory.Create(context.Text, classificationFormatMap.DefaultTextProperties,
				classifier.GetTags(context).Select(a => new TextRunPropertiesAndSpan(a.Span, classificationFormatMap.GetTextProperties(a.ClassificationType))), TextBlockFactory.Flags.DisableSetTextBlockFontFamily | TextBlockFactory.Flags.DisableFontSize);
		}
Ejemplo n.º 2
0
 private static List<Completion> GetCombinedSortedList(CompletionSet sparkCompletions, CompletionSet allCompletionsSet)
 {
     var combinedList = new List<Completion>();
     combinedList.AddRange(allCompletionsSet.Completions);
     combinedList.AddRange(sparkCompletions.Completions);
     return combinedList.SortAlphabetically();
 }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            int triggerPointPosition = session.GetTriggerPoint(session.TextView.TextBuffer).GetPosition(session.TextView.TextSnapshot);
            ITrackingSpan trackingSpan = session.TextView.TextSnapshot.CreateTrackingSpan(triggerPointPosition, 0, SpanTrackingMode.EdgeInclusive);

            var rewriteDirectives = new[] {
                new ApacheCompletion("RewriteBase", "RewriteBase", "The RewriteBase directive explicitly sets the base URL for per-directory rewrites."),
                new ApacheCompletion("RewriteCond", "RewriteCond", "The RewriteCond directive defines a rule condition. One or more RewriteCond can precede a RewriteRule directive."),
                new ApacheCompletion("RewriteEngine", "RewriteEngine", "The RewriteEngine directive enables or disables the runtime rewriting engine."),
                new ApacheCompletion("RewriteLock", "RewriteLock", "This directive sets the filename for a synchronization lockfile which mod_rewrite needs to communicate with RewriteMap programs."),
                new ApacheCompletion("RewriteLog", "RewriteLog", "The RewriteLog directive sets the name of the file to which the server logs any rewriting actions it performs."),
                new ApacheCompletion("RewriteLogLevel", "RewriteLogLevel", "The RewriteLogLevel directive sets the verbosity level of the rewriting logfile."),
                new ApacheCompletion("RewriteMap", "RewriteMap", "The RewriteMap directive defines a Rewriting Map which can be used inside rule substitution strings by the mapping-functions to insert/substitute fields through a key lookup."),
                new ApacheCompletion("RewriteOptions", "RewriteOptions", "The RewriteOptions directive sets some special options for the current per-server or per-directory configuration."),
                new ApacheCompletion("RewriteRule", "RewriteRule", "The RewriteRule directive is the real rewriting workhorse. The directive can occur more than once, with each instance defining a single rewrite rule. The order in which these rules are defined is important - this is the order in which they will be applied at run-time.")
            };

            var completionSet = new CompletionSet(
                ApacheContentType.Name,
                "Apache Rewrite Directives",
                trackingSpan,
                rewriteDirectives,
                null
            );

            completionSets.Add(completionSet);
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if ( !settings.TextCompletionEnabled ) {
            return;
              }
              if ( session.TextView.TextBuffer != this.theBuffer ) {
            return;
              }
              if ( !PlainTextCompletionContext.IsSet(session) ) {
            return;
              }
              var snapshot = theBuffer.CurrentSnapshot;
              var triggerPoint = session.GetTriggerPoint(snapshot);
              if ( !triggerPoint.HasValue ) {
            return;
              }

              var applicableToSpan = GetApplicableToSpan(triggerPoint.Value);

              var then = this.bufferStatsOnCompletion;
              var now = new BufferStats(snapshot);
              if ( currentCompletions == null || now.SignificantThan(then) ) {
            this.currentCompletions = BuildCompletionsList();
            this.bufferStatsOnCompletion = now;
              }
              var set = new CompletionSet(
            moniker: "plainText",
            displayName: "Text",
            applicableTo: applicableToSpan,
            completions: currentCompletions,
            completionBuilders: null
            );
              completionSets.Add(set);
        }
Ejemplo n.º 5
0
 private static List<Completion> GetCombinedSortedList(CompletionSet sparkCompletions, CompletionSet allCompletionsSet)
 {
     var combinedList = new List<Completion>();
     combinedList.AddRange(allCompletionsSet.Completions);
     combinedList.AddRange(sparkCompletions.Completions);
     combinedList.Sort((a, b) => a.DisplayText.CompareTo(b.DisplayText));
     return combinedList;
 }
Ejemplo n.º 6
0
 void sets_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
     if (e.Action != NotifyCollectionChangedAction.Add) {
         throw new NotImplementedException();
     }
     if (_active == null) {
         _active = _sets[0];
     }
 }
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="completionSet">Completion set</param>
		/// <param name="completion">Completion to classify</param>
		/// <param name="text">Text to classify</param>
		/// <param name="colorize">true if it should be colorized</param>
		protected CompletionClassifierContext(CompletionSet completionSet, Completion completion, string text, bool colorize)
			: base(text, string.Empty, colorize) {
			if (completionSet == null)
				throw new ArgumentNullException(nameof(completionSet));
			if (completion == null)
				throw new ArgumentNullException(nameof(completion));
			CompletionSet = completionSet;
			Completion = completion;
		}
Ejemplo n.º 8
0
 internal WordCompletionSession(ITrackingSpan wordTrackingSpan, IIntellisenseSessionStack intellisenseSessionStack, ICompletionSession completionSession, CompletionSet wordCompletionSet)
 {
     _textView = completionSession.TextView;
     _wordTrackingSpan = wordTrackingSpan;
     _wordCompletionSet = wordCompletionSet;
     _completionSession = completionSession;
     _completionSession.Dismissed += delegate { OnDismissed(); };
     _intellisenseSessionStack = intellisenseSessionStack;
 }
Ejemplo n.º 9
0
 private static bool TryExtractAllCompletionsSet(IList<CompletionSet> completionSets, out CompletionSet allCompletions)
 {
     allCompletions = null;
     foreach (var completionSet in completionSets)
     {
         if (completionSet.DisplayName != "All") continue;
         allCompletions = completionSet;
         return true;
     }
     return false;
 }
Ejemplo n.º 10
0
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (_disposed)
                throw new ObjectDisposedException("LuaCompletionSource");

            ITextSnapshot snapshot = _buffer.CurrentSnapshot;
            var triggerPoint = (SnapshotPoint)session.GetTriggerPoint(snapshot);

            if (triggerPoint == null)
                return;

            var line = triggerPoint.GetContainingLine();
            SnapshotPoint start = triggerPoint;

            var word = start;
            word -= 1;
            var ch = word.GetChar();

            List<Completion> completions = new List<Completion>();

            if (ch == '.' || ch == ':' || ch == '_') //for table search
            {
                while (word > line.Start && Help.is_word_char((word - 1).GetChar()))
                {
                    word -= 1;
                }
                String w = snapshot.GetText(word.Position,start - 1 - word);
                if (ch == '_')
                {
                    if (!FillWord(w+"_",completions))
                        return;
                }
                else
                {
                    if (!FillTable(w,ch,completions))
                        return;
                }
            }
            else
                return;
            if (ch == '_')
            {
                while (start > line.Start && Help.is_word_char((start - 1).GetChar()))
                {
                    start -= 1;
                }
            }
            var applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, triggerPoint), SpanTrackingMode.EdgeInclusive);
            var cs = new CompletionSet("All", "All", applicableTo, completions, null);
            completionSets.Add(cs);
            //session.SelectedCompletionSet = cs;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AugmentedCompletionSet"/> class from the specified
        /// <paramref name="source"/> <see cref="CompletionSet"/> and a second completion set used to augment the
        /// source set.
        /// </summary>
        /// <param name="session">The completion session, or <see langword="null"/> if no completion session was
        /// provided.</param>
        /// <param name="source">The source completion set.</param>
        /// <param name="secondSource">The second completion set used to augment <paramref name="source"/></param>
        /// <exception cref="ArgumentNullException">If <paramref name="source"/> is <see langword="null"/>.
        /// <para>-or-</para>
        /// <para>If <paramref name="secondSource"/> is <see langword="null"/>.</para>
        /// </exception>
        public AugmentedCompletionSet(ICompletionSession session, CompletionSet source, CompletionSet secondSource) :
            base(source.Moniker, source.DisplayName, source.ApplicableTo, source.Completions, source.CompletionBuilders)
        {
            if(source == null)
                throw new ArgumentNullException("source");

            if(secondSource == null)
                throw new ArgumentNullException("secondSource");

            _session = session;
            _source = source;
            _secondSource = secondSource;
            UpdateCompletionLists();
        }
Ejemplo n.º 12
0
        private static void MergeSparkWithAllCompletionsSet(IList<CompletionSet> completionSets, CompletionSet sparkCompletions)
        {
            CompletionSet allCompletionsSet;
            if (!TryExtractAllCompletionsSet(completionSets, out allCompletionsSet)) return;

            var mergedCompletionSet = new CompletionSet(
                                allCompletionsSet.Moniker,
                                allCompletionsSet.DisplayName,
                                allCompletionsSet.ApplicableTo,
                                GetCombinedSortedList(sparkCompletions, allCompletionsSet),
                                allCompletionsSet.CompletionBuilders);

            completionSets.Remove(allCompletionsSet);
            completionSets.Add(mergedCompletionSet);
        }
Ejemplo n.º 13
0
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            Debug.Assert(session != null, "session");
            Debug.Assert(completionSets != null, "completionSets");

            TemplateAnalysis current = this.analyzer.CurrentAnalysis;
            var builder = new TemplateCompletionBuilder(session.GetTriggerPoint(current.TextSnapshot).Value.Position);
            builder.Visit(current.Template);
            if (builder.Completions != null)
            {
                ITrackingSpan applicableTo = current.TextSnapshot.CreateTrackingSpan(builder.Node.Span, SpanTrackingMode.EdgeInclusive);
                IEnumerable<Completion> completions = builder.Completions.OrderBy(completion => completion.DisplayText);
                var completionSet = new CompletionSet("All", "All", applicableTo, completions, null);
                completionSets.Add(completionSet);
            }
        }
Ejemplo n.º 14
0
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            var triggerPoint = session.GetTriggerPoint(buffer.CurrentSnapshot);
            if (triggerPoint == null)
                return;

            ITextDocument doc;
            if (!textDocumentFactory.TryGetTextDocument(buffer, out doc))
                return;

            var applicableTo = buffer.CurrentSnapshot.CreateTrackingSpan(new SnapshotSpan(triggerPoint.Value, 1), SpanTrackingMode.EdgeInclusive);

            var completions = new ObservableCollection<Completion>();
            completions.Add(new Completion("Hard-coded..."));

            var completionSet = new CompletionSet("All", "All", applicableTo, Enumerable.Empty<Completion>(), completions);
            completionSets.Add(completionSet);

            Task.Run(async () =>
            {
                await Task.Delay(1000); // Wait 1s
                completions.Add(new Completion("Danny"));
            });

            //// Kick of async request to update the results.
            //analysisService
            //	.GetSuggestions(doc.FilePath, triggerPoint.Value.Position)
            //	.ContinueWith(completion =>
            //	{
            //		var completionID = completion.Result;
            //		IDisposable subscription = null;
            //		subscription = analysisService
            //			.CompletionResultsNotification
            //			.Where(c => c.Id == completionID)
            //			.Subscribe(c => UpdateCompletionResults(subscription, completions, c));
            //	});
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AugmentedCompletionSet"/> class from the specified
        /// <paramref name="source"/> <see cref="CompletionSet"/> and a second completion set used to augment the
        /// source set.
        /// </summary>
        /// <param name="session">The completion session, or <see langword="null"/> if no completion session was
        /// provided.</param>
        /// <param name="source">The source completion set.</param>
        /// <param name="secondSource">The second completion set used to augment <paramref name="source"/></param>
        /// <exception cref="ArgumentNullException">If <paramref name="source"/> is <see langword="null"/>.
        /// <para>-or-</para>
        /// <para>If <paramref name="secondSource"/> is <see langword="null"/>.</para>
        /// </exception>
        public AugmentedCompletionSet(ICompletionSession session, CompletionSet source, CompletionSet secondSource) :
            base(source.Moniker, source.DisplayName, source.ApplicableTo, source.Completions, source.CompletionBuilders)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (secondSource == null)
            {
                throw new ArgumentNullException("secondSource");
            }

            _session      = session;
            _source       = source;
            _secondSource = secondSource;
            UpdateCompletionLists();
        }
Ejemplo n.º 16
0
        public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("LuaCompletionSource");
            }

            ITextSnapshot snapshot     = _buffer.CurrentSnapshot;
            var           triggerPoint = (SnapshotPoint)session.GetTriggerPoint(snapshot);

            if (triggerPoint == null)
            {
                return;
            }

            var           line  = triggerPoint.GetContainingLine();
            SnapshotPoint start = triggerPoint;

            var word = start;

            word -= 1;
            var ch = word.GetChar();

            List <Completion> completions = new List <Completion>();

            if (ch == '.' || ch == ':' || ch == '_') //for table search
            {
                while (word > line.Start && Help.is_word_char((word - 1).GetChar()))
                {
                    word -= 1;
                }
                String w = snapshot.GetText(word.Position, start - 1 - word);
                if (ch == '_')
                {
                    if (!FillWord(w + "_", completions))
                    {
                        return;
                    }
                }
                else
                {
                    if (!FillTable(w, ch, completions))
                    {
                        return;
                    }
                }
            }
            else
            {
                return;
            }
            if (ch == '_')
            {
                while (start > line.Start && Help.is_word_char((start - 1).GetChar()))
                {
                    start -= 1;
                }
            }
            var applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, triggerPoint), SpanTrackingMode.EdgeInclusive);
            var cs           = new CompletionSet("All", "All", applicableTo, completions, null);

            completionSets.Add(cs);
            //session.SelectedCompletionSet = cs;
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="completionSet">Completion set</param>
 /// <param name="completion">Completion to classify</param>
 /// <param name="displayText">Text to classify</param>
 /// <param name="inputText">Current user input text</param>
 /// <param name="colorize">true if it should be colorized</param>
 public CompletionDisplayTextClassifierContext(CompletionSet completionSet, Completion completion, string displayText, string inputText, bool colorize)
     : base(completionSet, completion, displayText, colorize) => InputText = inputText ?? throw new ArgumentNullException(nameof(inputText));
Ejemplo n.º 18
0
 public void UpdateCompletions(int position)
 {
     CompletionSet = _engine.GetCompletions(Metadata, Text, position, _currentAssemblyName);
 }
Ejemplo n.º 19
0
        protected override IEnumerable <JsonCompletionEntry> GetEntries(JsonCompletionContext context)
        {
            var member = context.ContextNode as MemberNode;

            if (member == null || member.UnquotedNameText != ManifestConstants.Library)
            {
                yield break;
            }

            var parent = member.Parent as ObjectNode;

            if (!JsonHelpers.TryGetInstallationState(parent, out ILibraryInstallationState state))
            {
                yield break;
            }

            var             dependencies = Dependencies.FromConfigFile(ConfigFilePath);
            IProvider       provider     = dependencies.GetProvider(state.ProviderId);
            ILibraryCatalog catalog      = provider?.GetCatalog();

            if (catalog == null)
            {
                yield break;
            }

            // member.Value is null when there is no value yet, e.g. when typing a space at "library":|
            // where | represents caret position. In this case, set caretPosition to "1" to short circuit execution of this function
            // and return no entries (member.UnquotedValueText will be empty string in that case).
            int caretPosition = member.Value != null ? context.Session.TextView.Caret.Position.BufferPosition - member.Value.Start - 1 : 1;

            if (caretPosition > member.UnquotedValueText.Length)
            {
                yield break;
            }

            Task <CompletionSet> task = catalog.GetLibraryCompletionSetAsync(member.UnquotedValueText, caretPosition);
            int count = 0;

            if (!context.Session.Properties.ContainsProperty(CompletionController.RetriggerCompletion))
            {
                context.Session.Properties.AddProperty(CompletionController.RetriggerCompletion, true);
            }

            if (task.IsCompleted)
            {
                CompletionSet completionSet = task.Result;

                if (completionSet.Completions != null)
                {
                    List <JsonCompletionEntry> results = GetCompletionList(member, context, completionSet, count);

                    foreach (JsonCompletionEntry completionEntry in results)
                    {
                        yield return(completionEntry);
                    }
                }
            }
            else
            {
                yield return(new SimpleCompletionEntry(Resources.Text.Loading, string.Empty, KnownMonikers.Loading, context.Session));

                task.ContinueWith((a) =>
                {
                    if (!context.Session.IsDismissed)
                    {
                        CompletionSet completionSet = task.Result;

                        if (completionSet.Completions != null)
                        {
                            List <JsonCompletionEntry> results = GetCompletionList(member, context, completionSet, count);

                            UpdateListEntriesSync(context, results);
                        }
                    }
                });
            }
        }
Ejemplo n.º 20
0
        public override CompletionSet GetCompletions(IGlyphService glyphService) {
            var start = _stopwatch.ElapsedMilliseconds;

            var line = Span.GetStartPoint(TextBuffer.CurrentSnapshot).GetContainingLine();
            var startPos = line.Start.Position + line.GetText().IndexOf("def");

            var analysis = GetAnalysisEntry();
            if (analysis == null) {
                return null;
            }

            var span = Span.GetSpan(TextBuffer.CurrentSnapshot);
            int defIndent = span.Start.GetContainingLine().GetText().IndexOf("def");

            string indentation;
            if (_options.ConvertTabsToSpaces) {
                indentation = new string(' ', defIndent + _options.IndentSize);
            } else {
                indentation = new string('\t', defIndent / 8 + 1);
            }

            var snapshot = TextBuffer.CurrentSnapshot;
            var pos = VsProjectAnalyzer.TranslateIndex(startPos, snapshot, analysis);

            var completions = analysis.Analyzer.WaitForRequest(analysis.Analyzer.GetOverrideCompletionsAsync(
                analysis,
                TextBuffer,
                pos,
                indentation
            ), "OverrideCompletionAnalysis.GetOverrideCompletions")?.overrides;

            CompletionSet res;
            if (completions != null && completions.Any()) {
                var set = new FuzzyCompletionSet(
                    "PythonOverrides",
                    "Python",
                    Span,
                    completions.Select(
                        x => PythonCompletion(
                            glyphService,
                            x.name,
                            x.completion,
                            x.doc,
                            StandardGlyphGroup.GlyphGroupOverload
                        )
                    ).ToArray(),
                    _options,
                    CompletionComparer.UnderscoresLast
                );
                set.CommitByDefault = false;
                res = set;
            } else {
                res = new CompletionSet();
            }

            var end = _stopwatch.ElapsedMilliseconds;

            if (/*Logging &&*/ end - start > TooMuchTime) {
                Trace.WriteLine(String.Format("{0} lookup time {1} for {2} classes", this, end - start, res.Completions.Count));
            }

            return res;
        }
        void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            ITextSnapshot snapshot = textBuffer.CurrentSnapshot;
            SnapshotPoint? triggerPoint = session.GetTriggerPoint(snapshot);
            if (triggerPoint == null)
            {
                return;
            }
            SnapshotPoint end = triggerPoint.Value;
            SnapshotPoint start = end;
            // go back to either a delimiter, a whitespace char or start of line.
            while (start > 0)
            {
                SnapshotPoint prev = start - 1;
                if (IsWhiteSpaceOrDelimiter(prev.GetChar()))
                {
                    break;
                }
                start += -1;
            }

            var span = new SnapshotSpan(start, end);
            // The ApplicableTo span is what text will be replaced by the completion item
            ITrackingSpan applicableTo1 = snapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeInclusive);

            String statement = applicableTo1.GetText(applicableTo1.TextBuffer.CurrentSnapshot);

            AutocompleteService autocomplteService = AutocompleteClient.GetAutocompleteService();
            IEnumerable<StatementCompletion> completions = new List<StatementCompletion>();
            if (autocomplteService != null)
            {
                try
                {
                    completions = autocomplteService.GetCompletions(statement, intellisenseProviderType);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            }

            compList = new List<Completion>();
            bool prependDot = statement.EndsWith(".");

            foreach (StatementCompletion completion in completions)
            {
                //StatementCompletion completion = StatementCompletion.FromTuple(tuple.Item1, tuple.Item2);
                string str = completion.Text;
                var glyph = sourceProvider.GlyphService.GetGlyph(CompletionTypeToStandardGlyphGroup(completion.CompletionType),
                    StandardGlyphItem.GlyphItemPublic);
                compList.Add(new Completion(str, prependDot ? "." + str : str, str, glyph, null));
            }

            var applicableTo = FindTokenSpanAtPosition(session.GetTriggerPoint(textBuffer),
                    session);

            CompletionSet completionSet = new CompletionSet(
                "F# completions",    //the non-localized title of the tab 
                "F# completions",    //the display title of the tab
                applicableTo,
                compList,
                null);

            // Following code doesn't work:
            //ExposedObject.From(completionSet)._filterMatchType =
            //    Microsoft.VisualStudio.Language.Intellisense.CompletionMatchType.MatchInsertionText;

            completionSets.Add(completionSet);
        }
Ejemplo n.º 22
0
        public async Task <CompletionSet> GetLibraryCompletionSetAsync(string value, int caretPosition)
        {
            if (!await EnsureCatalogAsync(CancellationToken.None).ConfigureAwait(false))
            {
                return(default(CompletionSet));
            }

            var span = new CompletionSet
            {
                Start  = 0,
                Length = value.Length
            };

            int    at   = value.IndexOf('@');
            string name = at > -1 ? value.Substring(0, at) : value;

            var completions = new List <CompletionItem>();

            // Name
            if (at == -1 || caretPosition <= at)
            {
                IReadOnlyList <ILibraryGroup> result = await SearchAsync(name, int.MaxValue, CancellationToken.None).ConfigureAwait(false);

                foreach (CdnjsLibraryGroup group in result)
                {
                    var completion = new CompletionItem
                    {
                        DisplayText   = AliasedName(group.DisplayName),
                        InsertionText = group.DisplayName + "@" + group.Version,
                        Description   = group.Description,
                    };

                    completions.Add(completion);
                }
            }

            // Version
            else
            {
                CdnjsLibraryGroup group = _libraryGroups.FirstOrDefault(g => g.DisplayName == name);

                if (group != null)
                {
                    span.Start  = at + 1;
                    span.Length = value.Length - span.Start;

                    IEnumerable <Asset> assets = await GetAssetsAsync(name, CancellationToken.None).ConfigureAwait(false);

                    foreach (string version in assets.Select(a => a.Version))
                    {
                        var completion = new CompletionItem
                        {
                            DisplayText   = version,
                            InsertionText = $"{name}@{version}",
                        };

                        completions.Add(completion);
                    }
                }
            }

            span.Completions = completions;

            return(span);
        }
Ejemplo n.º 23
0
        void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            if (completionSets.Count != 0)
            {
                //                 completionSets.Clear();
                //                 session.Dismiss();
                //此处为XML激活的自动完成比如输入 <时
                return;
            }
            if (m_xmlType == XML_TYPE.Unknow)
            {
            }
            SnapshotPoint?currentPoint = session.GetTriggerPoint(m_textBuffer.CurrentSnapshot); // (session.TextView.Caret.Position.BufferPosition);

            if (!currentPoint.HasValue)
            {
                return;
            }
            ITextSnapshotLine       TextSnapshotLine = session.TextView.TextSnapshot.GetLineFromPosition(currentPoint.Value);
            ITextStructureNavigator navigator        = m_sourceProvider.NavigatorService.GetTextStructureNavigator(m_textBuffer);
            string        xmlText   = TextSnapshotLine.GetText();
            SnapshotPoint linestart = TextSnapshotLine.Start;

            xmlText = xmlText.Substring(0, currentPoint.Value - linestart.Position);
            //向前查找 <或>或者空格
            //string xmlText= m_textBuffer.CurrentSnapshot.GetText();
            int pos1 = xmlText.LastIndexOf("<");
            int pos2 = xmlText.LastIndexOf(" ");
            int pos3 = xmlText.LastIndexOf(">");
            int pos4 = xmlText.LastIndexOf("=");

            if (pos3 > pos1)
            {
                return;//标签已关闭
            }
            if (pos1 > pos2)
            {
                SouiData.GetInstance().GetMap(m_xmlType, out m_compList, SouiData.MAPTYPE.C, m_sourceProvider.GlyphService);
                var set = new CompletionSet(
                    "SOUI",
                    "SOUI",
                    FindTokenSpanAtPosition(session.GetTriggerPoint(m_textBuffer), session),
                    m_compList,
                    null);
                //                 if(completionSets.Count>0)
                //                 {
                //                     completionSets.Clear();
                //                 }
                completionSets.Add(set);
            }
            else if (pos4 > pos2)
            {
                string key = "";
                if (pos1 > pos3)
                {
                    if (xmlText[pos1 + 1] != '/')             //闭合节点
                    {
                        int pos = xmlText.IndexOf(" ", pos1); //<0123 56
                        ++pos1;
                        key = xmlText.Substring(pos1, pos - pos1);
                    }
                }
                //控件名
                if (key.Length != 0)
                {
                    //属性名
                    string pro = "";
                    xmlText.IndexOf(" ", pos1);//<0123 56
                    int pos = xmlText.LastIndexOf(" ", pos4);
                    ++pos;
                    pro = xmlText.Substring(pos, pos4 - pos);
                    if (pro.Length != 0)
                    {
                        SouiData.GetInstance().GetMap(m_xmlType, out m_compList, m_sourceProvider.GlyphService, key, pro);
                        var set = new CompletionSet(
                            "SOUI",
                            "SOUI",
                            FindTokenSpanAtPosition(session.GetTriggerPoint(m_textBuffer), session),
                            m_compList,
                            null);
                        if (completionSets.Count > 0)
                        {
                            completionSets.Clear();
                        }
                        completionSets.Add(set);
                    }
                }
            }
            else
            {
                string key = "";
                if (pos1 > pos3)
                {
                    if (xmlText[pos1 + 1] != '/')             //闭合节点
                    {
                        int pos = xmlText.IndexOf(" ", pos1); //<0123 56
                        ++pos1;
                        key = xmlText.Substring(pos1, pos - pos1);
                    }
                }
                if (key.Length != 0)
                {
                    SouiData.GetInstance().GetMap(m_xmlType, out m_compList, SouiData.MAPTYPE.P, m_sourceProvider.GlyphService, key);
                    var set = new CompletionSet(
                        "SOUI",
                        "SOUI",
                        FindTokenSpanAtPosition(session.GetTriggerPoint(m_textBuffer), session),
                        m_compList,
                        null);
                    if (completionSets.Count > 0)
                    {
                        completionSets.Clear();
                    }
                    completionSets.Add(set);
                }
            }
        }
 private bool IsPrefixMatch(CompletionSet selectedCompletionSet)
 {
     return(selectedCompletionSet is CustomCompletionSet &&
            ((CustomCompletionSet)selectedCompletionSet).PrefixMatch);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="completionSet">Completion set</param>
 /// <param name="completion">Completion to classify</param>
 /// <param name="text">Text to classify</param>
 /// <param name="colorize">true if it should be colorized</param>
 protected CompletionClassifierContext(CompletionSet completionSet, Completion completion, string text, bool colorize)
     : base(text, string.Empty, colorize)
 {
     CompletionSet = completionSet ?? throw new ArgumentNullException(nameof(completionSet));
     Completion    = completion ?? throw new ArgumentNullException(nameof(completion));
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Should this key commit a completion session?
        /// </summary>
        public override bool IsCommitChar(char typedChar)
        {
            if (HasActiveCompletionSession && typedChar != 0)
            {
                // only ( completes keywords
                CompletionSet completionSet  = CompletionSession.SelectedCompletionSet;
                string        completionText = completionSet.SelectionStatus.Completion.InsertionText;

                if (completionText == "else" || completionText == "repeat")
                {
                    // { after 'else' or 'repeat' completes keyword
                    if (typedChar == '{')
                    {
                        return(true);
                    }

                    // Space completes if selection is unique
                    if (char.IsWhiteSpace(typedChar) && completionSet.SelectionStatus.IsUnique)
                    {
                        return(true);
                    }

                    return(false);
                }

                // ';' completes after next or break keyword
                if (completionText == "break" || completionText == "next")
                {
                    if (typedChar == ';')
                    {
                        return(true);
                    }

                    // Space completes if selection is unique
                    if (char.IsWhiteSpace(typedChar) && completionSet.SelectionStatus.IsUnique)
                    {
                        return(true);
                    }
                }

                // Handle ( after keyword that is usually followed by expression in braces
                // such as for(), if(), library(), ...
                if (completionText == "if" || completionText == "for" || completionText == "while" ||
                    completionText == "return" || completionText == "library" || completionText == "require")
                {
                    return(typedChar == '(' || typedChar == '\t' || (char.IsWhiteSpace(typedChar) && completionSet.SelectionStatus.IsUnique));
                }

                switch (typedChar)
                {
                case '<':
                case '>':
                case '+':
                case '-':
                case '*':
                case '^':
                case '=':
                case '%':
                case '|':
                case '&':
                case '!':
                case ':':
                case '@':
                case '$':
                case '(':
                case '[':
                case '{':
                case ')':
                case ']':
                case '}':
                case ';':
                    return(completionSet.SelectionStatus.IsUnique);
                }

                if (typedChar == ' ' && !REditorSettings.CommitOnSpace)
                {
                    return(false);
                }

                if (char.IsWhiteSpace(typedChar))
                {
                    if (typedChar.IsLineBreak())
                    {
                        if (REditorSettings.CommitOnEnter)
                        {
                            return(true);
                        }

                        return(!IsAutoShownCompletion());
                    }
                    return(true);
                }
            }

            return(false);
        }
        /// <inheritdoc />
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            // The IntelliSense calculation within comments is rather simple. To detect when the completion is
            // currently located within an XML documentation comment, the following "tricks" are used.
            // 
            // 1. The filtering algorithm in use never removes "!--" (indicating an XML comment) from the
            //    completion set, so it is always listed when completion is invoked.  In addition, the sorting
            //    algorithm always places this item first in the completion set.
            // 2. Since this particular tag is not valid elsewhere in C#, it is easily used to determine when the
            //    caret is inside an XML documentation comment.
            if(completionSets.Count == 0 || completionSets[0].Completions.Count == 0 ||
              completionSets[0].Completions[0].DisplayText != "!--")
            {
                // Not inside a documentation comment, so leave things alone
                return;
            }

            // Next, we need to determine if the user pressed "<" or simply pressed Ctrl+Space to invoke code
            // completion.  Since the C# IntelliSense provider doesn't include any existing "<" character in the
            // reported ApplicableTo tracking span, we must insert this character when it's not already present.
            // XML itself makes this easy - the "<" character will either appear immediately before the
            // ApplicableTo span or it will not be present.
            ITextSnapshot snapshot = _textBuffer.CurrentSnapshot;
            SnapshotPoint startPoint = completionSets[0].ApplicableTo.GetStartPoint(snapshot);

            string prefix = String.Empty;

            if(startPoint > 0 && snapshot.GetText(startPoint.Position - 1, 1) != "<")
                prefix = "<";

            // Use the GlyphKeyword glyph for "normal" XML tags, to match the glyphs used by C#
            // for the standard IntelliSense tags. Use the GlyphGroupMacro glyph for other completion
            // items that expand to something other that what the user wrote (e.g. "true" expands to
            // <see langword="true"/> as opposed to <true/>).
            //
            // The descriptions for custom tags is copied from the Sandcastle XML Comments Guide.  Obsolete
            // custom tags are not included.
            var iconSource = _provider.GlyphService.GetGlyph(StandardGlyphGroup.GlyphKeyword,
                StandardGlyphItem.GlyphItemPublic);
            var macroIconSource = _provider.GlyphService.GetGlyph(StandardGlyphGroup.GlyphGroupMacro,
                StandardGlyphItem.GlyphItemPublic);

            // The elements are context sensitive so only show them if applicable based on the elements
            // determined to be valid by the C# IntelliSense provider.
            var allTags = completionSets.SelectMany(c => c.CompletionBuilders).Select(b => b.DisplayText).Concat(
                completionSets.SelectMany(c => c.Completions).Select(c => c.DisplayText)).ToList();

            // Elements allowed anywhere
            var completions = new List<Completion>
            {
                new CustomCompletion(session, "conceptualLink", prefix + "conceptualLink target=\"\xFF\"/>",
                    "This element is used to create a link to a MAML topic within the See Also section of a " +
                    "topic or an inline link to a MAML topic within one of the other XML comments elements.",
                    iconSource, ""),
                new Completion("inheritdoc", prefix + "inheritdoc/>", "This element can help minimize the " +
                    "effort required to document complex APIs by allowing common documentation to be " +
                    "inherited from base types/members.", iconSource, ""),
                new CustomCompletion(session, "inheritdoc cref", prefix + "inheritdoc cref=\"\xFF\"/>",
                    "Inherit documentation from a specific member.", iconSource, ""),
                new CustomCompletion(session, "inheritdoc cref/select", prefix + "inheritdoc cref=\"\xFF\" " +
                    "select=\"summary|remarks\"/>", "Inherit documentation from a specific member and comments.",
                    iconSource, ""),
                new Completion("token", prefix + "token", "This element represents a replaceable tag within " +
                    "a topic.", iconSource, "")
            };

            // General top-level elements
            if(allTags.Contains("exception"))
                completions.AddRange(new[]
                {
                    new Completion("AttachedEventComments", prefix + "AttachedEventComments", "This element " +
                        "is used to define the content that should appear on the auto-generated attached " +
                        "event member topic for a given WPF routed event member.", iconSource, ""),
                    new Completion("AttachedPropertyComments", prefix + "AttachedPropertyComments",
                        "This element is used to define the content that should appear on the auto-generated " +
                        "attached property member topic for a given WPF dependency property member.",
                        iconSource, ""),
                    new CustomCompletion(session, "event", prefix + "event cref=\"\xFF\"",
                        "This element is used to list events that can be raised by a type's member.",
                        iconSource, ""),
                    new Completion("overloads", prefix + "overloads", "This element is used to define the " +
                        "content that should appear on the auto-generated overloads topic for a given set of " +
                        "member overloads.", iconSource, ""),
                    new Completion("preliminary", prefix + "preliminary/>",
                        "This element is used to indicate that a particular type or member is preliminary and " +
                        "is subject to change.", iconSource, ""),
                    new Completion("threadsafety", prefix + "threadsafety static=\"true\" instance=\"false\"/>",
                        "This element is used to indicate whether or not a class or structure's static and " +
                        "instance members are safe for use in multi-threaded scenarios.", iconSource, "")
                });

            // General inline elements
            if(allTags.Contains("list"))
            {
                completions.AddRange(new[]
                {
                    new Completion("note", prefix + "note type=\"note\"", "This element is used to create a " +
                        "note-like section within a topic to draw attention to some important information.",
                        iconSource, "")
                });

                // Language-specific keyword extensions.  The C# provider allows these at any level but
                // Sandcastle only uses them if they are inline.
                completions.AddRange(new[]
                {
                    new Completion("null", prefix + "see langword=\"null\"/>", "Inserts the language-specific " +
                        "keyword 'null'.", macroIconSource, ""),
                    new Completion("static", prefix + "see langword=\"static\"/>", "Inserts the " +
                        "language-specific keyword 'static'.", macroIconSource, ""),
                    new Completion("virtual", prefix + "see langword=\"virtual\"/>", "Inserts the " +
                        "language-specific keyword 'virtual'.", macroIconSource, ""),
                    new Completion("true", prefix + "see langword=\"true\"/>", "Inserts the language-specific " +
                        "keyword 'true'.", macroIconSource, ""),
                    new Completion("false", prefix + "see langword=\"false\"/>", "Inserts the " +
                        "language-specific keyword 'false'.", macroIconSource, ""),
                    new Completion("abstract", prefix + "see langword=\"abstract\"/>", "Inserts the " +
                        "language-specific keyword 'abstract'.", macroIconSource, ""),
                    new Completion("async", prefix + "see langword=\"async\"/>", "Inserts the " +
                        "language-specific keyword 'async'.", macroIconSource, ""),
                    new Completion("await", prefix + "see langword=\"await\"/>", "Inserts the " +
                        "language-specific keyword 'await'.", macroIconSource, ""),
                    new Completion("async/await", prefix + "see langword=\"async/await\"/>", "Inserts the " +
                        "language-specific keyword 'async/await'.", macroIconSource, "")
                });
            }

            // Code element extensions
            if(allTags.Contains("code"))
                completions.AddRange(new[]
                {
                    new CustomCompletion(session, "code import", prefix + "code language=\"\xFF\" title=\" \" " +
                        "source=\"..\\Path\\SourceFile.cs\" region=\"Region Name\"/>", "This element is used " +
                        "to indicate that a multi-line section of text should be imported from the named " +
                        "region of the named file and formatted as a code block.", iconSource, ""),
                    new CustomCompletion(session, "code language", prefix + "code language=\"\xFF\" " +
                        "title=\" \"></code>", "This element is used to indicate that a multi-line section of " +
                        "text should be formatted as a code block.", iconSource, ""),
                });

            // The augmented completion set is created from the previously existing one (created by the C#
            // language service), and a CompletionSet created for the custom XML tags. The moniker and display
            // name for the additional set are not used, since the augmented set always returns the values
            // reported by the original completion set.
            CompletionSet additionalCompletionSet = new CompletionSet("", "", completionSets[0].ApplicableTo,
                completions, Enumerable.Empty<Completion>());

            completionSets[0] = new AugmentedCompletionSet(session, completionSets[0], additionalCompletionSet);
        }
 void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
 {
     try
     {
         if (this.m_isDisposed)
             return;
         SnapshotPoint? triggerPoint = session.GetTriggerPoint(this.m_textBuffer.CurrentSnapshot);
         if (!triggerPoint.HasValue || (this.m_textBuffer.ContentType.TypeName != "C/C++" || !triggerPoint.Value.GetContainingLine().GetText().TrimStart().StartsWith("///")))
             return;
         CompletionSet completionSet = new CompletionSet("TripleSlashCompletionSet", "TripleSlashCompletionSet", this.FindTokenSpanAtPosition(session.GetTriggerPoint(this.m_textBuffer), session), (IEnumerable<Completion>)this.m_compList, Enumerable.Empty<Completion>());
         completionSets.Add(completionSet);
     }
     catch
     {
     }
 }
        protected override IEnumerable <JSONCompletionEntry> GetEntries(JSONCompletionContext context)
        {
            var member = context.ContextItem as JSONMember;

            if (member == null || member.UnquotedNameText != ManifestConstants.Library)
            {
                yield break;
            }

            var parent = member.Parent as JSONObject;

            if (!JsonHelpers.TryGetInstallationState(parent, out ILibraryInstallationState state))
            {
                yield break;
            }

            var             dependencies = Dependencies.FromConfigFile(ConfigFilePath);
            IProvider       provider     = dependencies.GetProvider(state.ProviderId);
            ILibraryCatalog catalog      = provider?.GetCatalog();

            if (catalog == null)
            {
                yield break;
            }

            // member.Value is null when there is no value yet, e.g. when typing a space at "library":|
            // where | represents caret position. In this case, set caretPosition to "1" to short circuit execution of this function
            // and return no entries (member.UnquotedValueText will be empty string in that case).
            int caretPosition = member.Value != null ? context.Session.TextView.Caret.Position.BufferPosition - member.Value.Start - 1 : 1;

            if (caretPosition > member.UnquotedValueText.Length)
            {
                yield break;
            }

            Task <CompletionSet> task = catalog.GetLibraryCompletionSetAsync(member.UnquotedValueText, caretPosition);
            int count = 0;

            if (!context.Session.Properties.ContainsProperty(CompletionController.RetriggerCompletion))
            {
                context.Session.Properties.AddProperty(CompletionController.RetriggerCompletion, true);
            }

            if (task.IsCompleted)
            {
                CompletionSet set          = task.Result;
                int           start        = member.Value.Start;
                ITrackingSpan trackingSpan = context.Snapshot.CreateTrackingSpan(start + 1 + set.Start, set.Length, SpanTrackingMode.EdgeInclusive);

                if (set.Completions != null)
                {
                    foreach (CompletionItem item in set.Completions)
                    {
                        string       insertionText = item.InsertionText.Replace("\\\\", "\\").Replace("\\", "\\\\");
                        ImageMoniker moniker       = item.DisplayText.EndsWith("/") || item.DisplayText.EndsWith("\\") ? _folderIcon : _libraryIcon;
                        yield return(new SimpleCompletionEntry(item.DisplayText, insertionText, item.Description, moniker, trackingSpan, context.Session, ++count));
                    }
                }
            }
            else
            {
                yield return(new SimpleCompletionEntry(Resources.Text.Loading, string.Empty, KnownMonikers.Loading, context.Session));

                task.ContinueWith((a) =>
                {
                    if (!context.Session.IsDismissed)
                    {
                        CompletionSet set          = task.Result;
                        int start                  = member.Value.Start;
                        ITrackingSpan trackingSpan = context.Snapshot.CreateTrackingSpan(start + 1 + set.Start, set.Length, SpanTrackingMode.EdgeExclusive);

                        if (set.Completions != null)
                        {
                            var results = new List <JSONCompletionEntry>();

                            foreach (CompletionItem item in set.Completions)
                            {
                                string insertionText = item.InsertionText.Replace("\\", "\\\\");
                                ImageMoniker moniker = item.DisplayText.EndsWith("/") || item.DisplayText.EndsWith("\\") ? _folderIcon : _libraryIcon;
                                results.Add(new SimpleCompletionEntry(item.DisplayText, insertionText, item.Description, moniker, trackingSpan, context.Session, ++count));
                            }

                            UpdateListEntriesSync(context, results);
                        }
                    }
                });
            }
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="completionSet">Completion set</param>
 /// <param name="completion">Completion to classify</param>
 /// <param name="suffix">Text to classify</param>
 /// <param name="colorize">true if it should be colorized</param>
 public CompletionSuffixClassifierContext(CompletionSet completionSet, Completion completion, string suffix, bool colorize)
     : base(completionSet, completion, suffix, colorize)
 {
 }
Ejemplo n.º 31
0
        internal void RefreshSearch()
        {
            if (Text == null)
            {
                return;
            }

            string lastSelected = SelectedItem?.CompletionItem.InsertionText;
            int expect = Interlocked.Increment(ref _version);

            string text = Text;
            int caretIndex = text.Length;
            int atIndex = text.IndexOf('@');
            Func<string, int, Task<CompletionSet>> searchService = SearchService;
            Task.Delay(250).ContinueWith(d =>
            {
                if (Volatile.Read(ref _version) != expect)
                {
                    return;
                }

                Dispatcher.BeginInvoke((Action)(() =>
                {
                    searchService?.Invoke(text, caretIndex).ContinueWith(t =>
                    {
                        if (t.IsCanceled || t.IsFaulted)
                        {
                            return;
                        }

                        CompletionSet span = t.Result;

                        Dispatcher.BeginInvoke((Action)(() =>
                        {
                            if (Volatile.Read(ref _version) != expect || span.Completions == null)
                            {
                                return;
                            }

                            Items.Clear();

                            if (atIndex >= 0)
                            {
                                span.Completions = FilterOutUnmatchedItems(span.Completions, text.Substring(atIndex + 1));
                            }

                            foreach (CompletionItem entry in span.Completions)
                            {
                                Items.Add(new Completion(entry, span.Start, span.Length));
                            }

                            PositionCompletions(span.Length);
                            OnPropertyChanged(nameof(HasItems));

                            if (Items != null && Items.Count > 0 && Options.SelectedIndex == -1)
                            {
                                if (atIndex >= 0)
                                {
                                    SelectedItem = Items.FirstOrDefault(x => x.CompletionItem.DisplayText.StartsWith(text.Substring(atIndex + 1))) ?? Items[0];
                                }
                                else
                                {
                                    SelectedItem = Items.FirstOrDefault(x => x.CompletionItem.InsertionText == lastSelected) ?? Items[0];
                                }

                                Options.ScrollIntoView(SelectedItem);
                            }
                        }));
                    });
                }));
            });
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (disposed)
                return;

            ITextSnapshot snapshot = textBuffer.CurrentSnapshot;
            SnapshotPoint? triggerPoint = session.GetTriggerPoint(snapshot);
            if (triggerPoint == null)
                return;

            int position = triggerPoint.Value.Position;

            CompletionContext context;
            var completionProviders = CompletionEngine.GetCompletionProviders(session, textBuffer, triggerPoint.Value, navigator, out context).ToList();
            if (completionProviders.Count == 0 || context == null)
                return;

            var completions = new List<Completion>();

            foreach (ICompletionListProvider completionListProvider in completionProviders)
                completions.AddRange(completionListProvider.GetCompletionEntries(context));

            if (completions.Count == 0)
                return;

            ITrackingSpan trackingSpan =
                textBuffer.CurrentSnapshot.CreateTrackingSpan(
                    position <= context.SpanStart || position > context.SpanStart + context.SpanLength
                        ? new Span(position, 0)
                        : new Span(context.SpanStart, context.SpanLength), SpanTrackingMode.EdgeInclusive);

            CompletionSet completionSet = new CompletionSet("PaketCompletion", "Paket", trackingSpan, completions, Enumerable.Empty<Completion>());

            completionSets.Add(completionSet);
        }
        IWordCompletionSession IWordCompletionSessionFactoryService.CreateWordCompletionSession(ITextView textView, SnapshotSpan wordSpan, IEnumerable<string> wordCollection, bool isForward)
        {
            var completionData = new CompletionData(
                wordSpan,
                new ReadOnlyCollection<string>(wordCollection.ToList()));
            textView.Properties[_completionDataKey] = completionData;
            try
            {
                // Dismiss any active ICompletionSession instances.  It's possible and possibly common for
                // normal intellisense to be active when the user invokes word completion.  We want only word
                // completion displayed at this point
                foreach (var existingCompletionSession in _completionBroker.GetSessions(textView))
                {
                    existingCompletionSession.Dismiss();
                }

                // Create a completion session at the start of the word.  The actual session information will
                // take care of mapping it to a specific span
                var trackingPoint = textView.TextSnapshot.CreateTrackingPoint(wordSpan.Start, PointTrackingMode.Positive);
                var completionSession = _completionBroker.CreateCompletionSession(textView, trackingPoint, true);
                completionSession.Properties[WordCompletionSessionKey] = WordCompletionSessionKey;

                // Start the completion.  This will cause it to get populated at which point we can go about
                // filtering the data
                completionSession.Start();

                // Now move the word completion set to the fron
                var wordCompletionSet = completionSession.CompletionSets.FirstOrDefault(x => x.Moniker == WordCompletionSetName);
                if (wordCompletionSet == null)
                {
                    wordCompletionSet = new CompletionSet();
                }

                completionSession.SelectedCompletionSet = wordCompletionSet;

                var intellisenseSessionStack = _intellisenseSessionStackMapService.GetStackForTextView(textView);
                var wordTrackingSpan = wordSpan.Snapshot.CreateTrackingSpan(wordSpan.Span, SpanTrackingMode.EdgeInclusive);
                var wordCompletionSession = new WordCompletionSession(
                    wordTrackingSpan,
                    intellisenseSessionStack,
                    completionSession,
                    wordCompletionSet);

                // Ensure the correct item is selected and committed to the ITextBuffer.  If this is a forward completion
                // then we select the first item, else the last.  Sending the command will go ahead and insert the
                // completion in the given span
                var command = isForward ? IntellisenseKeyboardCommand.TopLine : IntellisenseKeyboardCommand.BottomLine;
                wordCompletionSession.SendCommand(command);

                return wordCompletionSession;
            }
            finally
            {
                textView.Properties.RemoveProperty(_completionDataKey);
            }
        }
Ejemplo n.º 34
0
        public async Task <CompletionSet> GetLibraryCompletionSetAsync(string libraryNameStart, int caretPosition)
        {
            var completions = new List <CompletionItem>();

            var completionSet = new CompletionSet
            {
                Start       = 0,
                Length      = 0,
                Completions = completions
            };

            if (string.IsNullOrEmpty(libraryNameStart))
            {
                // no point in doing the rest of the work, we know it's going to be an empty completion set anyway
                return(completionSet);
            }

            completionSet.Length = libraryNameStart.Length;

            (string name, string version) = _libraryNamingScheme.GetLibraryNameAndVersion(libraryNameStart);

            // Typing '@' after the library name should have version completion.

            try
            {
                // library name completion
                if (caretPosition < name.Length + 1)
                {
                    IEnumerable <NpmPackageInfo> packages = await _packageSearch.GetPackageNamesAsync(libraryNameStart, CancellationToken.None);

                    foreach (NpmPackageInfo packageInfo in packages)
                    {
                        var completionItem = new CompletionItem
                        {
                            DisplayText   = packageInfo.Name,
                            InsertionText = _libraryNamingScheme.GetLibraryId(packageInfo.Name, packageInfo.LatestVersion)
                        };

                        completions.Add(completionItem);
                    }

                    completionSet.CompletionType = CompletionSortOrder.AsSpecified;
                }

                // library version completion
                else
                {
                    completionSet.Start  = name.Length + 1;
                    completionSet.Length = version.Length;

                    NpmPackageInfo npmPackageInfo = await _packageInfoFactory.GetPackageInfoAsync(name, CancellationToken.None);

                    IList <SemanticVersion> versions = npmPackageInfo.Versions;

                    foreach (SemanticVersion semVersion in versions)
                    {
                        string versionText    = semVersion.ToString();
                        var    completionItem = new CompletionItem
                        {
                            DisplayText   = versionText,
                            InsertionText = name + "@" + versionText
                        };

                        completions.Add(completionItem);
                    }

                    // support @latest version
                    completions.Add(new CompletionItem
                    {
                        DisplayText   = LatestVersionTag,
                        InsertionText = _libraryNamingScheme.GetLibraryId(name, LatestVersionTag),
                    });

                    completionSet.CompletionType = CompletionSortOrder.Version;
                }
            }
            catch (Exception ex)
            {
                _logger.Log(ex.ToString(), LogLevel.Error);
            }

            return(completionSet);
        }
Ejemplo n.º 35
0
        public override void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (session == null || completionSets == null)
                return;

            ITrackingPoint triggerPoint = session.GetTriggerPoint(TextBuffer);
            if (triggerPoint != null)
            {
                IntellisenseController controller = null;
                CompletionInfo completionInfo = controller.CompletionInfo;
                ITextSnapshot snapshot = triggerPoint.TextBuffer.CurrentSnapshot;
                SnapshotPoint point = triggerPoint.GetPoint(snapshot);
                bool extendLeft = false;
                bool extend = true;

                switch (completionInfo.InvocationType)
                {
                case IntellisenseInvocationType.Default:
                    extend = completionInfo.InfoType == CompletionInfoType.GlobalInfo;
                    break;

                case IntellisenseInvocationType.BackspaceDeleteOrBackTab:
                case IntellisenseInvocationType.IdentifierChar:
                case IntellisenseInvocationType.Sharp:
                case IntellisenseInvocationType.Space:
                case IntellisenseInvocationType.ShowMemberList:
                    break;

                default:
                    extendLeft = true;
                    break;
                }

                TextExtent extentOfWord = default(TextExtent);
                if (extend)
                {
                    ITextBuffer textBuffer = TextBuffer;
                    ITextStructureNavigator navigator = TextStructureNavigatorSelectorService.CreateTextStructureNavigator(textBuffer, textBuffer.ContentType);
                    SnapshotPoint currentPosition = new SnapshotPoint(snapshot, triggerPoint.GetPosition(snapshot));
                    extentOfWord = navigator.GetExtentOfWord(currentPosition);
                    if (extentOfWord.Span.Start == point)
                    {
                        TextExtent extentOfPreviousWord = navigator.GetExtentOfWord(currentPosition - 1);
                        if (extentOfPreviousWord.IsSignificant && extentOfPreviousWord.Span.End == point && IsCompletionPrefix(extentOfPreviousWord))
                            extentOfWord = extentOfPreviousWord;
                        else
                            extend = false;
                    }
                }

                if (!extend || !extentOfWord.IsSignificant)
                {
                    SnapshotSpan span = new SnapshotSpan(point, 0);
                    extentOfWord = new TextExtent(span, false);
                }

                if (completionInfo.InvocationType == IntellisenseInvocationType.BackspaceDeleteOrBackTab && extentOfWord.Span.Length > 0)
                {
                    string str3 = snapshot.GetText(extentOfWord.Span);
                    if (!string.IsNullOrWhiteSpace(str3))
                    {
                        while (CommitCharacters.IndexOf(str3[0]) > 0)
                        {
                            SnapshotSpan span2 = extentOfWord.Span;
                            SnapshotSpan span3 = new SnapshotSpan(snapshot, span2.Start + 1, span2.Length - 1);
                            extentOfWord = new TextExtent(span3, false);
                            str3 = snapshot.GetText(extentOfWord.Span);
                            if (string.IsNullOrEmpty(str3))
                                break;
                        }
                    }
                    else
                    {
                        SnapshotSpan span4 = new SnapshotSpan(snapshot, extentOfWord.Span.End, 0);
                        extentOfWord = new TextExtent(span4, false);
                        completionInfo.InvocationType = IntellisenseInvocationType.Default;
                    }
                }

                ITrackingSpan applicableTo = snapshot.CreateTrackingSpan(extentOfWord.Span, SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward);
                if (extendLeft)
                {
                    SnapshotSpan textSoFarSpan = new SnapshotSpan(snapshot, extentOfWord.Span.Start, triggerPoint.GetPoint(snapshot));
                    string textSoFar = textSoFarSpan.GetText();
                    applicableTo = snapshot.CreateTrackingSpan(point.Position - textSoFar.Length, textSoFar.Length, SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward);
                }

                /* Context Tree
                 * 
                 *  - Global
                 *    - Options
                 *    - Tokens
                 *    - AttributeScope
                 *      - ACTION
                 *    - Named Action
                 *      - ACTION
                 *    - Rule
                 *      - Arguments
                 *        - ARG_ACTION
                 *      - AttributeScope
                 *        - ACTION
                 *      - Named Action
                 *        - ACTION
                 *      - Options
                 *      - Alternative
                 *        - Alternative*
                 *        - Rewrite
                 *        - ACTION
                 */

                List<Completion> completions = new List<Completion>();
                List<Completion> completionBuilders = new List<Completion>();

                List<IntellisenseContext> intellisenseContexts = GetIntellisenseContexts(triggerPoint);
                foreach (var context in intellisenseContexts)
                {
                    context.AugmentCompletionSession(session, completions, completionBuilders);
                }

                string moniker = "AntlrCompletions";
                string displayName = "ANTLR Completions";
                CompletionSet completionSet = new CompletionSet(moniker, displayName, applicableTo, completions, completionBuilders);
                completionSets.Add(completionSet);
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Should this key commit a completion session?
        /// </summary>
        public override bool IsCommitChar(char typedChar)
        {
            if (HasActiveCompletionSession && typedChar != 0)
            {
                // only ( completes keywords
                CompletionSet completionSet  = CompletionSession.SelectedCompletionSet;
                string        completionText = completionSet.SelectionStatus.Completion.InsertionText;

                if (completionText == "else" || completionText == "repeat")
                {
                    // { after 'else' or 'repeat' completes keyword
                    if (typedChar == '{')
                    {
                        return(true);
                    }

                    // Space completes if selection is unique
                    if (char.IsWhiteSpace(typedChar) && completionSet.SelectionStatus.IsUnique)
                    {
                        return(true);
                    }

                    return(false);
                }

                // ';' completes after next or break keyword
                if (completionText == "break" || completionText == "next")
                {
                    if (typedChar == ';')
                    {
                        return(true);
                    }

                    // Space completes if selection is unique
                    if (char.IsWhiteSpace(typedChar) && completionSet.SelectionStatus.IsUnique)
                    {
                        return(true);
                    }
                }

                // Handle ( after keyword that is usually followed by expression in braces
                // such as for(), if(), library(), ...
                if (completionText == "if" || completionText == "for" || completionText == "while" ||
                    completionText == "return" || completionText == "library" || completionText == "require")
                {
                    return(typedChar == '(' || typedChar == '\t' || (char.IsWhiteSpace(typedChar) && completionSet.SelectionStatus.IsUnique));
                }

                switch (typedChar)
                {
                case '<':
                case '>':
                case '+':
                case '-':
                case '*':
                case '^':
                case '=':
                case '%':
                case '|':
                case '&':
                case '!':
                case ':':
                case '@':
                case '$':
                case '(':
                case '[':
                case '{':
                case ')':
                case ']':
                case '}':
                case ';':
                    return(completionSet.SelectionStatus.IsUnique);
                }

                if (typedChar == ' ' && !REditorSettings.CommitOnSpace)
                {
                    return(false);
                }

                if (CharExtensions.IsLineBreak(typedChar))
                {
                    // Complete on Enter but only if selection does not exactly match
                    // applicable span. for example, if span is X and selection is X123
                    // then we do complete. However, if selection is X then text is already
                    // fully typed and Enter should be adding new line as with regular typing.
                    if (completionSet.SelectionStatus.IsSelected)
                    {
                        var typedText = completionSet.ApplicableTo.GetText(_textBuffer.CurrentSnapshot).Trim();
                        return(completionText.Length > typedText.Length);
                    }
                }

                return(char.IsWhiteSpace(typedChar));
            }

            return(false);
        }
        IWordCompletionSession IWordCompletionSessionFactoryService.CreateWordCompletionSession(ITextView textView, SnapshotSpan wordSpan, IEnumerable <string> wordCollection, bool isForward)
        {
            var completionData = new CompletionData(
                wordSpan,
                new ReadOnlyCollection <string>(wordCollection.ToList()));

            textView.Properties[_completionDataKey] = completionData;
            try
            {
                // Dismiss any active ICompletionSession instances.  It's possible and possibly common for
                // normal intellisense to be active when the user invokes word completion.  We want only word
                // completion displayed at this point
                foreach (var existingCompletionSession in _completionBroker.GetSessions(textView))
                {
                    existingCompletionSession.Dismiss();
                }

                // Create a completion session at the start of the word.  The actual session information will
                // take care of mapping it to a specific span
                var trackingPoint     = textView.TextSnapshot.CreateTrackingPoint(wordSpan.Start, PointTrackingMode.Positive);
                var completionSession = _completionBroker.CreateCompletionSession(textView, trackingPoint, true);
                completionSession.Properties[WordCompletionSessionKey] = WordCompletionSessionKey;

                // Start the completion.  This will cause it to get populated at which point we can go about
                // filtering the data
                completionSession.Start();

                // It's possible for the Start method to dismiss the ICompletionSession.  This happens when there
                // is an initialization error such as being unable to find a CompletionSet.  If this occurs we
                // just return the equivalent IWordCompletionSession (one which is dismissed)
                if (completionSession.IsDismissed)
                {
                    return(new DismissedWordCompletionSession(textView));
                }

                // Now move the word completion set to the fron
                var wordCompletionSet = completionSession.CompletionSets.FirstOrDefault(x => x.Moniker == WordCompletionSetName);
                if (wordCompletionSet == null)
                {
                    wordCompletionSet = new CompletionSet();
                }

                completionSession.SelectedCompletionSet = wordCompletionSet;

                var intellisenseSessionStack = _intellisenseSessionStackMapService.GetStackForTextView(textView);
                var wordTrackingSpan         = wordSpan.Snapshot.CreateTrackingSpan(wordSpan.Span, SpanTrackingMode.EdgeInclusive);
                var wordCompletionSession    = new WordCompletionSession(
                    wordTrackingSpan,
                    intellisenseSessionStack,
                    completionSession,
                    wordCompletionSet);

                // Ensure the correct item is selected and committed to the ITextBuffer.  If this is a forward completion
                // then we select the first item, else the last.  Sending the command will go ahead and insert the
                // completion in the given span
                var command = isForward ? IntellisenseKeyboardCommand.TopLine : IntellisenseKeyboardCommand.BottomLine;
                wordCompletionSession.SendCommand(command);

                return(wordCompletionSession);
            }
            finally
            {
                textView.Properties.RemoveProperty(_completionDataKey);
            }
        }
Ejemplo n.º 38
0
        public override async Task <CompletionItem> GetRecommendedSelectedCompletionAsync(CompletionSet completionSet, CompletionItem?lastSelected)
        {
            int atIndex = SearchText.IndexOf('@');
            var result  = default(CompletionItem);

            if (atIndex >= 0)
            {
                // if we're in the version portion, try to select the first item that starts with the version
                string versionPortion = SearchText.Substring(atIndex + 1);
                Func <CompletionItem, bool> predicate = x => x.DisplayText.StartsWith(versionPortion, StringComparison.OrdinalIgnoreCase);
                result = completionSet.Completions.FirstOrDefault(predicate);
                if (result == default(CompletionItem))
                {
                    result = completionSet.Completions.FirstOrDefault();
                }
            }
            else
            {
                result = await base.GetRecommendedSelectedCompletionAsync(completionSet, lastSelected);
            }

            return(result);
        }
Ejemplo n.º 39
0
        /// <inheritdoc />
        public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            // The IntelliSense calculation within comments is rather simple. To detect when the completion is
            // currently located within an XML documentation comment, the following "tricks" are used.
            //
            // 1. The filtering algorithm in use never removes "!--" (indicating an XML comment) from the
            //    completion set, so it is always listed when completion is invoked.  In addition, the sorting
            //    algorithm always places this item first in the completion set.
            // 2. Since this particular tag is not valid elsewhere in C#, it is easily used to determine when the
            //    caret is inside an XML documentation comment.
            if (completionSets.Count == 0 || completionSets[0].Completions.Count == 0 ||
                completionSets[0].Completions[0].DisplayText != "!--")
            {
                // Not inside a documentation comment, so leave things alone
                return;
            }

            // Next, we need to determine if the user pressed "<" or simply pressed Ctrl+Space to invoke code
            // completion.  Since the C# IntelliSense provider doesn't include any existing "<" character in the
            // reported ApplicableTo tracking span, we must insert this character when it's not already present.
            // XML itself makes this easy - the "<" character will either appear immediately before the
            // ApplicableTo span or it will not be present.
            ITextSnapshot snapshot   = _textBuffer.CurrentSnapshot;
            SnapshotPoint startPoint = completionSets[0].ApplicableTo.GetStartPoint(snapshot);

            string prefix = String.Empty;

            if (startPoint > 0 && snapshot.GetText(startPoint.Position - 1, 1) != "<")
            {
                prefix = "<";
            }

            // Use the GlyphKeyword glyph for "normal" XML tags, to match the glyphs used by C#
            // for the standard IntelliSense tags. Use the GlyphGroupMacro glyph for other completion
            // items that expand to something other that what the user wrote (e.g. "true" expands to
            // <see langword="true"/> as opposed to <true/>).
            //
            // The descriptions for custom tags is copied from the Sandcastle XML Comments Guide.  Obsolete
            // custom tags are not included.
            var iconSource = _provider.GlyphService.GetGlyph(StandardGlyphGroup.GlyphKeyword,
                                                             StandardGlyphItem.GlyphItemPublic);
            var macroIconSource = _provider.GlyphService.GetGlyph(StandardGlyphGroup.GlyphGroupMacro,
                                                                  StandardGlyphItem.GlyphItemPublic);

            // The elements are context sensitive so only show them if applicable based on the elements
            // determined to be valid by the C# IntelliSense provider.
            var allTags = completionSets.SelectMany(c => c.CompletionBuilders).Select(b => b.DisplayText).Concat(
                completionSets.SelectMany(c => c.Completions).Select(c => c.DisplayText)).ToList();

            // Elements allowed anywhere
            var completions = new List <Completion>
            {
                new CustomCompletion(session, "conceptualLink", prefix + "conceptualLink target=\"\xFF\"/>",
                                     "This element is used to create a link to a MAML topic within the See Also section of a " +
                                     "topic or an inline link to a MAML topic within one of the other XML comments elements.",
                                     iconSource, ""),
                new Completion("inheritdoc", prefix + "inheritdoc/>", "This element can help minimize the " +
                               "effort required to document complex APIs by allowing common documentation to be " +
                               "inherited from base types/members.", iconSource, ""),
                new CustomCompletion(session, "inheritdoc cref", prefix + "inheritdoc cref=\"\xFF\"/>",
                                     "Inherit documentation from a specific member.", iconSource, ""),
                new CustomCompletion(session, "inheritdoc cref/select", prefix + "inheritdoc cref=\"\xFF\" " +
                                     "select=\"summary|remarks\"/>", "Inherit documentation from a specific member and comments.",
                                     iconSource, ""),
                new Completion("token", prefix + "token", "This element represents a replaceable tag within " +
                               "a topic.", iconSource, "")
            };

            // General top-level elements
            if (allTags.Contains("exception"))
            {
                completions.AddRange(new[]
                {
                    new Completion("AttachedEventComments", prefix + "AttachedEventComments", "This element " +
                                   "is used to define the content that should appear on the auto-generated attached " +
                                   "event member topic for a given WPF routed event member.", iconSource, ""),
                    new Completion("AttachedPropertyComments", prefix + "AttachedPropertyComments",
                                   "This element is used to define the content that should appear on the auto-generated " +
                                   "attached property member topic for a given WPF dependency property member.",
                                   iconSource, ""),
                    new CustomCompletion(session, "event", prefix + "event cref=\"\xFF\"",
                                         "This element is used to list events that can be raised by a type's member.",
                                         iconSource, ""),
                    new Completion("overloads", prefix + "overloads", "This element is used to define the " +
                                   "content that should appear on the auto-generated overloads topic for a given set of " +
                                   "member overloads.", iconSource, ""),
                    new Completion("preliminary", prefix + "preliminary/>",
                                   "This element is used to indicate that a particular type or member is preliminary and " +
                                   "is subject to change.", iconSource, ""),
                    new Completion("threadsafety", prefix + "threadsafety static=\"true\" instance=\"false\"/>",
                                   "This element is used to indicate whether or not a class or structure's static and " +
                                   "instance members are safe for use in multi-threaded scenarios.", iconSource, "")
                });
            }

            // General inline elements
            if (allTags.Contains("list"))
            {
                completions.AddRange(new[]
                {
                    new Completion("note", prefix + "note type=\"note\"", "This element is used to create a " +
                                   "note-like section within a topic to draw attention to some important information.",
                                   iconSource, "")
                });

                // Language-specific keyword extensions.  The C# provider allows these at any level but
                // Sandcastle only uses them if they are inline.
                //
                // NOTE: The display text on these MUST be prefixed with "langword" or it will cause VS2013 to
                // crash whenever "<see" is typed into an XML comment.  Adding the prefix works around the issue.
                completions.AddRange(new[]
                {
                    new Completion("langword null", prefix + "see langword=\"null\"/>", "Inserts the language-specific " +
                                   "keyword 'null'.", macroIconSource, ""),
                    new Completion("langword static", prefix + "see langword=\"static\"/>", "Inserts the " +
                                   "language-specific keyword 'static'.", macroIconSource, ""),
                    new Completion("langword virtual", prefix + "see langword=\"virtual\"/>", "Inserts the " +
                                   "language-specific keyword 'virtual'.", macroIconSource, ""),
                    new Completion("langword true", prefix + "see langword=\"true\"/>", "Inserts the language-specific " +
                                   "keyword 'true'.", macroIconSource, ""),
                    new Completion("langword false", prefix + "see langword=\"false\"/>", "Inserts the " +
                                   "language-specific keyword 'false'.", macroIconSource, ""),
                    new Completion("langword abstract", prefix + "see langword=\"abstract\"/>", "Inserts the " +
                                   "language-specific keyword 'abstract'.", macroIconSource, ""),
                    new Completion("langword async", prefix + "see langword=\"async\"/>", "Inserts the " +
                                   "language-specific keyword 'async'.", macroIconSource, ""),
                    new Completion("langword await", prefix + "see langword=\"await\"/>", "Inserts the " +
                                   "language-specific keyword 'await'.", macroIconSource, ""),
                    new Completion("langword async/await", prefix + "see langword=\"async/await\"/>", "Inserts the " +
                                   "language-specific keyword 'async/await'.", macroIconSource, "")
                });
            }

            // Code element extensions
            if (allTags.Contains("code"))
            {
                completions.AddRange(new[]
                {
                    new CustomCompletion(session, "code import", prefix + "code language=\"\xFF\" title=\" \" " +
                                         "source=\"..\\Path\\SourceFile.cs\" region=\"Region Name\"/>", "This element is used " +
                                         "to indicate that a multi-line section of text should be imported from the named " +
                                         "region of the named file and formatted as a code block.", iconSource, ""),
                    new CustomCompletion(session, "code language", prefix + "code language=\"\xFF\" " +
                                         "title=\" \"></code>", "This element is used to indicate that a multi-line section of " +
                                         "text should be formatted as a code block.", iconSource, ""),
                });
            }

            // The augmented completion set is created from the previously existing one (created by the C#
            // language service), and a CompletionSet created for the custom XML tags. The moniker and display
            // name for the additional set are not used, since the augmented set always returns the values
            // reported by the original completion set.
            CompletionSet additionalCompletionSet = new CompletionSet("", "", completionSets[0].ApplicableTo,
                                                                      completions, Enumerable.Empty <Completion>());

            completionSets[0] = new AugmentedCompletionSet(completionSets[0], additionalCompletionSet);
        }
Ejemplo n.º 40
0
        private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextChange textChange = e.Changes.Last();

            // We will invoke completion on text insertion and not deletion.
            // Also, we don't want to invoke completion on dialog load as we pre populate the target
            // location textbox with name of the folder when dialog is initially loaded.
            // In the case of deletion or replacement, if the completion flyout is already open, we
            // should still update the list, as the filtered items have likely changed.
            bool textInserted = textChange.AddedLength > 0 && SearchTextBox.CaretIndex > 0;

            if (textInserted || Flyout.IsOpen)
            {
                ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
                {
                    // grab these WPF dependant things while we're still on the UI thread
                    int caretIndex = SearchTextBox.CaretIndex;
                    SearchTextBoxViewModel viewModel = ViewModel;

                    string textBeforeGetCompletion = SearchTextBox.Text;

                    // Switch to a background thread to not block the UI thread, as this operation can take
                    // a while for slow network connections
                    await TaskScheduler.Default;
                    CompletionSet completionSet = await viewModel.GetCompletionSetAsync(caretIndex);

                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    // If the value has changed then this request is out of date.
                    // If focus is elsewhere the work below won't be used anyway
                    if (textBeforeGetCompletion != SearchTextBox.Text || !SearchTextBox.IsFocused)
                    {
                        return;
                    }

                    if (completionSet.Completions == null || !completionSet.Completions.Any())
                    {
                        Flyout.IsOpen = false;
                        completionSet = new CompletionSet
                        {
                            Completions = new[]
                            {
                                new CompletionItem
                                {
                                    DisplayText   = Text.NoMatchesFound,
                                    InsertionText = null,
                                }
                            }
                        };
                    }

                    // repopulate the completion list
                    CompletionEntries.Clear();

                    List <CompletionItem> completions = GetSortedCompletionItems(completionSet);

                    foreach (CompletionItem entry in completions)
                    {
                        CompletionEntries.Add(new CompletionEntry(entry, completionSet.Start, completionSet.Length));
                    }

                    PositionCompletionPopup();

                    if (CompletionEntries != null && CompletionEntries.Count > 0 && Options.SelectedIndex == -1)
                    {
                        CompletionItem selectionCandidate = await ViewModel.GetRecommendedSelectedCompletionAsync(
                            completions: completions,
                            lastSelected: SelectedItem?.CompletionItem);
                        SelectedItem = CompletionEntries.FirstOrDefault(x => x.CompletionItem.InsertionText == selectionCandidate.InsertionText) ?? CompletionEntries[0];
                        Options.ScrollIntoView(SelectedItem);
                    }

                    Flyout.IsOpen = true;
                });
            }
        }
Ejemplo n.º 41
0
        public override CompletionSet GetCompletions(IGlyphService glyphService) {
            var start = _stopwatch.ElapsedMilliseconds;

            var line = Span.GetStartPoint(TextBuffer.CurrentSnapshot).GetContainingLine();
            var startPos = line.Start.Position + line.GetText().IndexOf("def");

            var analysis = GetAnalysisEntry();
            if (analysis == null) {
                return null;
            }

            var span = Span.GetSpan(TextBuffer.CurrentSnapshot);
            int defIndent = span.Start.GetContainingLine().GetText().IndexOf("def");

            string indentation;
            if (_options.ConvertTabsToSpaces) {
                indentation = new string(' ', defIndent + _options.IndentSize);
            } else {
                indentation = new string('\t', defIndent / 8 + 1);
            }

            var snapshot = TextBuffer.CurrentSnapshot;
            var pos = VsProjectAnalyzer.TranslateIndex(startPos, snapshot, analysis);

            var completions = analysis.Analyzer.GetOverrideCompletionsAsync(
                analysis,
                TextBuffer,
                pos,
                indentation
            ).WaitOrDefault(1000)?.overrides;

            CompletionSet res;
            if (completions != null && completions.Any()) {
                var set = new FuzzyCompletionSet(
                    "PythonOverrides",
                    "Python",
                    Span,
                    completions.Select(
                        x => PythonCompletion(
                            glyphService,
                            x.name,
                            x.completion,
                            x.doc,
                            StandardGlyphGroup.GlyphGroupOverload
                        )
                    ).ToArray(),
                    _options,
                    CompletionComparer.UnderscoresLast
                );
                set.CommitByDefault = false;
                res = set;
            } else {
                res = new CompletionSet();
            }

            var end = _stopwatch.ElapsedMilliseconds;

            if (/*Logging &&*/ end - start > TooMuchTime) {
                Trace.WriteLine(String.Format("{0} lookup time {1} for {2} classes", this, end - start, res.Completions.Count));
            }

            return res;
        }
Ejemplo n.º 42
0
 private static bool TryExtractAllCompletionsSet(IList <CompletionSet> completionSets, out CompletionSet allCompletions)
 {
     allCompletions = null;
     foreach (var completionSet in completionSets)
     {
         if (completionSet.DisplayName != "All")
         {
             continue;
         }
         allCompletions = completionSet;
         return(true);
     }
     return(false);
 }
Ejemplo n.º 43
0
        public override void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (session == null || completionSets == null)
                return;

            ITrackingPoint triggerPoint = session.GetTriggerPoint(TextBuffer);
            if (triggerPoint != null)
            {
                IntellisenseController controller = GetControllerForView(session.TextView);
                CompletionInfo completionInfo = controller.CompletionInfo;
                ITextSnapshot snapshot = triggerPoint.TextBuffer.CurrentSnapshot;
                SnapshotPoint point = triggerPoint.GetPoint(snapshot);
                ITrackingPoint point2 = triggerPoint;
                bool flag = false;
                bool extend = true;

                IntellisenseInvocationType invocationType = completionInfo.InvocationType;
                CompletionInfoType infoType = completionInfo.InfoType;

                switch (invocationType)
                {
                case IntellisenseInvocationType.Default:
                    extend = infoType == CompletionInfoType.GlobalInfo;
                    break;

                case IntellisenseInvocationType.BackspaceDeleteOrBackTab:
                case IntellisenseInvocationType.IdentifierChar:
                case IntellisenseInvocationType.Sharp:
                case IntellisenseInvocationType.Space:
                case IntellisenseInvocationType.ShowMemberList:
                    break;

                default:
                    flag = true;
                    break;
                }

                TextExtent extentOfWord = default(TextExtent);
                if (extend)
                {
                    ITextBuffer textBuffer = TextBuffer;
                    ITextStructureNavigator navigator = TextStructureNavigatorSelectorService.CreateTextStructureNavigator(textBuffer, textBuffer.ContentType);
                    SnapshotPoint currentPosition = new SnapshotPoint(snapshot, point2.GetPosition(snapshot));
                    extentOfWord = navigator.GetExtentOfWord(currentPosition);
                    if (extentOfWord.Span.Start == point)
                    {
                        TextExtent extentOfPreviousWord = navigator.GetExtentOfWord(currentPosition - 1);
                        if (extentOfPreviousWord.IsSignificant && extentOfPreviousWord.Span.End == point && IsCompletionPrefix(extentOfPreviousWord))
                            extentOfWord = extentOfPreviousWord;
                        else
                            extend = false;
                    }
                }

                if (!extend || !extentOfWord.IsSignificant)
                {
                    SnapshotSpan span = new SnapshotSpan(point, 0);
                    extentOfWord = new TextExtent(span, false);
                }

                if (invocationType == IntellisenseInvocationType.BackspaceDeleteOrBackTab && extentOfWord.Span.Length > 0)
                {
                    string str3 = snapshot.GetText(extentOfWord.Span);
                    if (!string.IsNullOrWhiteSpace(str3))
                    {
                        while ("!^()=<>\\:;.,+-*/{}\" '&%@?".IndexOf(str3[0]) > 0)
                        {
                            SnapshotSpan span2 = extentOfWord.Span;
                            SnapshotSpan span3 = new SnapshotSpan(snapshot, span2.Start + 1, span2.Length - 1);
                            extentOfWord = new TextExtent(span3, false);
                            str3 = snapshot.GetText(extentOfWord.Span);
                            if (string.IsNullOrEmpty(str3))
                                break;
                        }
                    }
                    else
                    {
                        SnapshotSpan span4 = new SnapshotSpan(snapshot, extentOfWord.Span.End, 0);
                        extentOfWord = new TextExtent(span4, false);
                        completionInfo.InvocationType = IntellisenseInvocationType.Default;
                    }
                }

                ITrackingSpan applicableTo = snapshot.CreateTrackingSpan(extentOfWord.Span, SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward);
                if (flag)
                {
                    SnapshotSpan textSoFarSpan = new SnapshotSpan(snapshot, extentOfWord.Span.Start, triggerPoint.GetPoint(snapshot));
                    string textSoFar = textSoFarSpan.GetText();
                    applicableTo = snapshot.CreateTrackingSpan(point.Position - textSoFar.Length, textSoFar.Length, SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward);
                }

                IEnumerable<Completion> context = GetContextCompletions(triggerPoint.GetPoint(snapshot), (AlloyIntellisenseController)controller, session);
                IEnumerable<Completion> keywords = GetKeywordCompletions();
                IEnumerable<Completion> snippets = GetSnippetCompletions();
                //List<Completion> signatures = GetSignatureCompletions();
                //List<Completion> relations = GetRelationCompletions();
                //List<Completion> predicates = GetPredicateCompletions();
                //List<Completion> functions = GetFunctionCompletions();
                //SnapshotSpan? Provider.IntellisenseCache.GetExpressionSpan(triggerPoint.GetPoint(snapshot));

                IEnumerable<Completion> completions = context.Concat(keywords).Concat(snippets);
                IEnumerable<Completion> orderedCompletions = completions.Distinct(CompletionDisplayNameComparer.CurrentCulture).OrderBy(i => i.DisplayText, StringComparer.CurrentCultureIgnoreCase);

                CompletionSet completionSet = new CompletionSet("AlloyCompletions", "Alloy Completions", applicableTo, orderedCompletions, EmptyCompletions);
                completionSets.Add(completionSet);
            }
        }
Ejemplo n.º 44
0
 private static IEnumerable<string> GetCompletionNames(CompletionSet completions) {
     foreach (var comp in completions.Completions) {
         yield return comp.InsertionText;
     }
 }
Ejemplo n.º 45
0
        protected override IEnumerable <JSONCompletionEntry> GetEntries(JSONCompletionContext context)
        {
            var member = context.ContextItem as JSONMember;

            if (member == null || member.UnquotedNameText != "id")
            {
                yield break;
            }

            var parent = member.Parent as JSONObject;

            if (!JsonHelpers.TryGetInstallationState(parent, out ILibraryInstallationState state))
            {
                yield break;
            }

            var             dependencies = Dependencies.FromConfigFile(ConfigFilePath);
            IProvider       provider     = dependencies.GetProvider(state.ProviderId);
            ILibraryCatalog catalog      = provider?.GetCatalog();

            if (catalog == null)
            {
                yield break;
            }

            int caretPosition = context.Session.TextView.Caret.Position.BufferPosition - member.Value.Start - 1;

            if (caretPosition > member.UnquotedValueText.Length)
            {
                yield break;
            }

            Task <CompletionSet> task = catalog.GetLibraryCompletionSetAsync(member.UnquotedValueText, caretPosition);
            int count = 0;

            if (task.IsCompleted)
            {
                CompletionSet set          = task.Result;
                int           start        = member.Value.Start;
                ITrackingSpan trackingSpan = context.Snapshot.CreateTrackingSpan(start + 1 + set.Start, set.Length, SpanTrackingMode.EdgeInclusive);

                if (set.Completions != null)
                {
                    foreach (CompletionItem item in set.Completions)
                    {
                        string       insertionText = item.InsertionText.Replace("\\\\", "\\").Replace("\\", "\\\\");
                        ImageMoniker moniker       = item.DisplayText.EndsWith("/") || item.DisplayText.EndsWith("\\") ? _folderIcon : _libraryIcon;
                        yield return(new SimpleCompletionEntry(item.DisplayText, insertionText, item.Description, moniker, trackingSpan, context.Session, ++count));
                    }
                }
            }
            else
            {
                yield return(new SimpleCompletionEntry(Resources.Text.Loading, KnownMonikers.Loading, context.Session));

                task.ContinueWith((a) =>
                {
                    if (!context.Session.IsDismissed)
                    {
                        CompletionSet set          = task.Result;
                        int start                  = member.Value.Start;
                        ITrackingSpan trackingSpan = context.Snapshot.CreateTrackingSpan(start + 1 + set.Start, set.Length, SpanTrackingMode.EdgeExclusive);

                        if (set.Completions != null)
                        {
                            var results = new List <JSONCompletionEntry>();

                            foreach (CompletionItem item in set.Completions)
                            {
                                string insertionText = item.InsertionText.Replace("\\", "\\\\");
                                ImageMoniker moniker = item.DisplayText.EndsWith("/") || item.DisplayText.EndsWith("\\") ? _folderIcon : _libraryIcon;
                                results.Add(new SimpleCompletionEntry(item.DisplayText, insertionText, item.Description, moniker, trackingSpan, context.Session, ++count));
                            }

                            UpdateListEntriesSync(context, results);
                        }
                    }
                });
            }
        }
Ejemplo n.º 46
0
        public override void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            if (session == null || completionSets == null)
            {
                return;
            }

            ITrackingPoint triggerPoint = session.GetTriggerPoint(TextBuffer);

            if (triggerPoint != null)
            {
                IntellisenseController controller     = GetControllerForView(session.TextView);
                CompletionInfo         completionInfo = controller.CompletionInfo;
                ITextSnapshot          snapshot       = triggerPoint.TextBuffer.CurrentSnapshot;
                SnapshotPoint          point          = triggerPoint.GetPoint(snapshot);
                bool extendLeft = false;
                bool extend     = true;

                // labels includes both implicit and explicit labels
                var labels = FindLabelsInScope(point);

                IntellisenseInvocationType invocationType = completionInfo.InvocationType;
                CompletionInfoType         infoType       = completionInfo.InfoType;

                switch (invocationType)
                {
                case IntellisenseInvocationType.Default:
                    extend = infoType == CompletionInfoType.GlobalInfo;
                    break;

                case IntellisenseInvocationType.BackspaceDeleteOrBackTab:
                case IntellisenseInvocationType.IdentifierChar:
                case IntellisenseInvocationType.Sharp:
                case IntellisenseInvocationType.Space:
                case IntellisenseInvocationType.ShowMemberList:
                    break;

                default:
                    extendLeft = true;
                    break;
                }

                TextExtent extentOfWord = default(TextExtent);
                if (extend)
                {
                    ITextBuffer             textBuffer      = TextBuffer;
                    ITextStructureNavigator navigator       = TextStructureNavigatorSelectorService.CreateTextStructureNavigator(textBuffer, textBuffer.ContentType);
                    SnapshotPoint           currentPosition = new SnapshotPoint(snapshot, triggerPoint.GetPosition(snapshot));
                    extentOfWord = navigator.GetExtentOfWord(currentPosition);
                    if (extentOfWord.Span.Start == point)
                    {
                        TextExtent extentOfPreviousWord = navigator.GetExtentOfWord(currentPosition - 1);
                        if (extentOfPreviousWord.IsSignificant && extentOfPreviousWord.Span.End == point && IsCompletionPrefix(extentOfPreviousWord))
                        {
                            extentOfWord = extentOfPreviousWord;
                        }
                        else
                        {
                            extend = false;
                        }
                    }
                }

                if (!extend || !extentOfWord.IsSignificant)
                {
                    SnapshotSpan span = new SnapshotSpan(point, 0);
                    extentOfWord = new TextExtent(span, false);
                }

                if (invocationType == IntellisenseInvocationType.BackspaceDeleteOrBackTab && extentOfWord.Span.Length > 0)
                {
                    string str3 = snapshot.GetText(extentOfWord.Span);
                    if (!string.IsNullOrWhiteSpace(str3))
                    {
                        while (CommitCharacters.IndexOf(str3[0]) > 0)
                        {
                            SnapshotSpan span2 = extentOfWord.Span;
                            SnapshotSpan span3 = new SnapshotSpan(snapshot, span2.Start + 1, span2.Length - 1);
                            extentOfWord = new TextExtent(span3, false);
                            str3         = snapshot.GetText(extentOfWord.Span);
                            if (string.IsNullOrEmpty(str3))
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        SnapshotSpan span4 = new SnapshotSpan(snapshot, extentOfWord.Span.End, 0);
                        extentOfWord = new TextExtent(span4, false);
                        completionInfo.InvocationType = IntellisenseInvocationType.Default;
                    }
                }

                if (completionInfo.InfoType == CompletionInfoType.AutoListMemberInfo && extentOfWord.Span.GetText().StartsWith("$") && labels.Count == 0)
                {
                    session.Dismiss();
                    return;
                }

                ITrackingSpan applicableTo = snapshot.CreateTrackingSpan(extentOfWord.Span, SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward);
                if (extendLeft)
                {
                    SnapshotSpan textSoFarSpan = new SnapshotSpan(snapshot, extentOfWord.Span.Start, triggerPoint.GetPoint(snapshot));
                    string       textSoFar     = textSoFarSpan.GetText();
                    applicableTo = snapshot.CreateTrackingSpan(point.Position - textSoFar.Length, textSoFar.Length, SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward);
                }

                IEnumerable <Completion> context          = GetContextCompletions(triggerPoint.GetPoint(snapshot), (Antlr4IntellisenseController)controller, session);
                IEnumerable <Completion> keywords         = GetKeywordCompletions();
                IEnumerable <Completion> snippets         = GetSnippetCompletions();
                IEnumerable <Completion> labelCompletions = GetLabelCompletions(labels);
                //SnapshotSpan? Provider.IntellisenseCache.GetExpressionSpan(triggerPoint.GetPoint(snapshot));

                IEnumerable <Completion> completions        = context.Concat(keywords).Concat(snippets).Concat(labelCompletions);
                IEnumerable <Completion> orderedCompletions = completions.Distinct(CompletionDisplayNameComparer.CurrentCulture).OrderBy(i => i.DisplayText, StringComparer.CurrentCultureIgnoreCase);

                CompletionSet completionSet = new CompletionSet("AntlrCompletions", "Antlr Completions", applicableTo, orderedCompletions, EmptyCompletions);
                completionSets.Add(completionSet);
            }
        }
Ejemplo n.º 47
0
        private static CompletionMatchResult MatchCompletionList(this CompletionSet set, IList <Completion> completionList, CompletionMatchType matchType, bool caseSensitive)
        {
            if (set.ApplicableTo == null)
            {
                throw new InvalidOperationException("Cannot match completion set with no applicability span.");
            }

            ITextSnapshot currentSnapshot = set.ApplicableTo.TextBuffer.CurrentSnapshot;
            string        text            = set.ApplicableTo.GetText(currentSnapshot);

            if (text.Length != 0)
            {
                Completion bestMatch        = null;
                int        maxMatchPosition = -1;
                bool       isUnique         = false;
                bool       isSelected       = false;
                foreach (Completion currentCompletion in completionList)
                {
                    string displayText = string.Empty;
                    if (matchType == CompletionMatchType.MatchDisplayText)
                    {
                        displayText = currentCompletion.DisplayText;
                    }
                    else if (matchType == CompletionMatchType.MatchInsertionText)
                    {
                        displayText = currentCompletion.InsertionText;
                    }
                    int matchPositionCount = 0;
                    for (int i = 0; i < text.Length; i++)
                    {
                        if (i >= displayText.Length)
                        {
                            break;
                        }
                        char textChar        = text[i];
                        char displayTextChar = displayText[i];
                        if (!caseSensitive)
                        {
                            textChar        = char.ToLowerInvariant(textChar);
                            displayTextChar = char.ToLowerInvariant(displayTextChar);
                        }
                        if (textChar != displayTextChar)
                        {
                            break;
                        }
                        matchPositionCount++;
                    }
                    if (matchPositionCount > maxMatchPosition)
                    {
                        maxMatchPosition = matchPositionCount;
                        bestMatch        = currentCompletion;
                        isUnique         = true;
                        if ((matchPositionCount == text.Length) && (maxMatchPosition > 0))
                        {
                            isSelected = true;
                        }
                    }
                    else if (matchPositionCount == maxMatchPosition)
                    {
                        isUnique = false;
                        if (isSelected)
                        {
                            break;
                        }
                    }
                }
                if (bestMatch != null)
                {
                    CompletionMatchResult result = new CompletionMatchResult();
                    result.SelectionStatus   = new CompletionSelectionStatus(bestMatch, isSelected, isUnique);
                    result.CharsMatchedCount = (maxMatchPosition >= 0) ? maxMatchPosition : 0;
                    return(result);
                }
            }
            return(null);
        }
Ejemplo n.º 48
0
        private List <JSONCompletionEntry> GetCompletionList(JSONMember member, JSONCompletionContext context, CompletionSet completionSet, int count)
        {
            int           start               = member.Value.Start;
            ITrackingSpan trackingSpan        = context.Snapshot.CreateTrackingSpan(start + 1 + completionSet.Start, completionSet.Length, SpanTrackingMode.EdgeExclusive);
            bool          isVersionCompletion = (completionSet.CompletionType == CompletionSortOrder.Version);

            List <JSONCompletionEntry> results = new List <JSONCompletionEntry>();

            foreach (CompletionItem item in completionSet.Completions)
            {
                string       insertionText = item.InsertionText.Replace("\\\\", "\\").Replace("\\", "\\\\");
                ImageMoniker moniker       = item.DisplayText.EndsWith("/") || item.DisplayText.EndsWith("\\") ? _folderIcon : _libraryIcon;

                if (isVersionCompletion)
                {
                    results.Add(new VersionCompletionEntry(item.DisplayText, insertionText, item.Description, moniker, trackingSpan, context.Session, ++count));
                }
                else
                {
                    results.Add(new SimpleCompletionEntry(item.DisplayText, insertionText, item.Description, moniker, trackingSpan, context.Session, ++count));
                }
            }

            return(results);
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Gets a list of completion spans for use in the JSON file.
        /// </summary>
        /// <param name="value">The current state of the library ID.</param>
        /// <param name="caretPosition">The caret position inside the <paramref name="value" />.</param>
        /// <returns></returns>
        public Task <CompletionSet> GetLibraryCompletionSetAsync(string value, int caretPosition)
        {
            if (value.Contains("://"))
            {
                return(Task.FromResult(default(CompletionSet)));
            }

            try
            {
                char   separator = value.Contains('\\') ? '\\' : '/';
                int    index     = value.Length >= caretPosition - 1 ? value.LastIndexOf(separator, Math.Max(caretPosition - 1, 0)) : value.Length;
                string path      = _provider.HostInteraction.WorkingDirectory;
                string prefix    = "";

                if (index > 0)
                {
                    prefix = value.Substring(0, index + 1);
                    path   = Path.Combine(path, prefix);
                }

                var set = new CompletionSet
                {
                    Start  = 0,
                    Length = value.Length
                };

                var dir = new DirectoryInfo(path);

                if (dir.Exists)
                {
                    var list = new List <CompletionItem>();

                    foreach (FileSystemInfo item in dir.EnumerateDirectories())
                    {
                        var completion = new CompletionItem
                        {
                            DisplayText   = item.Name + separator,
                            InsertionText = prefix + item.Name + separator,
                        };

                        list.Add(completion);
                    }

                    foreach (FileSystemInfo item in dir.EnumerateFiles())
                    {
                        var completion = new CompletionItem
                        {
                            DisplayText   = item.Name,
                            InsertionText = prefix + item.Name,
                        };

                        list.Add(completion);
                    }

                    set.Completions = list;
                }

                return(Task.FromResult(set));
            }
            catch
            {
                throw new InvalidLibraryException(value, _provider.Id);
            }
        }
Ejemplo n.º 50
0
		void UnregisterCompletionSetEvents() {
			if (currentCompletionSet != null) {
				currentCompletionSet.SelectionStatusChanged -= CompletionSet_SelectionStatusChanged;
				currentCompletionSet = null;
			}
		}
Ejemplo n.º 51
0
        private static void MergeSparkWithAllCompletionsSet(IList <CompletionSet> completionSets, CompletionSet sparkCompletions)
        {
            CompletionSet allCompletionsSet;

            if (!TryExtractAllCompletionsSet(completionSets, out allCompletionsSet))
            {
                return;
            }

            var mergedCompletionSet = new CompletionSet(
                allCompletionsSet.Moniker,
                allCompletionsSet.DisplayName,
                allCompletionsSet.ApplicableTo,
                GetCombinedSortedList(sparkCompletions, allCompletionsSet),
                allCompletionsSet.CompletionBuilders);

            completionSets.Remove(allCompletionsSet);
            completionSets.Add(mergedCompletionSet);
        }
Ejemplo n.º 52
0
 private bool IsPrefixMatch(CompletionSet selectedCompletionSet)
 {
     return selectedCompletionSet is CustomCompletionSet &&
            ((CustomCompletionSet)selectedCompletionSet).PrefixMatch;
 }
Ejemplo n.º 53
0
        private bool HandleCompletion(char commitCharacter)
        {
            ReadOnlyCollection <ICompletionSession> completionSessions = _completionBroker.GetSessions(_textView);

            if (completionSessions.Count == 0)
            {
                return(false);
            }

            ICompletionSession completionSession = completionSessions[0];

            if (completionSession.IsDismissed)
            {
                return(false);
            }

            CompletionSet             completionSet   = completionSession.SelectedCompletionSet;
            CompletionSelectionStatus selectionStatus = completionSet.SelectionStatus;

            if (!(selectionStatus.Completion is SandcastleCompletion))
            {
                // Workaround some odd behavior in the completion when trying to enter "</".  This prevents it
                // from converting it to an XML comment ("<!--/-->").
                if (commitCharacter == '/' && selectionStatus.Completion.InsertionText == "!--")
                {
                    completionSession.Dismiss();
                }

                // let other providers handle their own completions
                return(false);
            }

            string insertionText = selectionStatus.Completion.InsertionText;

            completionSession.Commit();

            bool passCharacterToEditor;

            switch (commitCharacter)
            {
            case '/':
            case '>':
                // if the insertion text doesn't end with '>' or '/>', allow the user to complete the item and insert
                // the closing element character by typing '/' or '>'.
                passCharacterToEditor = !insertionText.EndsWith(">");
                break;

            case ' ':
                // only pass the space through if the completion item doesn't contain any replaceable elements
                passCharacterToEditor = insertionText.IndexOf('\xFF') < 0;
                break;

            case '\n':
            case '\t':
            default:
                // these items trigger completion, but aren't written to the output
                passCharacterToEditor = false;
                break;
            }

            return(!passCharacterToEditor);
        }
Ejemplo n.º 54
0
        public override void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            if (session == null || completionSets == null)
            {
                return;
            }

            ITrackingPoint triggerPoint = session.GetTriggerPoint(TextBuffer);

            if (triggerPoint != null)
            {
                IntellisenseController controller     = null;
                CompletionInfo         completionInfo = controller.CompletionInfo;
                ITextSnapshot          snapshot       = triggerPoint.TextBuffer.CurrentSnapshot;
                SnapshotPoint          point          = triggerPoint.GetPoint(snapshot);
                bool extendLeft = false;
                bool extend     = true;

                switch (completionInfo.InvocationType)
                {
                case IntellisenseInvocationType.Default:
                    extend = completionInfo.InfoType == CompletionInfoType.GlobalInfo;
                    break;

                case IntellisenseInvocationType.BackspaceDeleteOrBackTab:
                case IntellisenseInvocationType.IdentifierChar:
                case IntellisenseInvocationType.Sharp:
                case IntellisenseInvocationType.Space:
                case IntellisenseInvocationType.ShowMemberList:
                    break;

                default:
                    extendLeft = true;
                    break;
                }

                TextExtent extentOfWord = default(TextExtent);
                if (extend)
                {
                    ITextBuffer             textBuffer      = TextBuffer;
                    ITextStructureNavigator navigator       = TextStructureNavigatorSelectorService.CreateTextStructureNavigator(textBuffer, textBuffer.ContentType);
                    SnapshotPoint           currentPosition = new SnapshotPoint(snapshot, triggerPoint.GetPosition(snapshot));
                    extentOfWord = navigator.GetExtentOfWord(currentPosition);
                    if (extentOfWord.Span.Start == point)
                    {
                        TextExtent extentOfPreviousWord = navigator.GetExtentOfWord(currentPosition - 1);
                        if (extentOfPreviousWord.IsSignificant && extentOfPreviousWord.Span.End == point && IsCompletionPrefix(extentOfPreviousWord))
                        {
                            extentOfWord = extentOfPreviousWord;
                        }
                        else
                        {
                            extend = false;
                        }
                    }
                }

                if (!extend || !extentOfWord.IsSignificant)
                {
                    SnapshotSpan span = new SnapshotSpan(point, 0);
                    extentOfWord = new TextExtent(span, false);
                }

                if (completionInfo.InvocationType == IntellisenseInvocationType.BackspaceDeleteOrBackTab && extentOfWord.Span.Length > 0)
                {
                    string str3 = snapshot.GetText(extentOfWord.Span);
                    if (!string.IsNullOrWhiteSpace(str3))
                    {
                        while (CommitCharacters.IndexOf(str3[0]) > 0)
                        {
                            SnapshotSpan span2 = extentOfWord.Span;
                            SnapshotSpan span3 = new SnapshotSpan(snapshot, span2.Start + 1, span2.Length - 1);
                            extentOfWord = new TextExtent(span3, false);
                            str3         = snapshot.GetText(extentOfWord.Span);
                            if (string.IsNullOrEmpty(str3))
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        SnapshotSpan span4 = new SnapshotSpan(snapshot, extentOfWord.Span.End, 0);
                        extentOfWord = new TextExtent(span4, false);
                        completionInfo.InvocationType = IntellisenseInvocationType.Default;
                    }
                }

                ITrackingSpan applicableTo = snapshot.CreateTrackingSpan(extentOfWord.Span, SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward);
                if (extendLeft)
                {
                    SnapshotSpan textSoFarSpan = new SnapshotSpan(snapshot, extentOfWord.Span.Start, triggerPoint.GetPoint(snapshot));
                    string       textSoFar     = textSoFarSpan.GetText();
                    applicableTo = snapshot.CreateTrackingSpan(point.Position - textSoFar.Length, textSoFar.Length, SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward);
                }

                /* Context Tree
                 *
                 *  - Global
                 *    - Options
                 *    - Tokens
                 *    - AttributeScope
                 *      - ACTION
                 *    - Named Action
                 *      - ACTION
                 *    - Rule
                 *      - Arguments
                 *        - ARG_ACTION
                 *      - AttributeScope
                 *        - ACTION
                 *      - Named Action
                 *        - ACTION
                 *      - Options
                 *      - Alternative
                 *        - Alternative*
                 *        - Rewrite
                 *        - ACTION
                 */

                List <Completion> completions        = new List <Completion>();
                List <Completion> completionBuilders = new List <Completion>();

                List <IntellisenseContext> intellisenseContexts = GetIntellisenseContexts(triggerPoint);
                foreach (var context in intellisenseContexts)
                {
                    context.AugmentCompletionSession(session, completions, completionBuilders);
                }

                string        moniker       = "AntlrCompletions";
                string        displayName   = "ANTLR Completions";
                CompletionSet completionSet = new CompletionSet(moniker, displayName, applicableTo, completions, completionBuilders);
                completionSets.Add(completionSet);
            }
        }
Ejemplo n.º 55
0
		void RegisterCompletionSetEvents(CompletionSet completionSet) {
			UnregisterCompletionSetEvents();
			Debug.Assert(currentCompletionSet == null);
			currentCompletionSet = completionSet;
			if (completionSet != null)
				completionSet.SelectionStatusChanged += CompletionSet_SelectionStatusChanged;
		}
Ejemplo n.º 56
0
		ITrackingPoint GetTrackingPoint(CompletionSet coll) {
			var trackingSpan = coll.ApplicableTo;
			var snapshot = trackingSpan.TextBuffer.CurrentSnapshot;
			var point = trackingSpan.GetStartPoint(snapshot);
			return snapshot.CreateTrackingPoint(point.Position, PointTrackingMode.Negative);
		}
Ejemplo n.º 57
0
        public override CompletionSet GetCompletions(IGlyphService glyphService) {
            var start = _stopwatch.ElapsedMilliseconds;

            var line = Span.GetStartPoint(TextBuffer.CurrentSnapshot).GetContainingLine();
            var startPos = line.Start.Position + line.GetText().IndexOf("def");

            var analysis = GetAnalysisEntry();
            if (analysis == null) {
                return null;
            }

            var snapshot = TextBuffer.CurrentSnapshot;
            var pos = VsProjectAnalyzer.TranslateIndex(startPos, snapshot, analysis);

            var cls = analysis.GetDefinitionTree(pos).LastOrDefault(member => member.MemberType == Interpreter.PythonMemberType.Class);
            var members = analysis.GetOverrideable(pos).ToArray();
            var completions = members
                .Select(member => PythonCompletion(glyphService,
                    member.Name,
                    MakeCompletionString(member, cls.Name),
                    member.Documentation,
                    StandardGlyphGroup.GlyphGroupOverload));

            CompletionSet res;
            if (completions.Any()) {
                var set = new FuzzyCompletionSet(
                    "PythonOverrides",
                    "Python",
                    Span,
                    completions,
                    _options,
                    CompletionComparer.UnderscoresLast
                );
                set.CommitByDefault = false;
                res = set;
            } else {
                res = new CompletionSet();
            }

            var end = _stopwatch.ElapsedMilliseconds;

            if (/*Logging &&*/ end - start > TooMuchTime) {
                Trace.WriteLine(String.Format("{0} lookup time {1} for {2} classes", this, end - start, res.Completions.Count));
            }

            return res;
        }
Ejemplo n.º 58
0
		public void Start() {
			if (IsStarted)
				throw new InvalidOperationException();
			if (IsDismissed)
				throw new InvalidOperationException();
			IsStarted = true;
			completionSources = CreateCompletionSources();

			var list = new List<CompletionSet>();
			foreach (var source in completionSources)
				source.AugmentCompletionSession(this, list);
			foreach (var cc in list)
				completionSets.Add(cc);

			if (completionSets.Count == 0)
				Dismiss();
			else {
				SelectedCompletionSet = completionSets[0];
				completionPresenter = intellisensePresenterFactoryService.TryCreateIntellisensePresenter(this);
				if (completionPresenter == null) {
					Dismiss();
					return;
				}
				PresenterChanged?.Invoke(this, EventArgs.Empty);
				completionSessionCommandTargetFilter = new CompletionSessionCommandTargetFilter(this);
			}
		}
Ejemplo n.º 59
0
        private static List <Completion> GetCombinedSortedList(CompletionSet sparkCompletions, CompletionSet allCompletionsSet)
        {
            var combinedList = new List <Completion>();

            combinedList.AddRange(allCompletionsSet.Completions);
            combinedList.AddRange(sparkCompletions.Completions);
            combinedList.Sort((a, b) => a.DisplayText.CompareTo(b.DisplayText));
            return(combinedList);
        }
        void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            var tokenSpanPosition = FindTokenSpanAtPosition(session.GetTriggerPoint(m_textBuffer), session);
            var text = tokenSpanPosition.GetText(tokenSpanPosition.TextBuffer.CurrentSnapshot);

            m_compList = new List<Completion>();

            var output = BuildElements(text);

            if (!string.IsNullOrWhiteSpace(output))
            {
                m_compList.Add(new Completion(text, output, text, null, null));
            }

            var completionSet = new CompletionSet(
                "HTML",
                "HTML",
                tokenSpanPosition,
                m_compList,
                null);
            completionSets.Add(completionSet);
        }