Exemple #1
0
        /// <summary>
        /// Formats statement that the caret is at
        /// </summary>
        public static void FormatCurrentStatement(ITextView textView, ITextBuffer textBuffer, IEditorShell editorShell, bool limitAtCaret = false, int caretOffset = 0)
        {
            SnapshotPoint?caretPoint = REditorDocument.MapCaretPositionFromView(textView);

            if (!caretPoint.HasValue)
            {
                return;
            }
            IREditorDocument document = REditorDocument.TryFromTextBuffer(textBuffer);

            if (document != null)
            {
                ITextSnapshot snapshot = textBuffer.CurrentSnapshot;
                AstRoot       ast      = document.EditorTree.AstRoot;
                IAstNode      node     = ast.GetNodeOfTypeFromPosition <IStatement>(Math.Max(0, caretPoint.Value + caretOffset)) as IAstNode;
                FormatNode(textView, textBuffer, editorShell, node, limit: caretPoint.Value);
            }
        }
Exemple #2
0
        internal BraceMatchingTagger(ITextView view, ITextBuffer sourceBuffer)
        {
            //here the keys are the open braces, and the values are the close braces
            _braceList = new Dictionary <char, char>
            {
                ['{']  = '}',
                ['[']  = ']',
                ['(']  = ')',
                ['\''] = '\'',
                ['"']  = '"'
            };
            View         = view;
            SourceBuffer = sourceBuffer;
            CurrentChar  = null;

            View.Caret.PositionChanged += CaretPositionChanged;
            View.LayoutChanged         += ViewLayoutChanged;
        }
            private async Task RecomputeTagsAsync(
                object oldState,
                SnapshotPoint?caretPosition,
                TextChangeRange?textChangeRange,
                ImmutableArray <DocumentSnapshotSpan> spansToTag,
                ImmutableDictionary <ITextBuffer, TagSpanIntervalTree <TTag> > oldTagTrees,
                bool initialTags,
                CancellationToken cancellationToken)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var context = new TaggerContext <TTag>(
                    oldState, spansToTag, caretPosition, textChangeRange, oldTagTrees, cancellationToken);

                await ProduceTagsAsync(context).ConfigureAwait(false);

                ProcessContext(oldTagTrees, context, initialTags);
            }
        private void OnTextViewMouseHover(object sender, MouseHoverEventArgs e)
        {
            SnapshotPoint?point = this.GetMousePosition(new SnapshotPoint(_textView.TextSnapshot, e.Position));

            if (point != null)
            {
                ITrackingPoint triggerPoint = point.Value.Snapshot.CreateTrackingPoint(point.Value.Position,
                                                                                       PointTrackingMode.Positive);

                // Find the broker for this buffer

                if (!_componentContext.QuickInfoBroker.IsQuickInfoActive(_textView))
                {
                    _session = _componentContext.QuickInfoBroker.CreateQuickInfoSession(_textView, triggerPoint, true);
                    _session.Start();
                }
            }
        }
Exemple #5
0
        private void TriggerCompletion()
        {
            // Caret must be in a non-projection location
            SnapshotPoint?caretPoint = _mTextView.Caret.Position.Point.GetPoint(
                textBuffer => !textBuffer.ContentType.IsOfType("projection"), PositionAffinity.Predecessor);

            if (!caretPoint.HasValue)
            {
                return;
            }

            _mSession = _mProvider.CompletionBroker.CreateCompletionSession(_mTextView,
                                                                            caretPoint.Value.Snapshot.CreateTrackingPoint(caretPoint.Value.Position, PointTrackingMode.Positive), true);

            // Subscribe to the Dismissed event on the session
            _mSession.Dismissed += OnSessionDismissed;
            _mSession.Start();
        }
Exemple #6
0
        /// <summary>
        /// Formats statement that the caret is at
        /// </summary>
        public static void FormatCurrentStatement(ITextView textView, ITextBuffer textBuffer)
        {
            SnapshotPoint?caretPoint = MapCaretToBuffer(textView, textBuffer);

            if (!caretPoint.HasValue)
            {
                return;
            }
            IREditorDocument document = REditorDocument.TryFromTextBuffer(textBuffer);

            if (document != null)
            {
                ITextSnapshot snapshot = textBuffer.CurrentSnapshot;
                AstRoot       ast      = document.EditorTree.AstRoot;
                IAstNode      node     = ast.GetNodeOfTypeFromPosition <IStatement>(Math.Max(0, caretPoint.Value - 1)) as IAstNode;
                FormatNode(textView, textBuffer, node);
            }
        }
Exemple #7
0
        void UpdateAtCaretPosition()
        {
            // Check for disposal, this can be disposed while waiting for idle
            if (_textView != null && _braceMatcher != null)
            {
                var caretPosition = _textView.Caret.Position;
                _currentChar = caretPosition.Point.GetPoint(_textBuffer, caretPosition.Affinity);

                // We need to clear current highlight if caret went to another buffer

                _highlighted = false;
                if (TagsChanged != null)
                {
                    TagsChanged(this, new SnapshotSpanEventArgs(new SnapshotSpan(_textBuffer.CurrentSnapshot, 0,
                                                                                 _textBuffer.CurrentSnapshot.Length)));
                }
            }
        }
Exemple #8
0
        public TextExtent GetExtentOfWord(SnapshotPoint currentPosition)
        {
            SnapshotPoint?point = _textBuffer.MapDown(currentPosition, RContentTypeDefinition.ContentType);

            if (point.HasValue)
            {
                Span?span = RTextStructure.GetWordSpan(point.Value.Snapshot, point.Value.Position);
                if (span.HasValue && span.Value.Length > 0)
                {
                    var viewSpan = _textBuffer.MapUp(span.Value, RContentTypeDefinition.ContentType);
                    if (viewSpan.HasValue)
                    {
                        return(new TextExtent(viewSpan.Value, isSignificant: true));
                    }
                }
            }
            return(_plainTextNavigator.GetExtentOfWord(currentPosition));
        }
Exemple #9
0
        internal TaggerContext(
            object state,
            ImmutableArray <DocumentSnapshotSpan> spansToTag,
            SnapshotPoint?caretPosition,
            TextChangeRange?textChangeRange,
            ImmutableDictionary <ITextBuffer, TagSpanIntervalTree <TTag> > existingTags,
            CancellationToken cancellationToken
            )
        {
            this.State             = state;
            this.SpansToTag        = spansToTag;
            this.CaretPosition     = caretPosition;
            this.TextChangeRange   = textChangeRange;
            this.CancellationToken = cancellationToken;

            _spansTagged  = spansToTag;
            _existingTags = existingTags;
        }
Exemple #10
0
            private void UpdateAtCaretPosition(CaretPosition caretPosition)
            {
                SnapshotPoint?point = caretPosition.Point.GetPoint(SourceBuffer, caretPosition.Affinity);

                if (point == null)
                {
                    return;
                }

                if (_highlightedSpans?.FirstOrDefault().Snapshot == SourceBuffer.CurrentSnapshot &&
                    (_highlightedSpans?.Any(s => s.Contains(point.Value)) ?? false))
                {
                    return;
                }

                NormalizedSnapshotSpanCollection newHighlightedSpans = null;

                this.HtmlDocument.HtmlEditorTree.GetPositionElement(point.Value.Position, out _, out AttributeNode attribute);

                if ((attribute?.ValueRangeUnquoted.Contains(point.Value.Position) ?? false) ||
                    (attribute?.ValueRangeUnquoted.End == point.Value.Position))
                {
                    if (attribute.Name?.Equals("class", StringComparison.InvariantCultureIgnoreCase) ?? false)
                    {
                        int relativeIndex = point.Value.Position - attribute.ValueRangeUnquoted.Start;

                        // find definitions
                        string @class = ClassRegex.Matches(attribute.Value)
                                        .Cast <Match>()
                                        .FirstOrDefault(m => m.Index <= relativeIndex && relativeIndex <= m.Index + m.Length)?
                                        .Value;

                        // find references
                        if (@class != null)
                        {
                            newHighlightedSpans = new NormalizedSnapshotSpanCollection(FindReferences(@class, point.Value.Snapshot));
                        }
                    }
                }

                _highlightedSpans = newHighlightedSpans;

                TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(new SnapshotSpan(SourceBuffer.CurrentSnapshot, 0, SourceBuffer.CurrentSnapshot.Length)));
            }
Exemple #11
0
        /// <summary>
        /// Given an IWpfTextView, find the position of the caret and report its column
        /// number. The column number is 0-based
        /// </summary>
        /// <param name="textView">The text view containing the caret</param>
        /// <returns>The column number of the caret's position. When the caret is at the
        /// leftmost column, the return value is zero.</returns>
        private static string GetCaretWord(IWpfTextView textView, ITextStructureNavigator textStructureNavigator)
        {
            var           caretPosition = textView.Caret.Position;
            var           sourceBuffer  = textView.TextBuffer;
            SnapshotPoint?point         = caretPosition.Point.GetPoint(sourceBuffer, caretPosition.Affinity);

            if (!point.HasValue)
            {
                return(null);
            }

            var        snapshotPoint = point.Value;
            TextExtent word          = textStructureNavigator.GetExtentOfWord(snapshotPoint);
            var        foundWord     = true;

            if (!HighlightWordTagger.WordExtentIsValid(snapshotPoint, word))
            {
                //Before we retry, make sure it is worthwhile
                if (word.Span.Start != snapshotPoint ||
                    snapshotPoint == snapshotPoint.GetContainingLine().Start ||
                    char.IsWhiteSpace((snapshotPoint - 1).GetChar()))
                {
                    foundWord = false;
                }
                else
                {
                    // Try again, one character previous.
                    //If the caret is at the end of a word, pick up the word.
                    word = textStructureNavigator.GetExtentOfWord(snapshotPoint - 1);

                    //If the word still isn't valid, we're done
                    if (!HighlightWordTagger.WordExtentIsValid(snapshotPoint, word))
                    {
                        foundWord = false;
                    }
                }
            }

            if (!foundWord)
            {
                return(null);
            }
            return(word.Span.GetText());
        }
        // Token: 0x06000004 RID: 4 RVA: 0x0000220C File Offset: 0x0000040C
        public string GetCurrentlyHighlightedWord()
        {
            IVsTextManager vsTextManager = (IVsTextManager)base.GetService(typeof(SVsTextManager));
            IVsTextView    vsTextView    = null;
            int            num           = 1;

            vsTextManager.GetActiveView(num, null, ref vsTextView);
            IComponentModel componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
            IVsEditorAdaptersFactoryService vsEditorAdaptersFactoryService = (IVsEditorAdaptersFactoryService)base.GetService(typeof(IVsEditorAdaptersFactoryService));
            IVsEditorAdaptersFactoryService service = componentModel.GetService <IVsEditorAdaptersFactoryService>();
            ITextView     wpfTextView = service.GetWpfTextView(vsTextView);
            ITextBuffer   textBuffer  = wpfTextView.TextBuffer;
            SnapshotPoint?point       = wpfTextView.Caret.Position.Point.GetPoint(textBuffer, wpfTextView.Caret.Position.Affinity);

            if (point == null)
            {
                return(null);
            }
            ITextStructureNavigatorSelectorService service2 = componentModel.GetService <ITextStructureNavigatorSelectorService>();
            ITextStructureNavigator textStructureNavigator  = service2.GetTextStructureNavigator(textBuffer);
            TextExtent extentOfWord = textStructureNavigator.GetExtentOfWord(point.Value);
            bool       flag         = true;

            if (!StickyHighlighterPackage.WordExtentIsValid(point.Value, extentOfWord))
            {
                if (extentOfWord.Span.Start != point.Value || point.Value == point.Value.GetContainingLine().Start || char.IsWhiteSpace((point.Value - 1).GetChar()))
                {
                    flag = false;
                }
                else
                {
                    extentOfWord = textStructureNavigator.GetExtentOfWord(point.Value - 1);
                    if (!StickyHighlighterPackage.WordExtentIsValid(point.Value, extentOfWord))
                    {
                        flag = false;
                    }
                }
            }
            if (!flag)
            {
                return(null);
            }
            return(extentOfWord.Span.GetText());
        }
Exemple #13
0
        public static void FormatCurrentScope(ITextView textView, ITextBuffer textBuffer, bool indentCaret)
        {
            // Figure out caret position in the document text buffer
            SnapshotPoint?caretPoint = REditorDocument.MapCaretPositionFromView(textView);

            if (!caretPoint.HasValue)
            {
                return;
            }
            IREditorDocument document = REditorDocument.TryFromTextBuffer(textBuffer);

            if (document != null)
            {
                // Make sure AST is up to date
                document.EditorTree.EnsureTreeReady();
                var           ast      = document.EditorTree.AstRoot;
                ITextSnapshot snapshot = textBuffer.CurrentSnapshot;

                // Find scope to format
                IScope scope = ast.GetNodeOfTypeFromPosition <IScope>(caretPoint.Value);

                using (var undoAction = EditorShell.Current.CreateCompoundAction(textView, textView.TextBuffer)) {
                    undoAction.Open(Resources.AutoFormat);
                    // Now format the scope
                    bool changed = RangeFormatter.FormatRange(textView, textBuffer, scope, REditorSettings.FormatOptions);
                    if (indentCaret)
                    {
                        // Formatting may change AST and the caret position so we need to reacquire both
                        caretPoint = REditorDocument.MapCaretPositionFromView(textView);
                        if (caretPoint.HasValue)
                        {
                            document.EditorTree.EnsureTreeReady();
                            ast   = document.EditorTree.AstRoot;
                            scope = ast.GetNodeOfTypeFromPosition <IScope>(caretPoint.Value);
                            IndentCaretInNewScope(textView, scope, caretPoint.Value, REditorSettings.FormatOptions);
                        }
                    }
                    if (changed)
                    {
                        undoAction.Commit();
                    }
                }
            }
        }
        private bool TriggerCompletion()
        {
            //the caret must be in a non-projection location
            SnapshotPoint?caretPoint =
                m_textView.Caret.Position.Point.GetPoint(
                    textBuffer => (FilterTextBufferPos(textBuffer)), PositionAffinity.Predecessor);

            if (!caretPoint.HasValue)
            {
                return(false);
            }

            EpochClassifier classifier = m_textView.TextBuffer.Properties.GetOrCreateSingletonProperty <EpochClassifier>(creator: () => null);

            if (classifier != null)
            {
                var spans = classifier.GetClassificationSpans(m_textView.GetTextElementSpan(caretPoint.Value));
                if (spans != null)
                {
                    foreach (var span in spans)
                    {
                        if (span.ClassificationType.IsOfType("comment"))
                        {
                            return(false);
                        }

                        if (span.ClassificationType.IsOfType("string"))
                        {
                            return(false);
                        }
                    }
                }
            }

            var trackingPoint = caretPoint.Value.Snapshot.CreateTrackingPoint(caretPoint.Value.Position, PointTrackingMode.Positive);

            m_session = m_provider.CompletionBroker.CreateCompletionSession(m_textView, trackingPoint, true);

            //subscribe to the Dismissed event on the session
            m_session.Dismissed += this.OnSessionDismissed;
            m_session.Start();

            return(true);
        }
Exemple #15
0
        private IEnumerable <InheritanceTag> GetInheritanceGlyphTagsStartingOnLine(ITextViewLine textViewLine)
        {
            ITextBuffer visualBuffer = _textViewHost.TextView.TextViewModel.VisualBuffer;
            ITextBuffer textBuffer   = _textViewHost.TextView.TextBuffer;

            foreach (IMappingTagSpan <IGlyphTag> iteratorVariable2 in _glyphTagAggregator.GetTags(textViewLine.ExtentAsMappingSpan))
            {
                InheritanceTag tag = iteratorVariable2.Tag as InheritanceTag;
                if (tag != null)
                {
                    SnapshotPoint?point             = iteratorVariable2.Span.Start.GetPoint(visualBuffer, PositionAffinity.Predecessor);
                    SnapshotPoint?iteratorVariable5 = iteratorVariable2.Span.Start.GetPoint(textBuffer, PositionAffinity.Predecessor);
                    if (point.HasValue && iteratorVariable5.HasValue && iteratorVariable5.Value >= textViewLine.Start && iteratorVariable5.Value <= textViewLine.End)
                    {
                        yield return(tag);
                    }
                }
            }
        }
        public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> qiContent, out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;

            if (session == null || qiContent == null)
            {
                return;
            }

            // Map the trigger point down to our buffer.
            SnapshotPoint?point = session.GetTriggerPoint(_buffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            var       tree = CssEditorDocument.FromTextBuffer(_buffer);
            ParseItem item = tree.StyleSheet.ItemBeforePosition(point.Value.Position);

            if (item == null || !item.IsValid)
            {
                return;
            }

            Selector sel = item.FindType <Selector>();

            if (sel == null)
            {
                return;
            }
            // Mixins don't have specificity
            if (sel.SimpleSelectors.Count == 1 && sel.SimpleSelectors[0].SubSelectors.Count == 1 && sel.SimpleSelectors[0].SubSelectors[0] is LessMixinDeclaration)
            {
                return;
            }

            applicableToSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(item.Start, item.Length, SpanTrackingMode.EdgeNegative);

            string content = GenerateContent(sel);

            qiContent.Add(content);
        }
Exemple #17
0
        //public static bool IsPreprocessorLine(this ParseTree tree, int lineNumber)
        //{
        //    PPTokenId id;
        //    int num;
        //    int num2;
        //    return tree.TryGetPreprocessorDirective(lineNumber, out id, out num, out num2);
        //}

        //public static bool IsRegionEndLine(this ParseTree tree, int lineNumber)
        //{
        //    LexData lexData = tree.LexData;
        //    if (lexData.RegionCount > 0)
        //    {
        //        foreach (int num in lexData.RegionEnds)
        //        {
        //            if (num == lineNumber)
        //            {
        //                return true;
        //            }
        //        }
        //    }
        //    return false;
        //}

        //public static bool IsRegionStartLine(this ParseTree tree, int lineNumber)
        //{
        //    LexData lexData = tree.LexData;
        //    if (lexData.RegionCount > 0)
        //    {
        //        foreach (int num in lexData.RegionStarts)
        //        {
        //            if (num == lineNumber)
        //            {
        //                return true;
        //            }
        //        }
        //    }
        //    return false;
        //}

        //public static bool IsTransitionLine(this ParseTree tree, int lineNumber)
        //{
        //    LexData lexData = tree.LexData;
        //    if (lexData.TransitionLineCount > 0)
        //    {
        //        foreach (int num in lexData.TransitionLines)
        //        {
        //            if (num == lineNumber)
        //            {
        //                return true;
        //            }
        //        }
        //    }
        //    return false;
        //}

        public static void MoveCaretTo(this IBraceCompletionSession session, SnapshotPoint point, int virtualSpaces = 0)
        {
            ITextView     textView = session.TextView;
            SnapshotPoint?nullable = textView.BufferGraph.MapUpToBuffer(point, PointTrackingMode.Negative, PositionAffinity.Successor, textView.TextBuffer);

            if (nullable.HasValue)
            {
                if (virtualSpaces <= 0)
                {
                    textView.Caret.MoveTo(nullable.Value);
                }
                else
                {
                    VirtualSnapshotPoint bufferPosition = new VirtualSnapshotPoint(nullable.Value, virtualSpaces);
                    textView.Caret.MoveTo(bufferPosition);
                }
                textView.Caret.EnsureVisible();
            }
        }
        // Verify that we are about to insert the closing brace right after the opening one
        private bool ValidateStart(SnapshotPoint?openingPoint, char openingChar)
        {
            if (openingPoint.HasValue)
            {
                ITextBuffer subjectBuffer = openingPoint.Value.Snapshot.TextBuffer;

                // Get the position based on the predecessor which should be the opening brace
                SnapshotPoint?caretPosition = _textView.Caret.Position.Point.GetPoint(subjectBuffer, PositionAffinity.Predecessor);

                // verify that the opening brace is right behind the caret
                if (caretPosition.HasValue && caretPosition.Value.Position > 0)
                {
                    SnapshotPoint openingBrace = caretPosition.Value.Subtract(1);
                    return(openingBrace.GetChar() == openingChar);
                }
            }

            return(false);
        }
        private IEnumerable <MarkerTag> GetTagsForLine(ITextViewLine line)
        {
            var visualBuffer = _textViewHost.TextView.TextViewModel.VisualBuffer;
            var textBuffer   = _textViewHost.TextView.TextBuffer;

            foreach (var mapping in _glyphTagAggregator.GetTags(line.ExtentAsMappingSpan))
            {
                var tag = mapping.Tag as MarkerTag;
                if (tag != null)
                {
                    SnapshotPoint?visualPoint = mapping.Span.Start.GetPoint(visualBuffer, PositionAffinity.Predecessor);
                    SnapshotPoint?textPoint   = mapping.Span.Start.GetPoint(textBuffer, PositionAffinity.Predecessor);
                    if (visualPoint.HasValue && visualPoint.HasValue && visualPoint.Value >= line.Start && visualPoint.Value <= line.End)
                    {
                        yield return(tag);
                    }
                }
            }
        }
Exemple #20
0
        private void OnTextViewMouseHover(object sender, MouseHoverEventArgs e)
        {
            //find the mouse position by mapping down to the subject buffer
            SnapshotPoint?point = m_textView.BufferGraph.MapDownToFirstMatch
                                      (new SnapshotPoint(m_textView.TextSnapshot, e.Position),
                                      PointTrackingMode.Positive,
                                      snapshot => m_subjectBuffers.Contains(snapshot.TextBuffer),
                                      PositionAffinity.Predecessor);

            if (point != null)
            {
                ITrackingPoint triggerPoint = point.Value.Snapshot.CreateTrackingPoint(point.Value.Position, PointTrackingMode.Positive);

                if (!m_provider.QuickInfoBroker.IsQuickInfoActive(m_textView))
                {
                    m_session = m_provider.QuickInfoBroker.TriggerQuickInfo(m_textView, triggerPoint, true);
                }
            }
        }
Exemple #21
0
        public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> qiContent, out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;

            SnapshotPoint?point = session.GetTriggerPoint(session.TextView.TextBuffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            HtmlEditorTree tree = HtmlEditorDocument.TryFromTextView(session.TextView).HtmlEditorTree;

            if (tree == null)
            {
                return;
            }

            ElementNode   node = null;
            AttributeNode attr = null;

            tree.GetPositionElement(point.Value.Position, out node, out attr);

            if (node == null || (!node.Name.Equals("img", StringComparison.OrdinalIgnoreCase) && !node.Name.Equals("source", StringComparison.OrdinalIgnoreCase)))
            {
                return;
            }
            if (attr == null || !attr.Name.Equals("src", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            string url = ImageQuickInfo.GetFullUrl(attr.Value, session.TextView.TextBuffer);

            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            applicableToSpan = session.TextView.TextBuffer.CurrentSnapshot.CreateTrackingSpan(point.Value.Position, 1, SpanTrackingMode.EdgeNegative);

            ImageQuickInfo.AddImageContent(qiContent, url);
        }
        private bool TriggerCompletion()
        {
            SnapshotPoint?caretPoint =
                m_textView.Caret.Position.Point.GetPoint(
                    textBuffer => (!textBuffer.ContentType.IsOfType("projection")), PositionAffinity.Predecessor);

            if (!caretPoint.HasValue)
            {
                return(false);
            }

            m_session = m_provider.CompletionBroker.CreateCompletionSession(m_textView,
                                                                            caretPoint.Value.Snapshot.CreateTrackingPoint(caretPoint.Value.Position, PointTrackingMode.Positive), true);

            m_session.Dismissed += this.OnSessionDismissed;
            m_session.Start();

            return(true);
        }
Exemple #23
0
        public void AugmentSignatureHelpSession(ISignatureHelpSession session, IList <ISignature> signatures)
        {
            SnapshotPoint?point = session.GetTriggerPoint(_buffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            CssEditorDocument document = CssEditorDocument.FromTextBuffer(_buffer);
            ParseItem         item     = document.StyleSheet.ItemBeforePosition(point.Value.Position);

            if (item == null)
            {
                return;
            }

            Declaration dec = item.FindType <Declaration>();

            if (dec == null || dec.PropertyName == null || dec.Colon == null)
            {
                return;
            }

            int length = dec.Length - (dec.Colon.Start - dec.Start);
            var span   = _buffer.CurrentSnapshot.CreateTrackingSpan(dec.Colon.Start, length, SpanTrackingMode.EdgeNegative);

            ValueOrderFactory.AddSignatures method = ValueOrderFactory.GetMethod(dec);

            if (method != null)
            {
                signatures.Clear();
                method(session, signatures, dec, span);

                Dispatcher.CurrentDispatcher.BeginInvoke(
                    new Action(() =>
                {
                    session.Properties.AddProperty("dec", dec);
                    session.Match();
                }),
                    DispatcherPriority.Normal, null);
            }
        }
Exemple #24
0
        public IEnumerable <ITagSpan <RegionTag> > GetTags(NormalizedSnapshotSpanCollection snapShotSpans)
        {
            foreach (SnapshotSpan snapshotSpan in snapShotSpans.Where(IsRegionOrEndRegion))
            {
                SnapshotPoint?point = View.Caret.Position.Point.GetPoint(SourceBuffer, View.Caret.Position.Affinity);

                int pointPosition          = point.HasValue ? snapshotSpan.Snapshot.GetLineNumberFromPosition(point.Value) : -1;
                int lineNumberFromPosition = snapshotSpan.Snapshot.GetLineNumberFromPosition(snapshotSpan.Start);
                int index = snapshotSpan.GetText().IndexOf(Constants.RegionIndicatorCharacter);

                SnapshotSpan newSpan = new SnapshotSpan(snapshotSpan.Snapshot, (int)snapshotSpan.Start + index, snapshotSpan.Length - index);

                string classificationTypeNames = lineNumberFromPosition != pointPosition
                    ? Constants.InactiveRegionClassificationTypeNames
                    : Constants.ActiveRegionClassificationTypeNames;

                yield return(new TagSpan <RegionTag>(newSpan, new RegionTag(ClassificationTypeRegistryService.GetClassificationType(classificationTypeNames))));
            }
        }
        private bool TryInsertRoxygenBlock()
        {
            SnapshotPoint?point = REditorDocument.MapCaretPositionFromView(TextView);

            if (point.HasValue)
            {
                var snapshot = _textBuffer.CurrentSnapshot;
                var line     = snapshot.GetLineFromPosition(point.Value);

                if (line.LineNumber < snapshot.LineCount - 1 && point.Value == line.End && line.GetText().EqualsOrdinal("##"))
                {
                    var nextLine = snapshot.GetLineFromLineNumber(line.LineNumber + 1);
                    var document = REditorDocument.FromTextBuffer(_textBuffer);
                    document.EditorTree.EnsureTreeReady();
                    return(RoxygenBlock.TryInsertBlock(_textBuffer, document.EditorTree.AstRoot, nextLine.Start));
                }
            }
            return(false);
        }
        protected void JumpToCurrentLocation(ITextView textView)
        {
            var editorOperationsFactoryService = CompositionManager.Instance.GetExportedValue <IEditorOperationsFactoryService> ();
            var editorOperations = editorOperationsFactoryService.GetEditorOperations(textView);
            VirtualSnapshotPoint point;

            if (textView == this.textView && offset.HasValue)
            {
                var sp = offset.Value.TranslateTo(textView.TextSnapshot, PointTrackingMode.Positive);
                point = new VirtualSnapshotPoint(textView.TextSnapshot, sp);
            }
            else
            {
                var snapshotLine = textView.TextSnapshot.GetLineFromLineNumber(this.line);
                point  = new VirtualSnapshotPoint(textView.TextSnapshot, snapshotLine.Start.Position + column);
                offset = point.Position;
            }
            editorOperations.SelectAndMoveCaret(point, point, TextSelectionMode.Stream, EnsureSpanVisibleOptions.AlwaysCenter);
        }
Exemple #27
0
        private static IKeywordScopeStatement GetFormatScope(ITextView textView, ITextBuffer textBuffer, AstRoot ast)
        {
            SnapshotPoint?caret = REditorDocument.MapCaretPositionFromView(textView);

            if (caret.HasValue)
            {
                try {
                    int lineNumber             = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(caret.Value.Position);
                    ITextSnapshotLine line     = textBuffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber);
                    string            lineText = line.GetText();
                    if (lineText.TrimEnd().EndsWith("}", StringComparison.Ordinal))
                    {
                        IKeywordScopeStatement scopeStatement = ast.GetNodeOfTypeFromPosition <IKeywordScopeStatement>(caret.Value);
                        return(scopeStatement);
                    }
                } catch (Exception) { }
            }
            return(null);
        }
        void OnTextViewMouseHover(object sender, MouseHoverEventArgs e)
        {
            SnapshotPoint?point = textView.BufferGraph.MapDownToFirstMatch(
                new SnapshotPoint(textView.TextSnapshot, e.Position),
                PointTrackingMode.Positive,
                snapshot => textBuffers.Contains(snapshot.TextBuffer),
                PositionAffinity.Predecessor
                );

            if (point != null)
            {
                ITrackingPoint triggerPoint = point.Value.Snapshot.CreateTrackingPoint(
                    point.Value.Position, PointTrackingMode.Positive);
                if (provider.QuickInfoBroker.IsQuickInfoActive(textView))
                {
                    session = provider.QuickInfoBroker.TriggerQuickInfo(textView, triggerPoint, true);
                }
            }
        }
        private bool TriggerCompletion()
        {
            //the caret must be in a non-projection location
            SnapshotPoint?caretPoint = TextView.Caret.Position.Point.GetPoint(
                textBuffer => (!textBuffer.ContentType.IsOfType("projection")),
                PositionAffinity.Predecessor);

            if (!caretPoint.HasValue)
            {
                return(false);
            }

            var currentDispatcher = Dispatcher.CurrentDispatcher;
            var newSession        = Provider.CompletionBroker.CreateCompletionSession(
                TextView,
                caretPoint.Value.Snapshot.CreateTrackingPoint(caretPoint.Value.Position, PointTrackingMode.Positive),
                true);
            JavaSessionCompletions precomputedCompletions = new JavaSessionCompletions(Provider, caretPoint.Value.Snapshot.TextBuffer);

            precomputedCompletions.CollectCompletionSets(newSession).ContinueWith((System.Threading.Tasks.Task t) =>
            {
                // Only attempt to start a completion session if we have results to show and the session wasn't dismissed while doing work on the background
                if (precomputedCompletions.CompletionSetList != null && precomputedCompletions.CompletionSetList.Count != 0 && !newSession.IsDismissed)
                {
                    newSession.Properties.AddProperty(typeof(JavaSessionCompletions), precomputedCompletions);

                    currentDispatcher.Invoke(() =>
                    {
                        newSession.Start(); // Note: Start will fail to really start the session if there are no completion results to show
                        //CompletionSession.Filter();
                        if (newSession.SelectedCompletionSet != null)
                        {
                            newSession.SelectedCompletionSet.SelectBestMatch();
                        }

                        //subscribe to the Dismissed event on the session
                        newSession.Dismissed += AutocompleteSession_Dismissed;
                        CompletionSession     = newSession;
                    });
                }
            });
            return(true);
        }
Exemple #30
0
            private void MoveCaretToEndOfCurrentInput()
            {
                var           textView      = _window.TextView;
                var           curLangBuffer = _window.CurrentLanguageBuffer;
                SnapshotPoint?curLangPoint  = null;

                // If anything is selected we need to clear it before inserting new code
                textView.Selection.Clear();

                // Find out if caret position is where code can be inserted.
                // Caret must be in the area mappable to the language buffer.
                if (!textView.Caret.InVirtualSpace)
                {
                    curLangPoint = textView.MapDownToBuffer(textView.Caret.Position.BufferPosition, curLangBuffer);
                }

                if (curLangPoint == null)
                {
                    // Sending to the interactive window is like appending the input to the end, we don't
                    // respect the current caret position or selection.  We use InsertCode which uses the
                    // current caret position, so first we need to ensure the caret is in the input buffer,
                    // otherwise inserting code does nothing.
                    SnapshotPoint?viewPoint = textView.BufferGraph.MapUpToBuffer(
                        new SnapshotPoint(curLangBuffer.CurrentSnapshot, curLangBuffer.CurrentSnapshot.Length),
                        PointTrackingMode.Positive,
                        PositionAffinity.Successor,
                        textView.TextBuffer
                        );

                    if (!viewPoint.HasValue)
                    {
                        // Unable to map language buffer to view.
                        // Try moving caret to the end of the view then.
                        viewPoint = new SnapshotPoint(
                            textView.TextBuffer.CurrentSnapshot,
                            textView.TextBuffer.CurrentSnapshot.Length
                            );
                    }

                    textView.Caret.MoveTo(viewPoint.Value);
                }
            }
 public MockMappingPoint(SnapshotPoint _position) {
     position = _position.Snapshot == null ? (SnapshotPoint?)null : _position;
 }
Exemple #32
0
		public void ShowIncrementalSearch(bool forward) {
			var searchKind = forward ? SearchKind.IncrementalSearchForward : SearchKind.IncrementalSearchBackward;
			if (IsSearchControlVisible && inIncrementalSearch && !wpfTextView.Selection.IsEmpty) {
				var options = GetFindOptions(searchKind, forward);
				var startingPosition = GetNextSearchPosition(wpfTextView.Selection.StreamSelectionSpan.SnapshotSpan, forward);
				incrementalStartPosition = startingPosition;
				ShowSearchControl(searchKind, canOverwriteSearchString: false);

				isIncrementalSearchCaretMove = true;
				try {
					FindNextCore(options, startingPosition);
				}
				finally {
					isIncrementalSearchCaretMove = false;
				}
				return;
			}

			SearchString = string.Empty;
			wpfTextView.VisualElement.Focus();
			incrementalStartPosition = wpfTextView.Caret.Position.BufferPosition;
			ShowSearchControl(searchKind, canOverwriteSearchString: false);
		}
        private void UpdateQuickInfoContent(IQuickInfoSession session, SnapshotPoint triggerPoint)
        {
            /* use the experimental model to locate and process the expression */
            Stopwatch stopwatch = Stopwatch.StartNew();

            // lex the entire document
            var currentSnapshot = triggerPoint.Snapshot;
            var input = new SnapshotCharStream(currentSnapshot, new Span(0, currentSnapshot.Length));
            var unicodeInput = new JavaUnicodeStream(input);
            var lexer = new Java2Lexer(unicodeInput);
            var tokens = new CommonTokenStream(lexer);
            tokens.Fill();

            // locate the last token before the trigger point
            while (true)
            {
                IToken nextToken = tokens.LT(1);
                if (nextToken.Type == CharStreamConstants.EndOfFile)
                    break;

                if (nextToken.StartIndex > triggerPoint.Position)
                    break;

                tokens.Consume();
            }

            IToken triggerToken = tokens.LT(-1);
            if (triggerToken == null)
                return;

            switch (triggerToken.Type)
            {
            // symbol references
            case Java2Lexer.IDENTIFIER:
            case Java2Lexer.THIS:
            case Java2Lexer.SUPER:
            // primitive types
            case Java2Lexer.BOOLEAN:
            case Java2Lexer.CHAR:
            case Java2Lexer.BYTE:
            case Java2Lexer.SHORT:
            case Java2Lexer.INT:
            case Java2Lexer.LONG:
            case Java2Lexer.FLOAT:
            case Java2Lexer.DOUBLE:
            // literals
            case Java2Lexer.INTLITERAL:
            case Java2Lexer.LONGLITERAL:
            case Java2Lexer.FLOATLITERAL:
            case Java2Lexer.DOUBLELITERAL:
            case Java2Lexer.CHARLITERAL:
            case Java2Lexer.STRINGLITERAL:
            case Java2Lexer.TRUE:
            case Java2Lexer.FALSE:
            case Java2Lexer.NULL:
                break;

            default:
                return;
            }

            NetworkInterpreter interpreter = CreateNetworkInterpreter(tokens);

            while (interpreter.TryStepBackward())
            {
                if (interpreter.Contexts.Count == 0 || interpreter.Contexts.Count > 400)
                    break;

                if (interpreter.Contexts.All(context => context.BoundedStart))
                    break;
            }

            interpreter.Contexts.RemoveAll(i => !i.BoundedStart);
            interpreter.CombineBoundedStartContexts();

            IOutputWindowPane pane = Provider.OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense);
            if (pane != null)
            {
                pane.WriteLine(string.Format("Located {0} QuickInfo expression(s) in {1}ms.", interpreter.Contexts.Count, stopwatch.ElapsedMilliseconds));
            }

            HashSet<string> intermediateResult = new HashSet<string>();
            HashSet<string> finalResult = new HashSet<string>();
            List<object> quickInfoContent = new List<object>();
            foreach (var context in interpreter.Contexts)
            {
                Span? span = null;

                foreach (var transition in context.Transitions)
                {
                    if (!transition.Transition.IsMatch)
                        continue;

                    IToken token = transition.Token;
                    Span tokenSpan = new Span(token.StartIndex, token.StopIndex - token.StartIndex + 1);
                    if (span == null)
                        span = tokenSpan;
                    else
                        span = Span.FromBounds(Math.Min(span.Value.Start, tokenSpan.Start), Math.Max(span.Value.End, tokenSpan.End));
                }

                if (span.HasValue && !span.Value.IsEmpty)
                {
                    string text = currentSnapshot.GetText(span.Value);
                    if (!intermediateResult.Add(text))
                        continue;

                    AstParserRuleReturnScope<CommonTree, CommonToken> result = null;

                    try
                    {
                        var expressionInput = new ANTLRStringStream(text);
                        var expressionUnicodeInput = new JavaUnicodeStream(expressionInput);
                        var expressionLexer = new Java2Lexer(expressionUnicodeInput);
                        var expressionTokens = new CommonTokenStream(expressionLexer);
                        var expressionParser = new Java2Parser(expressionTokens);
                        result = expressionParser.primary();

                        // anchors experiment
                        Contract.Assert(TextBuffer.CurrentSnapshot == triggerPoint.Snapshot);
                        ClassAnchorTracker tracker = new ClassAnchorTracker(TextBuffer, null);
                        SnapshotSpan trackedSpan = new SnapshotSpan(triggerPoint.Snapshot, 0, triggerPoint.Position);
                        ITagSpan<ScopeAnchorTag>[] tags = tracker.GetTags(new NormalizedSnapshotSpanCollection(trackedSpan)).ToArray();

                        text = result.Tree.ToStringTree();
                    }
                    catch (RecognitionException)
                    {
                        text = "Could not parse: " + text;
                    }

                    text = text.Replace("\n", "\\n").Replace("\r", "\\r");
                    finalResult.Add(text);

                    //if (Regex.IsMatch(text, @"^[A-Za-z_]+(?:\.\w+)*$"))
                    //{
                    //    NameResolutionContext resolutionContext = NameResolutionContext.Global(Provider.IntelliSenseCache);
                    //    resolutionContext = resolutionContext.Filter(text, null, true);
                    //    CodeElement[] matching = resolutionContext.GetMatchingElements();
                    //    if (matching.Length > 0)
                    //    {
                    //        foreach (var element in matching)
                    //        {
                    //            element.AugmentQuickInfoSession(quickInfoContent);
                    //        }
                    //    }
                    //    else
                    //    {
                    //        // check if this is a package
                    //        CodePhysicalFile[] files = Provider.IntelliSenseCache.GetPackageFiles(text, true);
                    //        if (files.Length > 0)
                    //        {
                    //            finalResult.Add(string.Format("package {0}", text));
                    //        }
                    //        else
                    //        {
                    //            // check if this is a type
                    //            string typeName = text.Substring(text.LastIndexOf('.') + 1);
                    //            CodeType[] types = Provider.IntelliSenseCache.GetTypes(typeName, true);
                    //            foreach (var type in types)
                    //            {
                    //                if (type.FullName == text)
                    //                    finalResult.Add(string.Format("{0}: {1}", type.GetType().Name, type.FullName));
                    //            }
                    //        }
                    //    }
                    //}
                    //else
                    //{
                    //    finalResult.Add(text);
                    //}
                }
            }

            ITrackingSpan applicableToSpan = null;

            foreach (var result in finalResult)
            {
                quickInfoContent.Add(result);
            }

            applicableToSpan = currentSnapshot.CreateTrackingSpan(new Span(triggerToken.StartIndex, triggerToken.StopIndex - triggerToken.StartIndex + 1), SpanTrackingMode.EdgeExclusive);

            //try
            //{
            //    Expression currentExpression = Provider.IntellisenseCache.ParseExpression(selection);
            //    if (currentExpression != null)
            //    {
            //        SnapshotSpan? span = currentExpression.Span;
            //        if (span.HasValue)
            //            applicableToSpan = span.Value.Snapshot.CreateTrackingSpan(span.Value, SpanTrackingMode.EdgeExclusive);

            //        quickInfoContent.Add(currentExpression.ToString());
            //    }
            //    else
            //    {
            //        quickInfoContent.Add("Could not parse expression.");
            //    }
            //}
            //catch (Exception ex)
            //{
            //    if (ErrorHandler.IsCriticalException(ex))
            //        throw;

            //    quickInfoContent.Add(ex.Message);
            //}

            lock (_contentUpdateLock)
            {
                _triggerPoint = triggerPoint;
                _applicableToSpan = applicableToSpan;
                _quickInfoContent = quickInfoContent;
            }

            IWpfTextView wpfTextView = session.TextView as IWpfTextView;
            if (wpfTextView != null && wpfTextView.VisualElement != null)
            {
                ITrackingPoint trackingTriggerPoint = triggerPoint.Snapshot.CreateTrackingPoint(triggerPoint.Position, PointTrackingMode.Negative);
                wpfTextView.VisualElement.Dispatcher.BeginInvoke((Action<IQuickInfoSession, ITrackingPoint, bool>)RetriggerQuickInfo, session, trackingTriggerPoint, true);
            }
        }