public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (IsHtmlFile && completionSets.Any())
            {
                var bottomSpan = completionSets.First().ApplicableTo;
                if (!JScriptEditorUtil.IsInJScriptLanguageBlock(_lbm, bottomSpan.GetStartPoint(bottomSpan.TextBuffer.CurrentSnapshot)))
                {
                    // This is an HTML statement completion session, so do nothing
                    return;
                }
            }

            // TODO: Reflect over the ShimCompletionSet to see where the Description value comes from
            //       as setting the property does not actually change the value.
            var newCompletionSets = completionSets
                .Select(cs => cs == null ? cs : new ScriptCompletionSet(
                    cs.Moniker,
                    cs.DisplayName,
                    cs.ApplicableTo,
                    cs.Completions
                        .Select(c => c == null ? c : new Completion(
                            c.DisplayText,
                            c.InsertionText,
                            DocCommentHelper.ProcessParaTags(c.Description),
                            c.IconSource,
                            c.IconAutomationText))
                        .ToList(),
                    cs.CompletionBuilders))
                .ToList();
            
            completionSets.Clear();

            newCompletionSets.ForEach(cs => completionSets.Add(cs));
        }
Ejemplo n.º 2
0
 private ITrackingSpan FindTokenSpanAtPosition(ITrackingPoint point, ICompletionSession session)
 {
     SnapshotPoint currentPoint = (session.TextView.Caret.Position.BufferPosition);
     ITextStructureNavigator navigator = _provider.NavigatorService.GetTextStructureNavigator(_textBuffer);
     TextExtent extent = navigator.GetExtentOfWord(currentPoint);
     return currentPoint.Snapshot.CreateTrackingSpan(extent.Span, SpanTrackingMode.EdgeInclusive);
 }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            int position = session.TextView.Caret.Position.BufferPosition.Position;
            var line = _buffer.CurrentSnapshot.Lines.SingleOrDefault(l => l.Start <= position && l.End >= position);
            if (line == null) return;

            int linePos = position - line.Start.Position;

            var info = NodeModuleCompletionUtils.FindCompletionInfo(line.GetText(), linePos);
            if (info == null) return;

            var callingFilename = _buffer.GetFileName();
            var baseFolder = Path.GetDirectoryName(callingFilename);

            IEnumerable<Completion> results;
            if (String.IsNullOrWhiteSpace(info.Item1))
                results = GetRootCompletions(baseFolder);
            else
                results = GetRelativeCompletions(NodeModuleService.ResolvePath(baseFolder, info.Item1));

            var trackingSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(info.Item2.Start + line.Start, info.Item2.Length, SpanTrackingMode.EdgeInclusive);
            completionSets.Add(new CompletionSet(
                "Node.js Modules",
                "Node.js Modules",
                trackingSpan,
                results,
                null
            ));
        }
        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);
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (_disposed)
                return;

            ITextSnapshot snapshot = session.TextView.TextBuffer.CurrentSnapshot;
            SnapshotPoint? triggerPoint = session.GetTriggerPoint(snapshot);
            ClassificationSpan clsSpan;

            if (triggerPoint == null || !triggerPoint.HasValue || triggerPoint.Value.Position == 0 || !IsAllowed(triggerPoint.Value, out clsSpan))
                return;

            ITrackingSpan tracking = FindTokenSpanAtPosition(session);

            if (tracking == null)
                return;

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

            if (clsSpan != null && clsSpan.ClassificationType.IsOfType(PredefinedClassificationTypeNames.SymbolDefinition))
            {
                AddVariableCompletions(snapshot, tracking, completions);
            }
            //else if (!tracking.GetText(snapshot).Any(c => !char.IsLetter(c) && !char.IsWhiteSpace(c)))
            //{
            //    AddKeywordCompletions(completions);
            //}

            if (completions.Count > 0)
            {
                var ordered = completions.OrderBy(c => c.DisplayText);
                completionSets.Add(new CompletionSet("Cmd", "Cmd", tracking, ordered, Enumerable.Empty<Completion>()));
            }
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            int position = session.TextView.Caret.Position.BufferPosition.Position;
            var line = _buffer.CurrentSnapshot.Lines.SingleOrDefault(l => l.Start <= position && l.End > position);

            if (line != null)
            {
                string text = line.GetText();
                int tagIndex = text.IndexOf("getElementsByTagName(");
                int classIndex = text.IndexOf("getElementsByClassName(");
                int idIndex = text.IndexOf("getElementById(");

                CompletionSet set = null;

                if (tagIndex > -1 && position > line.Start + tagIndex)
                    set = GetElementsByTagName(completionSets, position, line, text, tagIndex + 21);
                if (classIndex > -1 && position > line.Start + classIndex)
                    set = GetElementsByClassName(completionSets, position, line, text, classIndex + 23);
                if (idIndex > -1 && position > line.Start + idIndex)
                    set = GetElementById(completionSets, position, line, text, idIndex + 15);

                if (set != null)
                {
                    completionSets.Clear();
                    completionSets.Add(set);
                }
            }
        }
        public CommandFilter(IWpfTextView textView, ICompletionBroker broker)
        {
            _currentSession = null;

            TextView = textView;
            Broker = broker;
        }
Ejemplo n.º 8
0
 public RCompletionContext(ICompletionSession session, ITextBuffer textBuffer, AstRoot ast, int position)
 {
     Session = session;
     TextBuffer = textBuffer;
     Position = position;
     AstRoot = ast;
 }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets) {
            var buffer = _textBuffer;
            var snapshot = buffer.CurrentSnapshot;
            var triggerPoint = session.GetTriggerPoint(buffer).GetPoint(snapshot);

            // Disable completions if user is editing a special command (e.g. ".cls") in the REPL.
            if (snapshot.TextBuffer.Properties.ContainsProperty(typeof(IReplEvaluator)) && snapshot.Length != 0 && snapshot[0] == '.') {
                return;
            }

            if (ShouldTriggerRequireIntellisense(triggerPoint, _classifier, true, true)) {
                AugmentCompletionSessionForRequire(triggerPoint, session, completionSets);
                return;
            }

            var textBuffer = _textBuffer;
            var span = GetApplicableSpan(session, textBuffer);
            var provider = VsProjectAnalyzer.GetCompletions(
                _textBuffer.CurrentSnapshot,
                span,
                session.GetTriggerPoint(buffer));

            var completions = provider.GetCompletions(_glyphService);
            if (completions != null && completions.Completions.Count > 0) {
                completionSets.Add(completions);
            }
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            var caretPosition = session.TextView.Caret.Position.BufferPosition.Position;
            var tokenTriggeringIntellisense = _tokenizedBuffer.CurrentState.FindTokenAtIndex(caretPosition);
            if (caretPosition == tokenTriggeringIntellisense.IndexToken.StartIndex) tokenTriggeringIntellisense = tokenTriggeringIntellisense.Previous();
            var numberOfCharactersBeforeCursor = caretPosition - tokenTriggeringIntellisense.IndexToken.StartIndex;
            var textFromSymbolBeforeCursor = tokenTriggeringIntellisense.IndexToken.Token.Text.Substring(0, numberOfCharactersBeforeCursor);
            var currentIndexToken = _tokenizedBuffer.CurrentState.FindTokenAtIndex(0);
            var completions = new List<Completion>();

            while (currentIndexToken != null)
            {
                if (currentIndexToken.IndexToken.StartIndex != tokenTriggeringIntellisense.IndexToken.StartIndex)
                {
                    if (currentIndexToken.Node.Value.Type == TokenType.Symbol && currentIndexToken.Node.Value.Text.StartsWith(textFromSymbolBeforeCursor))
                    {
                        if (completions.Find(c => c.DisplayText == currentIndexToken.Node.Value.Text) == null)
                        {
                            completions.Add(new Completion(currentIndexToken.Node.Value.Text));
                        }
                    }
                }

                currentIndexToken = currentIndexToken.Next();
            }

            var snapshot = session.TextView.TextSnapshot;
            var start = new SnapshotPoint(snapshot, tokenTriggeringIntellisense.IndexToken.StartIndex);
            var end = new SnapshotPoint(snapshot, start.Position + tokenTriggeringIntellisense.IndexToken.Token.Text.Length);
            var applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, end), SpanTrackingMode.EdgeInclusive);
            completionSets.Add(new CompletionSet("All", "All", applicableTo, completions, new List<Completion>()));
        }
Ejemplo n.º 11
0
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (_disposed)
                throw new ObjectDisposedException("XSharpCompletionSource");

            List<Completion> completions = new List<Completion>()
            {
                new Completion("SELF"),
                new Completion("FUNCTION"),
                new Completion("CLASS")
            };
            
            ITextSnapshot snapshot = _buffer.CurrentSnapshot;
            var triggerPoint = (SnapshotPoint)session.GetTriggerPoint(snapshot);

            if (triggerPoint == null)
                return;

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

            while (start > line.Start && !char.IsWhiteSpace((start - 1).GetChar()))
            {
                start -= 1;
            }

            var applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, triggerPoint), SpanTrackingMode.EdgeInclusive);

            // XSHARP : Disable Intellisense 
            //completionSets.Add(new CompletionSet("All", "All", applicableTo, completions, Enumerable.Empty<Completion>()));
        }
            /// <summary>
            /// Augment the completion session with the provided set of words if this completion session is 
            /// being created for a word completion session
            /// </summary>
            void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
            {
                var textView = session.TextView;

                // Only provide completion information for the ITextBuffer directly associated with the 
                // ITextView.  In a projcetion secnario there will be several ITextBuffer instances associated
                // with a given ITextView and we provide ICompletionSource values for all of them.  We want to
                // avoid creating duplicate completion information
                if (textView.TextBuffer != _textBuffer)
                {
                    return;
                }

                // Get out the collection of words.  If none is present then there is no information to
                // augment here
                CompletionData completionData;
                if (!textView.Properties.TryGetPropertySafe(_completionDataKey, out completionData) || completionData.WordCollection == null)
                {
                    return;
                }

                var trackingSpan = completionData.WordSpan.Snapshot.CreateTrackingSpan(
                    completionData.WordSpan.Span,
                    SpanTrackingMode.EdgeInclusive);
                var completions = completionData.WordCollection.Select(word => new Completion(word));
                var wordCompletionSet = new WordCompletionSet(trackingSpan, completions);
                completionSets.Add(wordCompletionSet);
            }
Ejemplo n.º 13
0
        protected override bool IsRetriggerChar(ICompletionSession session, char typedCharacter) {
            if (typedCharacter == ' ') {
                return true;
            }

            return base.IsRetriggerChar(session, typedCharacter);
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (!session.Properties.ContainsProperty(BufferProperties.SessionOriginIntellisense) || !session.TextView.TextBuffer.Properties.ContainsProperty(typeof(IList<CompletionResult>)))
            {
                return;
            }

            var textBuffer = session.TextView.TextBuffer;

            var trackingSpan = (ITrackingSpan)textBuffer.Properties.GetProperty(BufferProperties.LastWordReplacementSpan);
            var list = (IList<CompletionResult>)textBuffer.Properties.GetProperty(typeof(IList<CompletionResult>));
            var currentSnapshot = textBuffer.CurrentSnapshot;
            var filterSpan = currentSnapshot.CreateTrackingSpan(trackingSpan.GetEndPoint(currentSnapshot).Position, 0, SpanTrackingMode.EdgeInclusive);
            var lineStartToApplicableTo = (ITrackingSpan)textBuffer.Properties.GetProperty(BufferProperties.LineUpToReplacementSpan);

            Log.DebugFormat("TrackingSpan: {0}", trackingSpan.GetText(currentSnapshot));
            Log.DebugFormat("FilterSpan: {0}", filterSpan.GetText(currentSnapshot));

            var compList = new List<Completion>();
            foreach (var match in list)
            {
                var glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupUnknown, StandardGlyphItem.GlyphItemPublic);
                switch (match.ResultType)
                {
                    case CompletionResultType.ParameterName:
                        glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic);
                        break;
                    case CompletionResultType.Command:
                        glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
                        break;
                    case CompletionResultType.Type:
                        glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPublic);
                        break;
                    case CompletionResultType.Property:
                        glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic);
                        break;
                    case CompletionResultType.Method:
                        glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
                        break;
                    case CompletionResultType.Variable:
                        glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPublic);
                        break;
                    case  CompletionResultType.ProviderContainer:
                    case  CompletionResultType.ProviderItem:
                        glyph = _glyphs.GetGlyph(match.ResultType == CompletionResultType.ProviderContainer ? StandardGlyphGroup.GlyphOpenFolder : StandardGlyphGroup.GlyphLibrary, StandardGlyphItem.GlyphItemPublic);
                        break;
                }

                var completion = new Completion();
                completion.Description = match.ToolTip;
                completion.DisplayText = match.ListItemText;
                completion.InsertionText = match.CompletionText;
                completion.IconSource = glyph;
                completion.IconAutomationText = completion.Description;

                compList.Add(completion);
            }

            completionSets.Add(new PowerShellCompletionSet(string.Empty, string.Empty, trackingSpan, compList, null, filterSpan, lineStartToApplicableTo));
        }
Ejemplo n.º 15
0
		public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets) {
			var snapshot = session.TextView.TextSnapshot;
			var triggerPoint = session.GetTriggerPoint(snapshot);
			if (triggerPoint == null)
				return;
			var info = CompletionInfo.Create(snapshot);
			if (info == null)
				return;

			// This helps a little to speed up the code
			ProfileOptimizationHelper.StartProfile("roslyn-completion-" + info.Value.CompletionService.Language);

			CompletionTrigger completionTrigger;
			session.Properties.TryGetProperty(typeof(CompletionTrigger), out completionTrigger);

			var completionList = info.Value.CompletionService.GetCompletionsAsync(info.Value.Document, triggerPoint.Value.Position, completionTrigger).GetAwaiter().GetResult();
			if (completionList == null)
				return;
			Debug.Assert(completionList.Span.End <= snapshot.Length);
			if (completionList.Span.End > snapshot.Length)
				return;
			var trackingSpan = snapshot.CreateTrackingSpan(completionList.Span.Start, completionList.Span.Length, SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward);
			var completionSet = RoslynCompletionSet.Create(imageMonikerService, mruCompletionService, completionList, info.Value.CompletionService, session.TextView, DefaultCompletionSetMoniker, dnSpy_Roslyn_Shared_Resources.CompletionSet_All, trackingSpan);
			completionSets.Add(completionSet);
		}
Ejemplo n.º 16
0
        public async System.Threading.Tasks.Task CollectCompletionSets(ICompletionSession newSession)
        {
            JavaEditor javaEditor = null;
            if (TextBuffer.Properties.TryGetProperty<JavaEditor>(typeof(JavaEditor), out javaEditor) &&
                javaEditor.TypeRootIdentifier != null)
            {
                var textReader = new TextSnapshotToTextReader(TextBuffer.CurrentSnapshot) as TextReader;
                var autocompleteRequest = ProtocolHandlers.CreateAutocompleteRequest(
                        textReader, 
                        javaEditor.TypeRootIdentifier, 
                        newSession.GetTriggerPoint(TextBuffer).GetPosition(TextBuffer.CurrentSnapshot));
                var autocompleteResponse = await javaEditor.JavaPkgServer.Send(javaEditor, autocompleteRequest);

                if (autocompleteResponse.responseType == Protocol.Response.ResponseType.Autocomplete && 
                    autocompleteResponse.autocompleteResponse != null)
                {
                    if (autocompleteResponse.autocompleteResponse.status && autocompleteResponse.autocompleteResponse.proposals.Count != 0)
                    {
                        CompletionSetList = new List<CompletionSet>();
                        var list = TransformCompletions(TextBuffer.CurrentSnapshot, autocompleteResponse.autocompleteResponse.proposals);
                        CompletionSetList.Add(new CompletionSet("Autocomplete", "Autocomplete", GetReplacementSpanFromCompletions(TextBuffer.CurrentSnapshot, autocompleteResponse.autocompleteResponse.proposals.First()), list, null)); // FindTokenSpanAtPosition(newSession.GetTriggerPoint(TextBuffer), newSession), list, null));
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            // if we don't have a stylesheet for the document yet, there isn't much we can do
            var stylesheet = Editor.Document.Stylesheet;
            if (stylesheet == null)
                return;

            // TODO: signal to cache that we are in an intellisense session and thus we do not want
            // to update the cache until we are done

            var span = FindTokenSpanAtPosition(session);
            var position = span.GetSpan(session.TextView.TextSnapshot).Start.Position;
            var context = CreateCompletionContext(stylesheet, position, session.TextView.TextSnapshot);
            var types = CalculateApplicableContexts(context);

            var values = (
                from type in types
                from provider in IntellisenseManager.ValueProvidersFor(type)
                from value in provider.GetCompletions(type, context)
                select value
            );

            var set = Compiler.Compile(span, values);
            if (set.Completions.Count > 0)
                completionSets.Add(set);
        }
Ejemplo n.º 18
0
    void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
    {
      var fileModel = VsUtils.TryGetFileModel(_textBuffer);

      if (fileModel == null)
        return;

      var client  = fileModel.Server.Client;
      var triggerPoint = session.GetTriggerPoint(_textBuffer);
      var snapshot = _textBuffer.CurrentSnapshot;
      var version = snapshot.Version.Convert();

      client.Send(new ClientMessage.CompleteWord(fileModel.Id, version, triggerPoint.GetPoint(snapshot).Position));
      var result = client.Receive<ServerMessage.CompleteWord>();
      var span = result.replacementSpan;
      var applicableTo = snapshot.CreateTrackingSpan(new Span(span.StartPos, span.Length), SpanTrackingMode.EdgeInclusive);

      var completions = new List<Completion>();

      CompletionElem.Literal literal;
      CompletionElem.Symbol  symbol;

      foreach (var elem in result.completionList)
      {
        if ((literal = elem as CompletionElem.Literal) != null)
          completions.Add(new Completion(literal.text, literal.text, "literal", null, null));
        else if ((symbol = elem as CompletionElem.Symbol) != null)
          completions.Add(new Completion(symbol.name, symbol.name, symbol.description, null, null));
      }

      completionSets.Add(new CompletionSet("NitraWordCompletion", "Nitra word completion", applicableTo, completions, null));
    }
        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);
        }
        private static SnapshotSpan GetLineSpan(AutoCompletionSource source, ICompletionSession session)
        {
            var currentPoint = (session.TextView.Caret.Position.BufferPosition) - 1;
            var lineStart = source.TextBuffer.CurrentSnapshot.GetText().LastIndexOf('\n', currentPoint) + 1;

            return new SnapshotSpan(source.TextBuffer.CurrentSnapshot, lineStart, currentPoint - lineStart + 1);
        }
		internal static bool ShowCompletion(ITextView view)
		{
			bool result = false;
			if (ISESnippetSessionManager.activeSession != null)
			{
				ISESnippetSessionManager.activeSession.Dismiss();
			}
			EditorImports.CompletionBroker.DismissAllSessions(view);
			if (!CommandImplementation.CanShowSnippet())
			{
				return result;
			}
			ISESnippetSessionManager.activeSession = EditorImports.CompletionBroker.TriggerCompletion(view);
			if (ISESnippetSessionManager.activeSession == null)
			{
				return result;
			}
			ISESnippetSessionManager.activeSession.Committed += ISESnippetSessionManager.eventHandlerSessionCommitted;
			ISESnippetSessionManager.activeSession.Dismissed += ISESnippetSessionManager.eventHandlerSessionDismissed;
			ISESnippetSessionManager.activeSession.SelectedCompletionSet.SelectionStatusChanged += ISESnippetSessionManager.eventHandlerSelectionChanged;
			ISESnippetSessionManager.activeSession.SelectedCompletionSet.SelectionStatus = new CompletionSelectionStatus(ISESnippetSessionManager.activeSession.SelectedCompletionSet.Completions[0], true, true);
			ISESnippetSessionManager.selectedSnippet = (ISESnippetSessionManager.activeSession.SelectedCompletionSet.SelectionStatus.Completion.Properties["SnippetInfo"] as ISESnippet);
			ISESnippetSessionManager.insertSpan = ISESnippetSessionManager.activeSession.SelectedCompletionSet.ApplicableTo;
			ISESnippetSessionManager.canFilter = true;
			return true;
		}
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            var position = session.GetTriggerPoint(_buffer).GetPoint(_buffer.CurrentSnapshot);
            var line = position.GetContainingLine();

            if (line == null)
                return;

            string text = line.GetText();
            var linePosition = position - line.Start;

            foreach (var source in completionSources)
            {
                var span = source.GetInvocationSpan(text, linePosition, position);
                if (span == null) continue;

                var trackingSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(span.Value.Start + line.Start, span.Value.Length, SpanTrackingMode.EdgeInclusive);
                completionSets.Add(new StringCompletionSet(
                    source.GetType().Name,
                    trackingSpan,
                    source.GetEntries(quoteChar: text[span.Value.Start], caret: session.TextView.Caret.Position.BufferPosition)
                ));
            }
            // TODO: Merge & resort all sets?  Will StringCompletionSource handle other entries?
            //completionSets.SelectMany(s => s.Completions).OrderBy(c=>c.DisplayText.TrimStart('"','\''))
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            var position = session.GetTriggerPoint(this.textBuffer).GetPoint(this.textBuffer.CurrentSnapshot);
            var line = position.GetContainingLine();

            if (line == null)
            {
                return;
            }

            int linePos = position - line.Start.Position;

            var info = UIRouterStateCompletionUtils.FindCompletionInfo(line.GetText(), linePos);
            if (info == null)
            {
                return;
            }

            var callingFilename = this.textBuffer.GetFileName();
            var appHierarchy = this.ngHierarchyProvider.Get(callingFilename);

            IEnumerable<Completion> results = null;
            results = this.GetCompletions(appHierarchy);

            var trackingSpan = this.textBuffer.CurrentSnapshot.CreateTrackingSpan(info.Item2.Start + line.Start, info.Item2.Length, SpanTrackingMode.EdgeInclusive);
            completionSets.Add(new CompletionSet(
                "Angular views",
                "Angular views",
                trackingSpan,
                results,
                null
            ));
        }
        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)
        {
            var position = session.GetTriggerPoint(_buffer).GetPoint(_buffer.CurrentSnapshot);
            var line = position.GetContainingLine();

            if (line == null) return;

            int linePos = position - line.Start.Position;

            var info = GruntTaskCompletionUtils.FindCompletionInfo(line.GetText(), linePos);
            if (info == null) return;

            var callingFilename = _buffer.GetFileName();
            var baseFolder = Path.GetDirectoryName(callingFilename);

            IEnumerable<Intel.Completion> results = new List<Intel.Completion>();
            if (String.IsNullOrWhiteSpace(info.Item1))
                results = GetRootCompletions(baseFolder);

            var trackingSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(info.Item2.Start + line.Start, info.Item2.Length, SpanTrackingMode.EdgeInclusive);
            completionSets.Add(new CompletionSet(
                "Node.js Modules",
                "Node.js Modules",
                trackingSpan,
                results,
                null
            ));

        }
Ejemplo n.º 26
0
 private ITrackingSpan FindSpanAtCurrentPositionFrom(ICompletionSession session)
 {
     var currentPoint = (session.TextView.Caret.Position.BufferPosition) - 1;
     var navigator = provider.NavigatorService.GetTextStructureNavigator(buffer);
     var extent = navigator.GetExtentOfWord(currentPoint);
     return currentPoint.Snapshot.CreateTrackingSpan(extent.Span, SpanTrackingMode.EdgeInclusive);
 }
Ejemplo n.º 27
0
        public override void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets) {
            var doc = HtmlEditorDocument.FromTextBuffer(_buffer);
            if (doc == null) {
                return;
            }
            doc.HtmlEditorTree.EnsureTreeReady();

            var primarySnapshot = doc.PrimaryView.TextSnapshot;
            var nullableTriggerPoint = session.GetTriggerPoint(primarySnapshot);
            if (!nullableTriggerPoint.HasValue) {
                return;
            }
            var triggerPoint = nullableTriggerPoint.Value;

            var artifacts = doc.HtmlEditorTree.ArtifactCollection;
            var index = artifacts.GetItemContaining(triggerPoint.Position);
            if (index < 0) {
                return;
            }

            var artifact = artifacts[index] as TemplateArtifact;
            if (artifact == null) {
                return;
            }

            var artifactText = doc.HtmlEditorTree.ParseTree.Text.GetText(artifact.InnerRange);
            artifact.Parse(artifactText);

            ITrackingSpan applicableSpan;
            var completionSet = GetCompletionSet(session.GetOptions(_analyzer._serviceProvider), _analyzer, artifact.TokenKind, artifactText, artifact.InnerRange.Start, triggerPoint, out applicableSpan);
            completionSets.Add(completionSet);
        }
        public VsctCompletionController(IWpfTextView textView, ICompletionBroker broker)
        {
            _currentSession = null;

            TextView = textView;
            Broker = broker;
        }
        void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            int position = session.GetTriggerPoint(session.TextView.TextBuffer).GetPosition(textBuffer.CurrentSnapshot);
            int line = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(position);
            int column = position - textBuffer.CurrentSnapshot.GetLineFromPosition(position).Start.Position;

            Microsoft.VisualStudio.IronPythonInference.Modules modules = new Microsoft.VisualStudio.IronPythonInference.Modules();

            IList<Declaration> attributes;
            if (textBuffer.GetReadOnlyExtents(new Span(0, textBuffer.CurrentSnapshot.Length)).Count > 0)
            {
                int start;
                var readWriteText = TextOfLine(textBuffer, line, column, out start, true);
                var module = modules.AnalyzeModule(new QuietCompilerSink(), textBuffer.GetFileName(), readWriteText);

                attributes = module.GetAttributesAt(1, column - 1);

                foreach (var attribute in GetEngineAttributes(readWriteText, column - start - 1))
                {
                    attributes.Add(attribute);
                }
            }
            else
            {
                var module = modules.AnalyzeModule(new QuietCompilerSink(), textBuffer.GetFileName(), textBuffer.CurrentSnapshot.GetText());

                attributes = module.GetAttributesAt(line + 1, column);
            }

            completionSets.Add(GetCompletions((List<Declaration>)attributes, session));
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (_disposed)
                return;

            List<Completion> completions = new List<Completion>();
            foreach (string item in RobotsTxtClassifier._valid)
            {
                completions.Add(new Completion(item, item, null, _glyph, item));
            }

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

            if (triggerPoint == null)
                return;

            var line = triggerPoint.GetContainingLine();
            string text = line.GetText();
            int index = text.IndexOf(':');
            int hash = text.IndexOf('#');
            SnapshotPoint start = triggerPoint;

            if (hash > -1 && hash < triggerPoint.Position || (index > -1 && (start - line.Start.Position) > index))
                return;

            while (start > line.Start && !char.IsWhiteSpace((start - 1).GetChar()))
            {
                start -= 1;
            }

            var applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, triggerPoint), SpanTrackingMode.EdgeInclusive);

            completionSets.Add(new CompletionSet("All", "All", applicableTo, completions, Enumerable.Empty<Completion>()));
        }
 /// <summary>
 ///   Determines which <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.CompletionSet" />s should be part of the specified <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.ICompletionSession" />.
 /// </summary>
 /// <param name = "session">The session for which completions are to be computed.</param>
 /// <param name = "completionSets">The set of the completionSets to be added to the session.</param>
 /// <remarks>
 ///   Each applicable <see cref = "M:Microsoft.VisualStudio.Language.Intellisense.ICompletionSource.AugmentCompletionSession(Microsoft.VisualStudio.Language.Intellisense.ICompletionSession,System.Collections.Generic.IList{Microsoft.VisualStudio.Language.Intellisense.CompletionSet})" /> instance will be called in-order to
 ///   (re)calculate a <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.ICompletionSession" />.  <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.CompletionSet" />s can be added to the session by adding
 ///   them to the completionSets collection passed-in as a parameter.  In addition, by removing items from the collection, a
 ///   source may filter <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.CompletionSet" />s provided by <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.ICompletionSource" />s earlier in the calculation
 ///   chain.
 /// </remarks>
 public override void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
 {
     UpdateDefaultCompletionSet(session, completionSets, Completions);
 }
Ejemplo n.º 32
0
 void OnActiveSessionDismissed(object sender, System.EventArgs e)
 {
     detachKeyboardFilter();
     activeSession = null;
 }
Ejemplo n.º 33
0
 private void OnSessionDismissed(object sender, EventArgs e)
 {
     m_session.Dismissed -= this.OnSessionDismissed;
     m_session            = null;
 }
Ejemplo n.º 34
0
 private void CompletionSession_Dismissed(object sender, EventArgs e)
 {
     Debug.Assert(_completionSession == sender);
     _completionSession.Dismissed -= CompletionSession_Dismissed;
     _completionSession            = null;
 }
Ejemplo n.º 35
0
        void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            SourceText sourceText   = this.m_sourceTextCache.Get(this.m_textBuffer.CurrentSnapshot);
            SyntaxTree syntaxTree   = this.m_parseTreeCache.Get(sourceText);
            var        triggerPoint = (SnapshotPoint)session.GetTriggerPoint(this.m_textBuffer.CurrentSnapshot);
            //var ch = triggerPoint.GetChar();
            Token currentToken      = null;
            int   currentTokenIndex = 0;

            for (; currentTokenIndex < syntaxTree.Tokens.Count; currentTokenIndex++)
            {
                var token = syntaxTree.Tokens[currentTokenIndex];
                if ((token.Start <= triggerPoint.Position) && (token.Start + token.Length) >= triggerPoint.Position)
                {
                    currentToken = token;
                    break;
                }
            }
            List <string> strList = new List <string>();

            if (currentToken == null)
            {
                return;
            }

            if (currentToken.Kind == SyntaxKind.Dot)
            {
                //user inputs dot. Try search members
                var targetname = syntaxTree.Tokens[currentTokenIndex - 1].Text;
                for (int i = 0; i < syntaxTree.StatementNodeList.Count; i++)
                {
                    var statement = syntaxTree.StatementNodeList[i];
                    if (statement.StartPosition + statement.Length < triggerPoint.Position) //make sure the variable is declared before the usage
                    {
                        if (statement.GetType() == typeof(AssignmentStatementNode))
                        {
                            for (int j = 0; j < statement.Children[2].Children.Count; j++)
                            {
                                if (statement.Children.Count > 2)
                                {
                                    var child = statement.Children[2].Children[j];
                                    if (child.GetType() == typeof(TableConstructorExp))
                                    {
                                        if (statement.Children[0].Children[j].Children[0].IsLeafNode && ((Token)(statement.Children[0].Children[j].Children[0])).Text == targetname)
                                        {
                                            foreach (var assignment in child.Children[1].Children)
                                            {
                                                if (assignment.GetType() == typeof(AssignmentField))
                                                {
                                                    strList.Add(((Token)assignment.Children[0]).Text);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else if (statement.GetType() == typeof(LocalAssignmentStatementNode))
                        {
                            if (statement.Children.Count > 3)
                            {
                                for (int j = 0; j < statement.Children[3].Children.Count; j++)
                                {
                                    var child = statement.Children[3].Children[j];
                                    if (child.GetType() == typeof(TableConstructorExp))
                                    {
                                        if (statement.Children[1].Children[j].IsLeafNode && ((Token)(statement.Children[1].Children[j])).Text == targetname)
                                        {
                                            foreach (var assignment in child.Children[1].Children)
                                            {
                                                if (assignment.GetType() == typeof(AssignmentField))
                                                {
                                                    strList.Add(((Token)assignment.Children[0]).Text);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                this.m_memberlist = true;
            }
            else
            {
                //list all variables and keywords
                //strList.Add("and");
                //strList.Add("break");
                //strList.Add("do");
                //strList.Add("else");
                //strList.Add("elseif");
                //strList.Add("end");
                //strList.Add("false");
                strList.Add("for");
                strList.Add("function");
                strList.Add("if");
                //strList.Add("in");
                strList.Add("local");
                //strList.Add("nil");
                //strList.Add("not");
                //strList.Add("or");
                //strList.Add("repeat");
                //strList.Add("return");
                //strList.Add("then");
                //strList.Add("true");
                //strList.Add("until");
                strList.Add("while");
                foreach (var statement in syntaxTree.StatementNodeList)
                {
                    if (statement.StartPosition + statement.Length < triggerPoint.Position) //make sure the variable is declared before the usage
                    {
                        if (statement.GetType() == typeof(AssignmentStatementNode))
                        {
                            var namelist = statement.Children[0];
                            foreach (var namevar in namelist.Children)
                            {
                                if (namevar.GetType() == typeof(NameVar))
                                {
                                    var str = ((Token)((NameVar)namevar).Children[0]).Text;
                                    if (strList.IndexOf(str) == -1)
                                    {
                                        strList.Add(str);
                                    }
                                }
                            }
                        }
                        else if (statement.GetType() == typeof(LocalAssignmentStatementNode))
                        {
                            foreach (var namevar in ((SeparatedList)statement.Children[1]).Children)
                            {
                                if (namevar.IsLeafNode)
                                {
                                    var str = ((Token)namevar).Text;
                                    if (strList.IndexOf(str) == -1)
                                    {
                                        strList.Add(str);
                                    }
                                }
                            }
                        }
                    }
                }
                this.m_memberlist = false;
            }
            strList.Sort();
            this.m_compList = new List <Completion>();
            foreach (string str in strList)
            {
                this.m_compList.Add(new Completion(str, str, str, null, null));
            }

            completionSets.Add(new CompletionSet(
                                   "Tokens", // the non-localized title of the tab
                                   "Tokens", // the display title of the tab
                                   this.FindTokenSpanAtPosition(session.GetTriggerPoint(this.m_textBuffer),
                                                                session),
                                   this.m_compList,
                                   null));
        }
Ejemplo n.º 36
0
        public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            Metadata metadata;

            _textBuffer.Properties.TryGetProperty(typeof(Metadata), out metadata);
            if (metadata == null)
            {
                return;
            }

            var pos   = session.TextView.Caret.Position.BufferPosition;
            var text  = pos.Snapshot.GetText(0, pos.Position);
            var state = XmlParser.Parse(text);


            var completions = new List <Completion>();

            _helper.SetMetadata(metadata, _textBuffer.CurrentSnapshot.GetText());

            var curStart = state.CurrentValueStart ?? 0;

            if (state.State == XmlParser.ParserState.StartElement)
            {
                var tagName = state.TagName;
                if (tagName.Contains("."))
                {
                    var dotPos   = tagName.IndexOf(".");
                    var typeName = tagName.Substring(0, dotPos);
                    var compName = tagName.Substring(dotPos + 1, 0);
                    curStart = curStart + dotPos + 1;
                    completions.AddRange(_helper.FilterPropertyNames(typeName, compName).Select(p => new Completion(p)));
                }
                else
                {
                    completions.AddRange(_helper.FilterTypeNames(tagName).Select(x => new Completion(x)));
                }
            }
            else if (state.State == XmlParser.ParserState.InsideElement ||
                     state.State == XmlParser.ParserState.StartAttribute)
            {
                if (state.State == XmlParser.ParserState.InsideElement)
                {
                    curStart = pos.Position; //Force completion to be started from current cursor position
                }
                if (state.AttributeName?.Contains(".") == true)
                {
                    var dotPos = state.AttributeName.IndexOf('.');
                    curStart += dotPos + 1;
                    var split = state.AttributeName.Split(new[] { '.' }, 2);
                    completions.AddRange(_helper.FilterPropertyNames(split[0], split[1], true)
                                         .Select(x => new Completion(x, x + "=\"\"", x, null, null)));
                }
                else
                {
                    completions.AddRange(_helper.FilterPropertyNames(state.TagName, state.AttributeName).Select(x => new Completion(x, x + "=\"\"", x, null, null)));
                    completions.AddRange(
                        _helper.FilterTypeNames(state.AttributeName, true)
                        .Select(v => new Completion(v, v + ". ", v, null, null)));
                }


                session.Committed += delegate
                {
                    session.TextView.Caret.MoveToPreviousCaretPosition();
                    //Automagically trigger new completion for attribute enums
                    ((CompletionCommandHandler)session.TextView.Properties[typeof(CompletionCommandHandler)])
                    .TriggerNew();
                };
            }
            else if (state.State == XmlParser.ParserState.AttributeValue)
            {
                MetadataProperty prop;
                if (state.AttributeName.Contains("."))
                {
                    //Attached property
                    var split = state.AttributeName.Split('.');
                    prop = _helper.LookupProperty(split[0], split[1]);
                }
                else
                {
                    prop = _helper.LookupProperty(state.TagName, state.AttributeName);
                }

                //Markup extension, ignore everything else
                if (state.AttributeValue.StartsWith("{"))
                {
                    curStart = state.CurrentValueStart.Value +
                               BuildCompletionsForMarkupExtension(completions,
                                                                  text.Substring(state.CurrentValueStart.Value));
                }
                else
                {
                    if (prop?.Type == MetadataPropertyType.Enum && prop.EnumValues != null)
                    {
                        completions.AddRange(prop.EnumValues.Select(v => new Completion(v)));
                    }
                    else if (state.AttributeName == "xmlns" || state.AttributeName.Contains("xmlns:"))
                    {
                        if (state.AttributeValue.StartsWith("clr-namespace:"))
                        {
                            completions.AddRange(
                                metadata.Namespaces.Keys.Where(v => v.StartsWith(state.AttributeValue))
                                .Select(v => new Completion(v)));
                        }
                        else
                        {
                            completions.Add(new Completion("clr-namespace:"));
                            completions.AddRange(
                                metadata.Namespaces.Keys.Where(
                                    v =>
                                    v.StartsWith(state.AttributeValue) &&
                                    !"clr-namespace".StartsWith(state.AttributeValue))
                                .Select(v => new Completion(v)));
                        }
                    }
                }
            }

            if (completions.Count != 0)
            {
                var span = new SnapshotSpan(pos.Snapshot, curStart, pos.Position - curStart);
                completionSets.Insert(0, new CompletionSet("Perspex", "Perspex",
                                                           pos.Snapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeInclusive), completions, null));
            }
        }
 private void OnDismissed(object sender, EventArgs e)
 {
     _currentSession.Dismissed -= OnDismissed;
     _currentSession.Committed -= OnCommitted;
     _currentSession            = null;
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Does a loose scan of the surrounding code to determine the completion context, and returns a list of meaningful completions.
        /// </summary>
        /// <param name="completionSession">The current completion session.</param>
        /// <param name="completionSets">The target list to store the generated completion sets into.</param>
        public void AugmentCompletionSession(ICompletionSession completionSession, IList <CompletionSet> completionSets)
        {
            // Run text parser, skip all tokens behind the current word
            SnapshotPoint cursorPoint = (completionSession.TextView.Caret.Position.BufferPosition) - 1;
            var           tokens      = _aiParser.GetTokens(cursorPoint, true).SkipWhile(t => t.StartPoint > cursorPoint);

            // Check whether we are in a comment or in a string; skip the current word
            AiToken firstToken = tokens.First();

            if (firstToken.Type == AiTokenTypes.Comment || firstToken.Type == AiTokenTypes.String)
            {
                return;
            }
            if (firstToken.Type != AiTokenTypes.OpeningBrace)
            {
                tokens = tokens.Skip(1);
            }

            // Go backwards and find "(" with known keyword or "=>"
            CurrentCompletionContext completionContext = CurrentCompletionContext.Unknown;
            int            closingBraceCount           = 0;
            List <AiToken> tokensTillFirstOpeningBrace = new List <AiToken>();

            Constants.CommandDefinition commandDefinition = null; // Used for storing the parameter type list of a fact/action.
            bool encounteredOpeningBrace = false;

            foreach (AiToken token in tokens)
            {
                // Check token type
                switch (token.Type)
                {
                case AiTokenTypes.OpeningBrace:
                {
                    // Found an opening brace, set flag to stop copying tokens
                    if (!encounteredOpeningBrace)
                    {
                        encounteredOpeningBrace = true;
                    }
                    else
                    {
                        --closingBraceCount;
                    }
                    break;
                }

                case AiTokenTypes.ClosingBrace:
                {
                    // If a closing brace is encountered before an opening one, an error must have occured
                    if (encounteredOpeningBrace)
                    {
                        ++closingBraceCount;
                    }
                    else
                    {
                        completionContext = CurrentCompletionContext.Error;
                    }
                    break;
                }

                case AiTokenTypes.Defconst:
                case AiTokenTypes.Load:
                case AiTokenTypes.LoadRandom:
                {
                    // These commands hint a top level context, but completion within one of them is not supported
                    if (encounteredOpeningBrace)
                    {
                        completionContext = CurrentCompletionContext.TopLevel;
                    }
                    else
                    {
                        completionContext = CurrentCompletionContext.NotSupported;
                    }
                    break;
                }

                case AiTokenTypes.Defrule:
                case AiTokenTypes.BooleanFactName:
                {
                    // If an opening brace was found, we have a fact
                    if (encounteredOpeningBrace)
                    {
                        completionContext = CurrentCompletionContext.RuleFacts;
                    }
                    else
                    {
                        completionContext = CurrentCompletionContext.Error;     // "defrule" has no parameters
                    }
                    break;
                }

                case AiTokenTypes.RuleArrow:
                {
                    // If an opening brace was found, we have an action
                    if (encounteredOpeningBrace && closingBraceCount == 0)
                    {
                        completionContext = CurrentCompletionContext.RuleActions;
                    }
                    else if (encounteredOpeningBrace && closingBraceCount == 1)
                    {
                        completionContext = CurrentCompletionContext.TopLevel;
                    }
                    else
                    {
                        completionContext = CurrentCompletionContext.Error;     // "=>" has no parameters
                    }
                    break;
                }

                case AiTokenTypes.FactName:
                {
                    // We probably have a fact/action with parameter list
                    if (!encounteredOpeningBrace)
                    {
                        // Get parameter list
                        commandDefinition = Constants.AiRuleFacts[token.Content];
                        completionContext = CurrentCompletionContext.Parameters;
                    }
                    // TODO error state if directly in front of a brace
                    break;
                }

                case AiTokenTypes.ActionName:
                {
                    // We probably have a fact/action with parameter list
                    if (!encounteredOpeningBrace)
                    {
                        // Get parameter list
                        commandDefinition = Constants.AiRuleActions[token.Content];
                        completionContext = CurrentCompletionContext.Parameters;
                    }
                    // TODO error state if directly in front of a brace
                    break;
                }

                case AiTokenTypes.Word:
                case AiTokenTypes.Number:
                case AiTokenTypes.String:
                {
                    // Put this token into the list to determine the current parameter position of a given fact or action
                    if (!encounteredOpeningBrace)
                    {
                        tokensTillFirstOpeningBrace.Add(token);
                    }
                    // TODO error state if directly in front of a brace
                    break;
                }
                }

                // Stop if a context was deduced or an error occured
                if (completionContext != CurrentCompletionContext.Unknown)
                {
                    break;
                }
            }

            // Handle input at document start
            if (completionContext == CurrentCompletionContext.Unknown && encounteredOpeningBrace)
            {
                completionContext = CurrentCompletionContext.TopLevel;
            }

            // Show completion set depending on current context
            switch (completionContext)
            {
            case CurrentCompletionContext.TopLevel:
                completionSets.Add(new CompletionSet("Commands", "Commands", GetTrackingSpan(firstToken.StartPoint, cursorPoint), _aiTopLevelKeywordCompletions, null));
                break;

            case CurrentCompletionContext.RuleFacts:
                completionSets.Add(new CompletionSet("Facts", "Facts", GetTrackingSpan(firstToken.StartPoint, cursorPoint), _aiFactCompletions, null));
                break;

            case CurrentCompletionContext.RuleActions:
                completionSets.Add(new CompletionSet("Actions", "Actions", GetTrackingSpan(firstToken.StartPoint, cursorPoint), _aiActionCompletions, null));
                break;

            case CurrentCompletionContext.Parameters:
            {
                // Compare scanned parameters with parameter list
                tokensTillFirstOpeningBrace.Reverse();
                if (tokensTillFirstOpeningBrace.Count > commandDefinition.Parameters.Count())
                {
                    break;
                }
                int i = 0;
                foreach (string parameterType in commandDefinition.Parameters)
                {
                    // Reached current parameter?
                    if (i == tokensTillFirstOpeningBrace.Count)
                    {
                        // Show completion list, if there is one
                        if (Constants.AiCommandParameters.ContainsKey(parameterType))
                        {
                            completionSets.Add(new CompletionSet("Parameter", "Parameter values", GetTrackingSpan(firstToken.StartPoint, cursorPoint), _aiCommandParameterCompletions[parameterType], null));
                        }
                        break;
                    }
                    else
                    {
                        // Check type
                        AiToken token = tokensTillFirstOpeningBrace[i];
                        if (parameterType == "string" && token.Type != AiTokenTypes.String)
                        {
                            goto case CurrentCompletionContext.Error;
                        }
                        else if (parameterType == "value" && token.Type != AiTokenTypes.Number)
                        {
                            goto case CurrentCompletionContext.Error;
                        }
                        else if (Constants.AiCommandParameters.ContainsKey(parameterType) && !Constants.AiCommandParameters[parameterType].PossibleValues.Contains(token.Content))
                        {
                            goto case CurrentCompletionContext.Error;
                        }
                    }
                    ++i;
                }
                break;
            }

            case CurrentCompletionContext.Error:
                // Do nothing
                break;
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Triggers Statement completion when appropriate keys are pressed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void VisualElement_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            // Make sure that this event happened on the same text view to which we're attached.
            ITextView textView = sender as ITextView;

            if (this.textView != textView)
            {
                return;
            }

            // if there is a session already leave it be
            if (activeSession != null)
            {
                return;
            }

            // determine which subject buffer is affected by looking at the caret position
            SnapshotPoint?caret = textView.Caret.Position.Point.GetPoint
                                      (textBuffer => buffer == textBuffer, PositionAffinity.Predecessor);

            // return if no suitable buffer found
            if (!caret.HasValue)
            {
                return;
            }

            SnapshotPoint caretPoint = caret.Value;

            var subjectBuffer = caretPoint.Snapshot.TextBuffer;

            CompletionContext completionContext =
                AbstractCompletionSet.GetCompletionContext(e.Key, subjectBuffer, caretPoint.Position);

            if (completionContext == CompletionContext.None)
            {
                return;
            }

            // the invocation occurred in a subject buffer of interest to us
            triggerPosition = caretPoint.Position;
            ITrackingPoint triggerPoint = caretPoint.Snapshot.CreateTrackingPoint(triggerPosition, PointTrackingMode.Negative);

            completionSpan = caretPoint.Snapshot.CreateTrackingSpan(caretPoint.Position, 0, SpanTrackingMode.EdgeInclusive);

            // attach filter to intercept the Enter key
            attachKeyboardFilter();

            // Create a completion session
            activeSession = provider.CompletionBroker.CreateCompletionSession(textView, triggerPoint, true);

            // Put the completion context and original (empty) completion span
            // on the session so that it can be used by the completion source
            activeSession.Properties.AddProperty(typeof(CompletionContext), completionContext);
            activeSession.Properties.AddProperty(typeof(Controller), completionSpan);

            // Attach to the session events
            activeSession.Dismissed += new System.EventHandler(OnActiveSessionDismissed);
            activeSession.Committed += new System.EventHandler(OnActiveSessionCommitted);

            // Start the completion session. The intellisense will be triggered.
            activeSession.Start();
        }
Ejemplo n.º 40
0
        public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            var textBuffer = session.TextView.TextBuffer;

            if (!session.Properties.ContainsProperty(BufferProperties.SessionOriginIntellisense) ||
                !textBuffer.Properties.ContainsProperty(BufferProperties.LastWordReplacementSpan) ||
                !textBuffer.Properties.ContainsProperty(typeof(IList <CompletionResult>)) ||
                !textBuffer.Properties.ContainsProperty(BufferProperties.LineUpToReplacementSpan))
            {
                return;
            }

            ITrackingSpan            trackingSpan;
            IList <CompletionResult> list;
            ITrackingSpan            lineStartToApplicableTo;

            textBuffer.Properties.TryGetProperty <ITrackingSpan>(BufferProperties.LastWordReplacementSpan, out trackingSpan);
            textBuffer.Properties.TryGetProperty <IList <CompletionResult> >(typeof(IList <CompletionResult>), out list);
            textBuffer.Properties.TryGetProperty <ITrackingSpan>(BufferProperties.LineUpToReplacementSpan, out lineStartToApplicableTo);

            var currentSnapshot      = textBuffer.CurrentSnapshot;
            var trackingSpanEndPoint = trackingSpan.GetEndPoint(currentSnapshot);

            // When IntelliSense for path completion is triggered in double quotes, the quotes are both part of completion, which makes the endpoint of tracking span not boudary of the final completion.
            var  endCharPoint             = trackingSpanEndPoint - 1;
            char trackingSpanEndPointChar = endCharPoint.GetChar();

            if (trackingSpanEndPointChar == '\"')
            {
                trackingSpanEndPoint = endCharPoint;
            }
            var filterSpan = currentSnapshot.CreateTrackingSpan(trackingSpanEndPoint, 0, SpanTrackingMode.EdgeInclusive);

            var compList = new List <Completion>();

            foreach (var match in list)
            {
                var glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupUnknown, StandardGlyphItem.GlyphItemPublic);
                switch (match.ResultType)
                {
                case CompletionResultType.ParameterName:
                    glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemPublic);
                    break;

                case CompletionResultType.ParameterValue:
                    glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupEnumMember, StandardGlyphItem.GlyphItemPublic);
                    break;

                case CompletionResultType.Command:
                    glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
                    break;

                case CompletionResultType.Type:
                    glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPublic);
                    break;

                case CompletionResultType.Property:
                    glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic);
                    break;

                case CompletionResultType.Method:
                    glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
                    break;

                case CompletionResultType.Variable:
                    glyph = _glyphs.GetGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPublic);
                    break;

                case CompletionResultType.ProviderContainer:
                case CompletionResultType.ProviderItem:
                    glyph = _glyphs.GetGlyph(match.ResultType == CompletionResultType.ProviderContainer ? StandardGlyphGroup.GlyphOpenFolder : StandardGlyphGroup.GlyphLibrary, StandardGlyphItem.GlyphItemPublic);
                    break;
                }

                var completion = new Completion();
                completion.Description        = match.ToolTip;
                completion.DisplayText        = match.ListItemText;
                completion.InsertionText      = match.CompletionText;
                completion.IconSource         = glyph;
                completion.IconAutomationText = completion.Description;

                compList.Add(completion);
            }

            completionSets.Add(new PowerShellCompletionSet(string.Empty, string.Empty, trackingSpan, compList, null, filterSpan, lineStartToApplicableTo));
        }
Ejemplo n.º 41
0
        public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            //AsmDudeToolsStatic.Output_INFO(string.Format("{0}:AugmentCompletionSession", this.ToString()));

            if (!Settings.Default.CodeCompletion_On)
            {
                return;
            }

            try
            {
                DateTime      time1        = DateTime.Now;
                ITextSnapshot snapshot     = this._buffer.CurrentSnapshot;
                SnapshotPoint triggerPoint = (SnapshotPoint)session.GetTriggerPoint(snapshot);
                if (triggerPoint == null)
                {
                    return;
                }
                ITextSnapshotLine line = triggerPoint.GetContainingLine();

                //1] check if current position is in a remark; if we are in a remark, no code completion
                #region
                if (triggerPoint.Position > 1)
                {
                    char currentTypedChar = (triggerPoint - 1).GetChar();
                    //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession: current char = "+ currentTypedChar);
                    if (!currentTypedChar.Equals('#'))
                    { //TODO UGLY since the user can configure this starting character
                        int pos = triggerPoint.Position - line.Start;
                        if (AsmSourceTools.IsInRemark(pos, line.GetText()))
                        {
                            //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession: currently in a remark section");
                            return;
                        }
                        else
                        {
                            // AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession: not in a remark section");
                        }
                    }
                }
                #endregion

                //2] find the start of the current keyword
                #region
                SnapshotPoint start = triggerPoint;
                while ((start > line.Start) && !AsmTools.AsmSourceTools.IsSeparatorChar((start - 1).GetChar()))
                {
                    start -= 1;
                }
                #endregion

                //3] get the word that is currently being typed
                #region
                ITrackingSpan applicableTo   = snapshot.CreateTrackingSpan(new SnapshotSpan(start, triggerPoint), SpanTrackingMode.EdgeInclusive);
                string        partialKeyword = applicableTo.GetText(snapshot);
                bool          useCapitals    = AsmDudeToolsStatic.Is_All_Upper(partialKeyword);

                string   lineStr  = line.GetText();
                var      t        = AsmSourceTools.ParseLine(lineStr);
                Mnemonic mnemonic = t.Mnemonic;

                //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession; lineStr="+ lineStr+ "; t.Item1="+t.Item1);

                string previousKeyword = AsmDudeToolsStatic.Get_Previous_Keyword(line.Start, start).ToUpper();

                if (mnemonic == Mnemonic.NONE)
                {
                    //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession; lineStr=" + lineStr + "; previousKeyword=" + previousKeyword);

                    if (previousKeyword.Equals("INVOKE")) //TODO INVOKE is a MASM keyword not a NASM one...
                    {
                        // Suggest a label
                        var completions = this.Label_Completions(useCapitals, false);
                        if (completions.Any <Completion>())
                        {
                            completionSets.Add(new CompletionSet("Labels", "Labels", applicableTo, completions, Enumerable.Empty <Completion>()));
                        }
                    }
                    else
                    {
                        {
                            ISet <AsmTokenType> selected1 = new HashSet <AsmTokenType> {
                                AsmTokenType.Directive, AsmTokenType.Jump, AsmTokenType.Misc, AsmTokenType.Mnemonic
                            };
                            var completions1 = this.Selected_Completions(useCapitals, selected1, true);
                            if (completions1.Any <Completion>())
                            {
                                completionSets.Add(new CompletionSet("All", "All", applicableTo, completions1, Enumerable.Empty <Completion>()));
                            }
                        }
                        if (false)
                        {
                            ISet <AsmTokenType> selected2 = new HashSet <AsmTokenType> {
                                AsmTokenType.Jump, AsmTokenType.Mnemonic
                            };
                            var completions2 = this.Selected_Completions(useCapitals, selected2, false);
                            if (completions2.Any <Completion>())
                            {
                                completionSets.Add(new CompletionSet("Instr", "Instr", applicableTo, completions2, Enumerable.Empty <Completion>()));
                            }
                        }
                        if (false)
                        {
                            ISet <AsmTokenType> selected3 = new HashSet <AsmTokenType> {
                                AsmTokenType.Directive, AsmTokenType.Misc
                            };
                            var completions3 = this.Selected_Completions(useCapitals, selected3, true);
                            if (completions3.Any <Completion>())
                            {
                                completionSets.Add(new CompletionSet("Directive", "Directive", applicableTo, completions3, Enumerable.Empty <Completion>()));
                            }
                        }
                    }
                }
                else
                { // the current line contains a mnemonic
                  //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession; mnemonic=" + mnemonic+ "; previousKeyword="+ previousKeyword);

                    if (AsmSourceTools.IsJump(AsmSourceTools.ParseMnemonic(previousKeyword, true)))
                    {
                        //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession; previous keyword is a jump mnemonic");
                        // previous keyword is jump (or call) mnemonic. Suggest "SHORT" or a label
                        var completions = this.Label_Completions(useCapitals, true);
                        if (completions.Any <Completion>())
                        {
                            completionSets.Add(new CompletionSet("Labels", "Labels", applicableTo, completions, Enumerable.Empty <Completion>()));
                        }
                    }
                    else if (previousKeyword.Equals("SHORT") || previousKeyword.Equals("NEAR"))
                    {
                        // Suggest a label
                        var completions = this.Label_Completions(useCapitals, false);
                        if (completions.Any <Completion>())
                        {
                            completionSets.Add(new CompletionSet("Labels", "Labels", applicableTo, completions, Enumerable.Empty <Completion>()));
                        }
                    }
                    else
                    {
                        IList <Operand>         operands = AsmSourceTools.MakeOperands(t.Args);
                        ISet <AsmSignatureEnum> allowed  = new HashSet <AsmSignatureEnum>();
                        int commaCount = AsmSignature.Count_Commas(lineStr);
                        IEnumerable <AsmSignatureElement> allSignatures = this._asmDudeTools.Mnemonic_Store.GetSignatures(mnemonic);

                        ISet <Arch> selectedArchitectures = AsmDudeToolsStatic.Get_Arch_Swithed_On();
                        foreach (AsmSignatureElement se in AsmSignatureHelpSource.Constrain_Signatures(allSignatures, operands, selectedArchitectures))
                        {
                            if (commaCount < se.Operands.Count)
                            {
                                foreach (AsmSignatureEnum s in se.Operands[commaCount])
                                {
                                    allowed.Add(s);
                                }
                            }
                        }
                        var completions = this.Mnemonic_Operand_Completions(useCapitals, allowed, line.LineNumber);
                        if (completions.Any <Completion>())
                        {
                            completionSets.Add(new CompletionSet("All", "All", applicableTo, completions, Enumerable.Empty <Completion>()));
                        }
                    }
                }
                #endregion
                AsmDudeToolsStatic.Print_Speed_Warning(time1, "Code Completion");
            }
            catch (Exception e)
            {
                AsmDudeToolsStatic.Output_ERROR(string.Format("{0}:AugmentCompletionSession; e={1}", this.ToString(), e.ToString()));
            }
        }
 internal StringLiteralCompletionList(IServiceProvider serviceProvider, ICompletionSession session, ITextView view, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
     : base(serviceProvider, session, view, span, textBuffer, options)
 {
 }
        public static bool DoCallMatch(IntellisenseController completionTarget)
        {
            Contract.Requires <ArgumentNullException>(completionTarget != null, "completionTarget");

#if true
            return(false);
#else
            bool flag2 = false;
            ICompletionSession session = completionTarget.CompletionSession;
            if (session != null)
            {
                ITextSnapshot snapshot = session.TextView.TextSnapshot;
                string        text     = snapshot.GetText(completionTarget.CompletionInfo.ApplicableTo.GetSpan(snapshot));
                if (string.IsNullOrEmpty(text))
                {
                    return(false);
                }

                session.Match();
                CompletionSet set1  = null;
                CompletionSet set2  = null;
                CompletionSet set3  = null;
                CompletionSet set4  = null;
                bool          flag3 = false;
                bool          flag4 = false;
                foreach (CompletionSet set in session.CompletionSets.Where(i => i != null && i.SelectionStatus != null && i.SelectionStatus.Completion != null))
                {
                    flag2 = true;
                    bool isAllTab = false;
                    if (isAllTab)
                    {
                        set3  = set;
                        flag3 = string.Equals(text, set.SelectionStatus.Completion.DisplayText, StringComparison.CurrentCultureIgnoreCase);
                    }
                    else
                    {
                        set4  = set;
                        flag4 = string.Equals(text, set.SelectionStatus.Completion.DisplayText, StringComparison.CurrentCultureIgnoreCase);
                    }
                }

                if (flag3 && !flag4)
                {
                    set1 = set3;
                }
                else if (set2 != null)
                {
                    if (set2 != set3 && set4 == null)
                    {
                        set1 = set3;
                    }
                }
                else if (set4 != null)
                {
                    set1 = set4;
                }
                else
                {
                    set1 = set3;
                }

                if (set1 != null)
                {
                    session.SelectedCompletionSet = set1;
                }
            }

            return(flag2);
#endif
        }
Ejemplo n.º 44
0
 internal OverrideCompletionAnalysis(PythonEditorServices services, ICompletionSession session, ITextView view, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
     : base(services, session, view, span, textBuffer, options)
 {
 }
Ejemplo n.º 45
0
        public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            var triggerPoint = session.GetTriggerPoint(m_textBuffer.CurrentSnapshot).GetValueOrDefault();

            bool inMeta;
            var  tracker = TrackUE4MacroSpecifier(triggerPoint, out inMeta);

            if (tracker == null)
            {
                return;
            }

            if (tracker.MacroConst == UE4Macros.UPROPERTY)
            {
                if (inMeta)
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UPropertyMeta",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.UMP, tracker.MetaSpecifiers),
                                           null));
                }
                else
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UProperty",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.UP, tracker.Specifiers),
                                           null));
                }
            }
            if (tracker.MacroConst == UE4Macros.UCLASS)
            {
                if (inMeta)
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UClassMeta",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.UMC, tracker.MetaSpecifiers),
                                           null));
                }
                else
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UClass",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.UC, tracker.Specifiers),
                                           null));
                }
            }
            if (tracker.MacroConst == UE4Macros.UINTERFACE)
            {
                if (inMeta)
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UInterfaceMeta",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.UMI, tracker.MetaSpecifiers),
                                           null));
                }
                else
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UInterface",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.UI, tracker.Specifiers),
                                           null));
                }
            }
            if (tracker.MacroConst == UE4Macros.UFUNCTION)
            {
                if (inMeta)
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UFunctionMeta",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.UMF, tracker.MetaSpecifiers),
                                           null));
                }
                else
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UFunction",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.UF, tracker.Specifiers),
                                           null));
                }
            }
            if (tracker.MacroConst == UE4Macros.USTRUCT)
            {
                if (inMeta)
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UStructMeta",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.UMS, tracker.MetaSpecifiers),
                                           null));
                }
                else
                {
                    completionSets.Add(new CompletionSet(
                                           "ue4",
                                           "UStruct",
                                           FindTokenSpanAtPosition(triggerPoint),
                                           ConstructCompletions(UE4SpecifiersSource.US, tracker.Specifiers),
                                           null));
                }
            }
            session.SelectedCompletionSetChanged += SessionSelectedCompletionSetChanged;
        }
Ejemplo n.º 46
0
 void CurSessionDismissedOrCommitted(object sender, EventArgs e)
 {
     _curSession = null;
 }
Ejemplo n.º 47
0
        public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            if (session == null || completionSets == null)
            {
                return;
            }

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

            SyntaxTree tree         = this.source.Tree;
            Snapshot   snapshot     = this.source.CurrentSnapshot;
            int        triggerPoint = session.GetTriggerPoint(this.textBuffer).GetPosition(snapshot);

            if (tree != null)
            {
                List <Definition> definitions = new List <Definition>();

                foreach (string key in tree.Definitions.Keys)
                {
                    Definition definition = tree.Definitions[key].Find(def => def.Scope.Contains(snapshot, triggerPoint));

                    if (definition != null)
                    {
                        definitions.Add(definition);
                    }
                }

                SyntaxNode node            = tree.GetNodeFromPosition(snapshot, triggerPoint);
                Definition currentFunction = null;

                foreach (SyntaxNode ancestor in node.Ancestors)
                {
                    if (ancestor.SyntaxType == SyntaxType.FunctionDefinition)
                    {
                        FunctionDefinitionSyntax function = ancestor as FunctionDefinitionSyntax;

                        currentFunction = function.FunctionHeader.Identifier.Definition;
                        break;
                    }
                }

                for (int i = 0; i < definitions.Count; i++)
                {
                    if (definitions[i].Name != currentFunction?.Name)
                    {
                        int overloads = definitions[i].Overloads.Count;

                        if (BuiltInData.Instance.Definitions.ContainsKey(definitions[i].Name.Text))
                        {
                            overloads += BuiltInData.Instance.Definitions[definitions[i].Name.Text].Count;
                        }

                        completions.Add(new GLSLCompletion(definitions[i].ToTextBlock(this.formatMap, this.provider.TypeRegistry, definitions[i].Overloads.Count - 1), definitions[i], definitions[i].GetImageSource(this.provider.GlyphService)));
                    }
                }
            }

            for (int i = 0; i < builtIn.Count; i++)
            {
                if (!completions.Contains(completion => completion.DisplayText == builtIn[this.source.Type][i].DisplayText))
                {
                    completions.Add(builtIn[this.source.Type][i]);
                }
            }

            ITrackingSpan span = this.FindTokenSpanAtPosition(session);

            completions.Sort((first, second) => string.Compare(first.DisplayText, second.DisplayText, System.StringComparison.Ordinal));

            completionSets.Add(new CompletionSet("GLSL", "GLSL", span, completions, null));
        }
Ejemplo n.º 48
0
 internal WordLegacyCompletionSession(ITrackingSpan wordTrackingSpan, IIntellisenseSessionStack intellisenseSessionStack, ICompletionSession completionSession, WordLegacyCompletionSet wordCompletionSet)
 {
     _textView                     = completionSession.TextView;
     _wordTrackingSpan             = wordTrackingSpan;
     _wordCompletionSet            = wordCompletionSet;
     _completionSession            = completionSession;
     _completionSession.Dismissed += delegate { OnDismissed(); };
     _intellisenseSessionStack     = intellisenseSessionStack;
 }
Ejemplo n.º 49
0
 public MyCompletionSet(string moniker, string displayName, ITrackingSpan applicableTo, ICollection <Completion> completions, IEnumerable <Completion> completionBuilders, ICompletionSession session) : base(moniker, displayName, applicableTo, completions, completionBuilders)
 {
     _items   = completions;
     _session = session;
 }
Ejemplo n.º 50
0
 internal NormalCompletionAnalysis(PythonEditorServices services, ICompletionSession session, ITextView view, ITextSnapshot snapshot, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
     : base(services, session, view, span, textBuffer, options)
 {
     _snapshot = snapshot;
 }
Ejemplo n.º 51
0
		void CompletionSession_Dismissed(object sender, EventArgs e) {
			var session = (ICompletionSession)sender;
			session.Dismissed -= CompletionSession_Dismissed;
			if (completionSession == session)
				completionSession = null;
		}
Ejemplo n.º 52
0
 private void SessionOnDismissed(object sender, EventArgs e)
 {
     _session = null;
 }
Ejemplo n.º 53
0
 private FromImportCompletionAnalysis(string[] ns, bool includeStar, IServiceProvider serviceProvider, ICompletionSession session, ITextView view, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
     : base(serviceProvider, session, view, span, textBuffer, options)
 {
     _namespace   = ns;
     _includeStar = includeStar;
 }
Ejemplo n.º 54
0
 public static string[] GetInsertionTexts(this ICompletionSession completionSession)
 {
     return(completionSession.CompletionSets.First().Completions.Select(x => x.InsertionText).ToArray());
 }
 void OnActiveSessionDismissed(object sender, System.EventArgs e)
 {
     this.subjectTextView.Properties.GetProperty <TextViewEventManager>(TextViewEventManager.Key).OnIntellisenseSessionEnd(new EventArgs());
     activeSession = null;
 }
Ejemplo n.º 56
0
        public static CompletionAnalysis Make(IList <ClassificationSpan> tokens, IServiceProvider serviceProvider, ICompletionSession session, ITextView view, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
        {
            Debug.Assert(tokens[0].Span.GetText() == "from");

            var  ns          = new List <string>();
            bool nsComplete  = false;
            bool seenImport  = false;
            bool seenName    = false;
            bool seenAs      = false;
            bool seenAlias   = false;
            bool includeStar = true;

            foreach (var token in tokens.Skip(1))
            {
                if (token == null || token.Span.End > span.GetEndPoint(textBuffer.CurrentSnapshot).Position)
                {
                    break;
                }

                if (!seenImport)
                {
                    if (token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier))
                    {
                        ns.Add(token.Span.GetText());
                        nsComplete = true;
                    }
                    else if (token.ClassificationType.IsOfType(PythonPredefinedClassificationTypeNames.Dot))
                    {
                        nsComplete = false;
                    }
                    seenImport = IsKeyword(token, "import");
                }
                else if (token.ClassificationType.IsOfType(PythonPredefinedClassificationTypeNames.Comma))
                {
                    seenName    = false;
                    seenAs      = false;
                    seenAlias   = false;
                    includeStar = false;
                }
                else if (token.Span.GetText() == "*")
                {
                    // Nothing comes after a star
                    return(EmptyCompletionContext);
                }
                else if (IsKeyword(token, "as"))
                {
                    seenAs = true;
                }
                else if (token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier))
                {
                    if (seenAlias)
                    {
                        return(EmptyCompletionContext);
                    }
                    else if (seenAs)
                    {
                        seenAlias = true;
                    }
                    else if (seenName)
                    {
                        return(EmptyCompletionContext);
                    }
                    else
                    {
                        seenName = true;
                    }
                }
                else
                {
                    includeStar = false;
                }
            }
            if (!seenImport)
            {
                if (nsComplete)
                {
                    return(new ImportKeywordCompletionAnalysis(serviceProvider, session, view, span, textBuffer, options));
                }
                else
                {
                    return(ImportCompletionAnalysis.Make(tokens, serviceProvider, session, view, span, textBuffer, options));
                }
            }

            if (!nsComplete || seenAlias || seenAs)
            {
                return(EmptyCompletionContext);
            }

            if (seenName)
            {
                return(new AsKeywordCompletionAnalysis(serviceProvider, session, view, span, textBuffer, options));
            }

            return(new FromImportCompletionAnalysis(ns.ToArray(), includeStar, serviceProvider, session, view, span, textBuffer, options));
        }
Ejemplo n.º 57
0
 internal OverrideCompletionAnalysis(IServiceProvider serviceProvider, ICompletionSession session, ITextView view, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
     : base(serviceProvider, session, view, span, textBuffer, options)
 {
 }
Ejemplo n.º 58
0
 public ImportKeywordCompletionAnalysis(IServiceProvider serviceProvider, ICompletionSession session, ITextView view, ITrackingSpan span, ITextBuffer buffer, CompletionOptions options)
     : base(serviceProvider, session, view, span, buffer, options)
 {
 }
        public void PresentItems(
            ITrackingSpan triggerSpan,
            IList <CompletionItem> completionItems,
            CompletionItem selectedItem,
            CompletionItem suggestionModeItem,
            bool suggestionMode,
            bool isSoftSelected,
            ImmutableArray <CompletionItemFilter> completionItemFilters,
            string filterText)
        {
            AssertIsForeground();

            // check if this update is still relevant
            if (_textView.IsClosed || _isDismissed)
            {
                return;
            }

            if (triggerSpan != null)
            {
                _completionSet.SetTrackingSpan(triggerSpan);
            }

            _ignoreSelectionStatusChangedEvent = true;
            try
            {
                _completionSet.SetCompletionItems(
                    completionItems, selectedItem, suggestionModeItem, suggestionMode,
                    isSoftSelected, completionItemFilters, filterText);
            }
            finally
            {
                _ignoreSelectionStatusChangedEvent = false;
            }

            if (_editorSessionOpt == null)
            {
                // We're tracking the caret.  Don't have the editor do it.
                // Map the span instead of a point to avoid affinity problems.
                _editorSessionOpt = _completionBroker.CreateCompletionSession(
                    _textView,
                    triggerSpan.GetStartTrackingPoint(PointTrackingMode.Negative),
                    trackCaret: false);

                if (_textView is IDebuggerTextView debugTextView && !debugTextView.IsImmediateWindow)
                {
                    debugTextView.HACK_StartCompletionSession(_editorSessionOpt);
                }

                _editorSessionOpt.Dismissed += (s, e) => OnEditorSessionDismissed();

                // So here's the deal.  We cannot create the editor session and give it the right
                // items (even though we know what they are).  Instead, the session will call
                // back into the ICompletionSourceProvider (which is us) to get those values. It
                // will pass itself along with the calls back into ICompletionSourceProvider.
                // So, in order to make that connection work, we add properties to the session
                // so that we can call back into ourselves, get the items and add it to the
                // session.
                _editorSessionOpt.Properties.AddProperty(Key, this);
                _editorSessionOpt.Start();
            }

            // Call so that the editor will refresh the completion text to embolden.
            _editorSessionOpt?.Match();
        }
Ejemplo n.º 60
0
 /// <summary>
 /// Returns a list of completions.
 /// </summary>
 /// <param name="session">The completion session.</param>
 /// <returns>A list of completions.</returns>
 internal abstract List <Completion> GetCompletions(ICompletionSession session);