public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            IList<ClassificationSpan> spans = new List<ClassificationSpan>();

            string text = span.GetText();
            int index = text.IndexOf("#", StringComparison.Ordinal);

            if (index > -1)
            {
                var result = new SnapshotSpan(span.Snapshot, span.Start + index, text.Length - index);
                spans.Add(new ClassificationSpan(result, comment));
            }

            if (index == -1 || index > 0)
            {
                var trimmed = text.TrimStart();
                var offset = text.Length - trimmed.Length;
                string[] args = trimmed.Split(' ');

                if (args.Length >= 2 && ValidKeywords.Contains(args[0].Trim().ToLowerInvariant()))
                {
                    var result = new SnapshotSpan(span.Snapshot, span.Start + offset, args[0].Trim().Length);
                    spans.Add(new ClassificationSpan(result, keyword));
                }
            }

            return spans;
        }
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            IList<ClassificationSpan> list = new List<ClassificationSpan>();

            string text = span.GetText();

            if (text.StartsWith("/// <binding"))
            {
                foreach (Match match in _binding.Matches(text))
                {
                    var value = match.Groups["value"];
                    var result = new SnapshotSpan(span.Snapshot, span.Start + value.Index, value.Length);
                    list.Add(new ClassificationSpan(result, _formatDefinition));
                }                
            }
            else
            {
                int index = text.IndexOf(_searchText, StringComparison.Ordinal);

                if (index == -1)
                    return list;

                foreach (Match match in _task.Matches(text))
                {
                    var name = match.Groups["name"];
                    var result = new SnapshotSpan(span.Snapshot, span.Start + name.Index, name.Length);
                    list.Add(new ClassificationSpan(result, _formatDefinition));
                }
            }

            return list;
        }
        public static Boolean TryParse(SnapshotSpan span, out BuildResult result)
        {
            var text = span.GetText();

            result = null;
            if (!text.StartsWith("========== ", StringComparison.Ordinal)) {
                return false;
            }
            if (!text.EndsWith(" ==========\r\n", StringComparison.Ordinal)) {
                return false;
            }

            var regex = "^========== (?:Build|Rebuild All): (?<Succeeded>\\d+) succeeded, (?<Failed>\\d+) failed, (?:(?<UpToDate>\\d+) up-to-date, )?(?<Skipped>\\d+) skipped ==========\r\n$";
            var match = Regex.Match(text, regex);
            if (!match.Success) {
                return false;
            }

            var localResult = new BuildResult();
            localResult.Succeeded = Convert.ToInt32(match.Groups["Succeeded"].Value);
            localResult.Failed = Convert.ToInt32(match.Groups["Failed"].Value);
            if (match.Groups["UpToDate"].Success) {
                localResult.UpToDate = Convert.ToInt32(match.Groups["UpToDate"].Value);
            }
            localResult.Skipped = Convert.ToInt32(match.Groups["Skipped"].Value);
            result = localResult;
            return true;
        }
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            LoadSettings();
            var classifications = new List<ClassificationSpan>();

            var snapshot = span.Snapshot;
            if (snapshot == null || snapshot.Length == 0 || !CanSearch(span) || !HighlightFindResults)
            {
                return classifications;
            }

            var text = span.GetText();

            var filenameSpans = GetMatches(text, FilenameRegex, span.Start, FilenameClassificationType).ToList();
            var searchTermSpans = GetMatches(text, _searchTextRegex, span.Start, SearchTermClassificationType).ToList();

            var toRemove = (from searchSpan in searchTermSpans
                from filenameSpan in filenameSpans
                where filenameSpan.Span.Contains(searchSpan.Span)
                select searchSpan).ToList();

            classifications.AddRange(filenameSpans);
            classifications.AddRange(searchTermSpans.Except(toRemove));
            return classifications;
        }
 private IList<ClassificationSpan> CreateClassificationSpans(SnapshotSpan trackingSpan)
 {
     var gherkinClassificationSpans = new GherkinClassificationSpans(
         this.classificationTypeRegistryService, trackingSpan.Snapshot, trackingSpan.Start);
     gherkinClassificationSpans.Parse(trackingSpan.GetText());
     return gherkinClassificationSpans.ClassificationSpans.ToList();
 }
        private static int CalculateDeletionStartFromStartPosition(ITextSnapshot snapshot, int startPosition)
        {
            var position = startPosition - 1;

            if (position < 0)
            {
                return 0;
            }

            while (true)
            {
                if (position > 0)
                {
                    var ss = new SnapshotSpan(snapshot, position, 1);
                    var text = ss.GetText();

                    if (text != null && !"\r\n".Contains(text) && string.IsNullOrWhiteSpace(text))
                    {
                        --position;
                        continue;
                    }

                    ++position;
                }

                return position;
            }
        }
            public TrackingSession(StateMachine stateMachine, SnapshotSpan snapshotSpan, IAsynchronousOperationListener asyncListener)
            {
                AssertIsForeground();

                _asyncListener = asyncListener;
                _trackingSpan = snapshotSpan.Snapshot.CreateTrackingSpan(snapshotSpan.Span, SpanTrackingMode.EdgeInclusive);
                _cancellationTokenSource = new CancellationTokenSource();
                _cancellationToken = _cancellationTokenSource.Token;

                if (snapshotSpan.Length > 0)
                {
                    // If the snapshotSpan is nonempty, then the session began with a change that
                    // was touching a word. Asynchronously determine whether that word was a
                    // renamable identifier. If it is, alert the state machine so it can trigger
                    // tagging.

                    _originalName = snapshotSpan.GetText();
                    _isRenamableIdentifierTask = Task.Factory.SafeStartNewFromAsync(
                        () => DetermineIfRenamableIdentifierAsync(snapshotSpan, initialCheck: true),
                        _cancellationToken,
                        TaskScheduler.Default);

                    QueueUpdateToStateMachine(stateMachine, _isRenamableIdentifierTask);
                }
                else
                {
                    // If the snapshotSpan is empty, that means text was added in a location that is
                    // not touching an existing word, which happens a fair amount when writing new
                    // code. In this case we already know that the user is not renaming an
                    // identifier.

                    _isRenamableIdentifierTask = s_notRenamableTask;
                }
            }
        /// <summary>
        /// Classify the given spans
        /// </summary>
        /// <param name="span">The span of interest in this projection buffer.</param>
        /// <returns>The list of <see cref="ClassificationSpan"/> as contributed by the source buffers.</returns>
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            ITextSnapshot snapshot = span.Snapshot;

            List<ClassificationSpan> spans = new List<ClassificationSpan>();

            if (snapshot.Length == 0)
                return spans;

            var text = span.GetText();

            if (text.StartsWith("System.Windows.Data Error", StringComparison.OrdinalIgnoreCase))
            {
                IClassificationType type = _classificationTypeRegistry.GetClassificationType("output.wpfbindingalert");
                spans.Add(new ClassificationSpan(span, type));
            }
            else if (text.IndexOf("error ", StringComparison.OrdinalIgnoreCase) >= 0 ||
                     text.IndexOf("error:", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                //error followed by a space is the typical error of the build.
                IClassificationType type = _classificationTypeRegistry.GetClassificationType("output.alert");
                spans.Add(new ClassificationSpan(span, type));
            }
            else if (text.IndexOf("INFO:", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                //error followed by a space is the typical error of the build.
                IClassificationType type = _classificationTypeRegistry.GetClassificationType("output.info");
                spans.Add(new ClassificationSpan(span, type));
            }

            return spans;
        }
        // This does not work properly for multiline fenced code-blocks,
        // since we get each line separately.  If I can assume that this
        // always runs sequentially without skipping, I can add state to
        // track whether we're in a fenced block.
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            string text = span.GetText();

            var codeBlocks = FindMatches(span, text, _reCode, _code).ToList();

            if (codeBlocks.Any())
            {
                // Flatten all code blocks to avoid matching text within them
                var nonCodeBuilder = text.ToCharArray();
                foreach (var code in codeBlocks)
                {
                    for (int i = code.Span.Start; i < code.Span.End; i++)
                    {
                        nonCodeBuilder[i - span.Start] = 'Q';
                    }
                }
                text = new String(nonCodeBuilder);
            }

            var quotes = FindMatches(span, text, _reQuote, _quote);
            var bolds = FindMatches(span, text, _reBold, _bold);
            var italics = FindMatches(span, text, _reItalic, _italic);
            var headers = FindMatches(span, text, _reHeader, _header);

            return bolds.Concat(italics).Concat(headers).Concat(codeBlocks).Concat(quotes).ToList();
        }
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            IList<ClassificationSpan> list = new List<ClassificationSpan>();
            if (!_isRobotsTxt)
                return list;

            string text = span.GetText();
            int index = text.IndexOf("#");

            if (index > -1)
            {
                var result = new SnapshotSpan(span.Snapshot, span.Start + index, text.Length - index);
                list.Add(new ClassificationSpan(result, _comment));
            }

            if (index == -1 || index > 0)
            {
                string[] args = text.Split(':');

                if (args.Length >= 2 && _valid.Contains(args[0].Trim().ToLowerInvariant()))
                {
                    var result = new SnapshotSpan(span.Snapshot, span.Start, args[0].Length);
                    list.Add(new ClassificationSpan(result, _keyword));
                }
            }

            return list;
        }
        private static int CalculateDeletionEndFromRuleEndPosition(ITextSnapshot snapshot, int endPosition)
        {
            var position = endPosition;
            var committedPosition = position;

            while (true)
            {
                if (position < snapshot.Length)
                {
                    var ss = new SnapshotSpan(snapshot, position, 1);
                    var text = ss.GetText();

                    if (text != null)
                    {
                        if ("\r\n".Contains(text))
                        {
                            committedPosition = ++position;
                            continue;
                        }

                        if (string.IsNullOrWhiteSpace(text))
                        {
                            ++position;
                            continue;
                        }
                    }
                }

                return committedPosition;
            }
        }
Example #12
0
 private void CreateVisuals(ITextViewLine line)
 {
     IWpfTextViewLineCollection textViewLines = _view.TextViewLines;
     SnapshotSpan span = new SnapshotSpan(_view.TextSnapshot, Span.FromBounds(line.Start, line.End));
     if (span.GetText().IsMethodDefinition())
         AddAdornmentToMethod(line, textViewLines, span);
 }
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            var classifications = new List<ClassificationSpan>();

            var snapshot = span.Snapshot;
            if (snapshot == null || snapshot.Length == 0 || !CanSearch(span) || !SettingsProvider.IsHighlightFindResultsEnabled())
            {
                return classifications;
            }

            var text = span.GetText();

            var filenameSpans = GetMatches(text, FilenameRegex, span.Start, FilenameClassificationType).ToList();
            //var searchTermSpans = GetMatches(text, searchTextRegex, span.Start, SearchTermClassificationType).ToList();
            List<ClassificationSpan> searchTermSpans = null;
            //if (StudioUtility.IsMultitextFind())
            if (multitext)
            {
                searchTermSpans = GetMatches(text, listsearchTextRegex, span.Start, SearchTermClassificationType).ToList();
            }
            else
            {
                searchTermSpans = GetMatches(text, searchTextRegex, span.Start, SearchTermClassificationType).ToList();
            }
            var toRemove = (from searchSpan in searchTermSpans
                            from filenameSpan in filenameSpans
                            where filenameSpan.Span.Contains(searchSpan.Span)
                            select searchSpan).ToList();

            classifications.AddRange(filenameSpans);
            classifications.AddRange(searchTermSpans.Except(toRemove));
            return classifications;
        }
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            IList<ClassificationSpan> list = new List<ClassificationSpan>();
            if (!_isDockerfile)
                return list;

            string text = span.GetText();
            int index = text.IndexOf("#", StringComparison.Ordinal);

            if (index > -1)
            {
                var result = new SnapshotSpan(span.Snapshot, span.Start + index, text.Length - index);
                list.Add(new ClassificationSpan(result, _comment));
            }

            if (_textType != TextType.Dockerfile)
                return list;

            if (index == -1 || index > 0)
            {
                string[] args = text.Split(' ');

                if (args.Length >= 2 && Valid.Contains(args[0].Trim().ToUpperInvariant()))
                {
                    var result = new SnapshotSpan(span.Snapshot, span.Start, args[0].Length);
                    list.Add(new ClassificationSpan(result, _keyword));
                }
            }

            return list;
        }
Example #15
0
        IList<ClassificationSpan> IClassifier.GetClassificationSpans(SnapshotSpan span)
        {
            var classifications = new List<ClassificationSpan>();

            using (var systemState = new SystemState())
            {
                int startIndex, endIndex;

                if (span != null)
                {
                    string spanText = span.GetText();
                    System.Diagnostics.Debug.WriteLine((spanText != null) ? spanText : string.Empty);
                }

                // Execute the IPy tokenizer
                var tokenizer = new Tokenizer(span.GetText().ToCharArray(), true, systemState, new CompilerContext(string.Empty, new QuietCompilerSink()));
                var token = tokenizer.Next();

                // Iterate the tokens
                while (token.Kind != TokenKind.EndOfFile)
                {
                    // Determine the bounds of the classfication span
                    startIndex = span.Snapshot.GetLineFromLineNumber(tokenizer.StartLocation.Line - 1 + span.Start.GetContainingLine().LineNumber).Start.Position + tokenizer.StartLocation.Column;
                    endIndex = span.Snapshot.GetLineFromLineNumber(tokenizer.EndLocation.Line - 1 + span.Start.GetContainingLine().LineNumber).Start.Position + tokenizer.EndLocation.Column;

                    if (endIndex > span.Snapshot.GetText().Length)
                        endIndex = span.Snapshot.GetText().Length;

                    if (endIndex > startIndex && !span.Snapshot.TextBuffer.IsReadOnly(new Span(startIndex, endIndex - startIndex)))
                    {
                        // Add the classfication span
                        classifications.Add(new ClassificationSpan(new SnapshotSpan(span.Snapshot, startIndex, endIndex - startIndex), GetClassificationType(token)));
                    }

                    // Get next token
                    token = tokenizer.Next();
                }
            }

            foreach (var region in span.Snapshot.TextBuffer.GetReadOnlyExtents(span))
            {
                // Add classfication for read only regions
                classifications.Add(new ClassificationSpan(new SnapshotSpan(span.Snapshot, region), classificationRegistryService.GetClassificationType("PythonReadOnlyRegion")));
            }

            return classifications;
        }
        public override void PreprocessMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            if (e.ClickCount != 3)
                return;

            ITextViewLine clickLine = GetTextViewLineUnderPoint(e);
            if (clickLine == null)
                return;

            SnapshotSpan extent = clickLine.ExtentIncludingLineBreak;

            ErrorPosition position = outputProcessor.FindFirstErrorPosition(
                extent.GetText());

            if (position != null)
            {
                var filenameSpan = new SnapshotSpan(
                    extent.Start + position.Filename.Start,
                    position.Filename.Length);

                string filename = filenameSpan.GetText();

                if (File.Exists(filename))
                {
                    VsShellUtilities.OpenDocument(
                        serviceProvider,
                        filenameSpan.GetText());

                    var lineNumberSpan = new SnapshotSpan(
                        extent.Start + position.LineNumber.Start,
                        position.LineNumber.Length);

                    string lineNumberString = lineNumberSpan.GetText();
                    int lineNumber = int.Parse(lineNumberString);

                    // view.VisualSnapshot.LineCount shows old document line count.
                    //if (lineNumber <= view.VisualSnapshot.LineCount)
                    {
                        dte.ExecuteCommand("Edit.GoTo " + lineNumberString);
                    }

                    e.Handled = true;
                }
            }
        }
        public SnapshotCharStream(SnapshotSpan cachedSpan)
        {
            Contract.Requires<ArgumentException>(cachedSpan.Snapshot != null);

            this.Snapshot = cachedSpan.Snapshot;
            _count = Snapshot.Length;
            _explicitCache = true;
            _currentSnapshotLineStartIndex = cachedSpan.Start;
            _currentSnapshotLine = cachedSpan.GetText();
        }
Example #18
0
        public IList < ClassificationSpan > GetClassificationSpans ( SnapshotSpan span )
        {
            var snapshot = span.Snapshot;
            var start    = span.Start.Position;

            return ILParser.Parse ( span.GetText ( ) )
                           .Select ( token => new ClassificationSpan ( new SnapshotSpan ( snapshot,
                                                                                          start + token.Start, token.Length ),
                                                                       classificationTypeRegistry.GetClassificationType ( token.Class ) ) )
                           .ToList ( );
        }
Example #19
0
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            var handler = new ClassificationParserHandler(span, classificationTypes);
            var parser = new Parser(handler);
            if (parser.Parse(span.GetText()))
            {
                return handler.Result;
            }

            return new List<ClassificationSpan>();
        }
Example #20
0
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            var code = span.GetText();

            var tokens = parser.Parse(code);

            return tokens
                .Select(t => ClassifyToken(t, span.Start))
                .Where(c => c != null)
                .ToList();
        }
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            string text = span.GetText();

            var bolds = FindMatches(span, text, _reBold, _bold);
            var italics = FindMatches(span, text, _reItalic, _italic);
            var headers = FindMatches(span, text, _reHeader, _header);
            var codes = FindMatches(span, text, _reCode, _code);

            return bolds.Concat(italics).Concat(headers).Concat(codes).ToList();
        }
Example #22
0
        internal static ReadOnlyCollection<ITagSpan<TextMarkerTag>> GetDogTags(SnapshotSpan span)
        {
            var text = span.GetText();
            var list = new List<ITagSpan<TextMarkerTag>>();
            foreach (var current in GetDogSpans(text))
            {
                var tagSpan = new SnapshotSpan(span.Start.Add(current.Start), current.Length);
                list.Add(CreateTagSpan(tagSpan));
            }

            return list.ToReadOnlyCollectionShallow();
        }
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            IList<ClassificationSpan> list = new List<ClassificationSpan>();

            string text = span.GetText();

            // Statement
            if (text.Trim().Equals("WEBVTT", StringComparison.OrdinalIgnoreCase))
            {
                list.Add(new ClassificationSpan(span, _statement));
                return list;
            }

            // Comment
            if (text.StartsWith("NOTE", StringComparison.Ordinal))
            {
                list.Add(new ClassificationSpan(span, _comment));
                return list;
            }

            // Time
            foreach (Match match in _rxTime.Matches(text))
            {
                int start = span.Start.Position + match.Index;
                SnapshotSpan timeSpan = new SnapshotSpan(span.Snapshot, start, match.Length);
                list.Add(new ClassificationSpan(timeSpan, _time));
            }

            if (list.Count > 0)
                return list;

            // Markup
            foreach (Match match in _rxMarkup.Matches(text))
            {
                int start = span.Start.Position + match.Index;
                SnapshotSpan timeSpan = new SnapshotSpan(span.Snapshot, start, match.Length);
                list.Add(new ClassificationSpan(timeSpan, _markup));

                // Name
                if (match.Value.StartsWith("<v ", StringComparison.Ordinal))
                {
                    Match nameMatch = _rxName.Match(match.Value);
                    if (nameMatch.Success)
                    {
                        start = span.Start.Position + match.Index + nameMatch.Groups[1].Index;
                        SnapshotSpan nameSpan = new SnapshotSpan(span.Snapshot, start, nameMatch.Groups[1].Length);
                        list.Add(new ClassificationSpan(nameSpan, _name));
                    }
                }
            }

            return list;
        }
Example #24
0
#pragma warning restore 67

        /// <summary>
        /// Gets all the <see cref="ClassificationSpan"/> objects that intersect with the given range of text.
        /// </summary>
        /// <remarks>
        /// This method scans the given SnapshotSpan for potential matches for this classification.
        /// In this instance, it classifies everything and returns each span as a new ClassificationSpan.
        /// </remarks>
        /// <param name="span">The span currently being classified.</param>
        /// <returns>A list of ClassificationSpans that represent spans identified to be of this classification.</returns>
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            var result = new List<ClassificationSpan>();

            var text = span.GetText();
            foreach (Match m in Regex.Matches(text, @"\bfunction\b"))
            {
                var currSpan = new SnapshotSpan(span.Start + m.Groups[0].Index, m.Groups[0].Length);
                result.Add(new ClassificationSpan(currSpan, this.registry.GetClassificationType("function")));
            }
            return result;
        }
        /// <summary>
        /// This method scans the given SnapshotSpan for potential matches for this classification.
        /// In this instance, it classifies everything and returns each span as a new ClassificationSpan.
        /// </summary>
        /// <param name="trackingSpan">The span currently being classified</param>
        /// <returns>A list of ClassificationSpans that represent spans identified to be of this classification</returns>
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            //create a list to hold the results
            List<ClassificationSpan> classifications = new List<ClassificationSpan>();

            if (span.GetText().Contains("/// twitted"))
            {
                classifications.Add(new ClassificationSpan(new SnapshotSpan(span.Snapshot, new Span(span.Start, span.Length)),
                                               _classificationType));
            }

            return classifications;
        }
Example #26
0
 public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
 {
     var result = new List<ClassificationSpan>();
     var lexer = CreateLexerFor(span.GetText());
     var begin = -1;
     var length = -1;
     IClassificationType classification = null;
     var offset = span.Start.Position;
     while (ScanTokenAndProvideInfoAboutIt(lexer, span.GetText(), ref begin, ref length, ref classification))
     {
         try
         {
             result.Add(new ClassificationSpan(new SnapshotSpan(span.Snapshot, offset + begin, length), classification));
         }
         catch (Exception e)
         {
             Debug.WriteLine(e.Message);
             break;
         }
     }
     return result;
 }
        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            IList<ClassificationSpan> list = new List<ClassificationSpan>();

            string text = span.GetText();

            foreach (Match match in _regex.Matches(text))
            {
                SnapshotSpan s = new SnapshotSpan(span.Snapshot, span.Start + match.Index, match.Length);
                list.Add(new ClassificationSpan(s, _variable));
            }

            return list;
        }
Example #28
0
 private static IEnumerable<Tuple<SnapshotSpan, TagSpan<GherkinTokenTag>>> HandleText(
     SnapshotSpan span, GherkinTokenType tokenType,
     string surroundingText)
 {
     var str = span.GetText().TrimEnd(WhiteSpaces.Chars);
     var idx = str.IndexOf(surroundingText, StringComparison.InvariantCulture);
     var idx2 = str.LastIndexOf(surroundingText, StringComparison.InvariantCulture);
     if (idx == -1 || idx2 == -1)
         yield break;
     ITextSnapshotLine containingLine = span.Start.GetContainingLine();
     var tokenSpan = new SnapshotSpan(span.Snapshot, new Span(containingLine.Start.Position + idx, idx2 - idx + 1));
     var tagSpan = new TagSpan<GherkinTokenTag>(tokenSpan, new GherkinTokenTag(tokenType));
     yield return new Tuple<SnapshotSpan, TagSpan<GherkinTokenTag>>(tokenSpan, tagSpan);
 }
 public static CompletionAnalysis Make(ClassificationSpan start, ClassificationSpan end, Span loc,
     ITextSnapshot snapshot, ITrackingSpan span, ITextBuffer buffer, bool isSpace)
 {
     if (start == end) {
         return new ImportCompletionAnalysis(String.Empty, loc.Start, span, buffer);
     } else if (!isSpace) {
         int nsLen = end.Span.End - start.Span.End - 1;
         var nsSpan = new SnapshotSpan(snapshot, start.Span.End + 1, nsLen);
         var text = nsSpan.GetText().Trim();
         return new ImportCompletionAnalysis(text, loc.Start, span, buffer);
     } else {
         return EmptyCompletionContext;
     }
 }
 public void DeleteSpan2()
 {
     CreateLines("foo", "bar", "baz");
     var tss = _view.TextSnapshot;
     var span = new SnapshotSpan(
         tss.GetLineFromLineNumber(0).Start,
         tss.GetLineFromLineNumber(1).EndIncludingLineBreak);
     var reg = new Register('c');
     _operations.DeleteSpan(span, MotionKind._unique_Exclusive, OperationKind.LineWise, reg);
     tss = _view.TextSnapshot;
     Assert.AreEqual(1, tss.LineCount);
     Assert.AreEqual("baz", tss.GetLineFromLineNumber(0).GetText());
     Assert.AreEqual(span.GetText(), reg.StringValue);
 }
Example #31
0
        private void UpdateWordAdornments(object threadContext)
        {
            SnapshotPoint currentRequest = RequestedPoint;

            List <SnapshotSpan> wordSpans = new List <SnapshotSpan>();

            // Find all words in the buffer like the one the caret is on
            TextExtent word = TextStructureNavigator.GetExtentOfWord(currentRequest);

            bool foundWord = true;

            // If we've selected something not worth highlighting, we might have
            // missed a "word" by a little bit
            if (!WordExtentIsValid(currentRequest, word))
            {
                // Before we retry, make sure it is worthwhile
                if (word.Span.Start != currentRequest ||
                    currentRequest == currentRequest.GetContainingLine().Start ||
                    char.IsWhiteSpace((currentRequest - 1).GetChar()))
                {
                    foundWord = false;
                }
                else
                {
                    // Try again, one character previous.  If the caret is at the end of a word, then
                    // this will pick up the word we are at the end of.
                    word = TextStructureNavigator.GetExtentOfWord(currentRequest - 1);

                    // If we still aren't valid the second time around, we're done
                    if (!WordExtentIsValid(currentRequest, word))
                    {
                        foundWord = false;
                    }
                }
            }

            if (!foundWord)
            {
                // If we couldn't find a word, just clear out the existing markers
                SynchronousUpdate(currentRequest, new NormalizedSnapshotSpanCollection(), null);
                return;
            }

            SnapshotSpan currentWord = word.Span;

            // If this is the same word we currently have, we're done (e.g. caret moved within a word).
            if (CurrentWord.HasValue && currentWord == CurrentWord)
            {
                return;
            }

            // Find the new spans
            FindData findData = new FindData(currentWord.GetText(), currentWord.Snapshot);

            findData.FindOptions = FindOptions.WholeWord | FindOptions.MatchCase;

            wordSpans.AddRange(TextSearchService.FindAll(findData));

            // If we are still up-to-date (another change hasn't happened yet), do a real update
            if (currentRequest == RequestedPoint)
            {
                SynchronousUpdate(currentRequest, new NormalizedSnapshotSpanCollection(wordSpans), currentWord);
            }
        }
Example #32
0
        private void UpdateWordAdornments(object threadContext)
        {
            try
            {
                SnapshotPoint currentRequest = RequestedPoint;

                List <SnapshotSpan> wordSpans = new List <SnapshotSpan>();

                string clickLineSelection = SourceBuffer.CurrentSnapshot.GetLineFromPosition(RequestedPoint).GetText();
                int    lineStartPos       = SourceBuffer.CurrentSnapshot.GetLineFromPosition(RequestedPoint).Start.Position;
                int    lineCaretPos       = RequestedPoint.Position - lineStartPos;

                int  fileStartPos = -1;
                int  fileEndPos   = -1;
                bool foundWord    = false;

                if ((fileStartPos = clickLineSelection.IndexOf("file://")) > 0 &&
                    (fileEndPos = clickLineSelection.IndexOf(">")) > 0 &&
                    (fileEndPos > fileStartPos) &&
                    (lineCaretPos > fileStartPos && lineCaretPos < fileEndPos) &&
                    fileStartPos >= 0 &&
                    fileEndPos >= 0)
                {
                    fileStartPos += "file://".Length;

                    string strFilePath = clickLineSelection.Substring(fileStartPos, fileEndPos - fileStartPos);

                    if (File.Exists(strFilePath))
                    {
                        string strExt = Path.GetExtension(strFilePath);

                        foundWord = true;

                        string editorTool = VSDebugProPackage.Context.Settings.GetAssignedTool(strExt);

                        if (editorTool != string.Empty)
                        {
                            Process.Start(editorTool, strFilePath);
                        }
                    }
                }

                if (!foundWord)
                {
                    // If we couldn't find a word, just clear out the existing markers
                    SynchronousUpdate(currentRequest, new NormalizedSnapshotSpanCollection(), null);
                    return;
                }

                SnapshotSpan currentWord = new SnapshotSpan(new SnapshotPoint(SourceBuffer.CurrentSnapshot, lineStartPos + fileStartPos),
                                                            new SnapshotPoint(SourceBuffer.CurrentSnapshot, lineStartPos + fileEndPos));

                // If this is the same word we currently have, we're done (e.g. caret moved within a word).
                if (CurrentWord.HasValue && currentWord == CurrentWord)
                {
                    return;
                }

                // Find the new spans
                FindData findData = new FindData(currentWord.GetText(), currentWord.Snapshot);
                findData.FindOptions = FindOptions.WholeWord | FindOptions.MatchCase;

                wordSpans.AddRange(TextSearchService.FindAll(findData));
                // If we are still up-to-date (another change hasn't happened yet), do a real update
                if (currentRequest == RequestedPoint)
                {
                    SynchronousUpdate(currentRequest, new NormalizedSnapshotSpanCollection(wordSpans), currentWord);
                }
            }
            catch (Exception)
            {
            }
        }
            internal async Task <IEnumerable <Diagnostic> > GetDiagnostic(SyntaxTree tree, DiagnosticDescriptor diagnosticDescriptor, CancellationToken cancellationToken)
            {
                try
                {
                    // This can be called on a background thread. We are being asked whether a
                    // lightbulb should be shown for the given document, but we only know about the
                    // current state of the buffer. Compare the text to see if we should bail early.
                    // Even if the text is the same, the buffer may change on the UI thread during this
                    // method. If it does, we may give an incorrect response, but the diagnostics
                    // engine will know that the document changed and not display the lightbulb anyway.

                    if (Buffer.AsTextContainer().CurrentText != await tree.GetTextAsync(cancellationToken).ConfigureAwait(false))
                    {
                        return(SpecializedCollections.EmptyEnumerable <Diagnostic>());
                    }

                    TrackingSession trackingSession;
                    if (CanInvokeRename(out trackingSession, waitForResult: true, cancellationToken: cancellationToken))
                    {
                        SnapshotSpan snapshotSpan = trackingSession.TrackingSpan.GetSpan(Buffer.CurrentSnapshot);
                        var          textSpan     = snapshotSpan.Span.ToTextSpan();

                        var builder = ImmutableDictionary.CreateBuilder <string, string>();
                        builder.Add(RenameTrackingDiagnosticAnalyzer.RenameFromPropertyKey, trackingSession.OriginalName);
                        builder.Add(RenameTrackingDiagnosticAnalyzer.RenameToPropertyKey, snapshotSpan.GetText());
                        var properties = builder.ToImmutable();

                        var diagnostic = Diagnostic.Create(diagnosticDescriptor,
                                                           tree.GetLocation(textSpan),
                                                           properties);

                        return(SpecializedCollections.SingletonEnumerable(diagnostic));
                    }

                    return(SpecializedCollections.EmptyEnumerable <Diagnostic>());
                }
                catch (Exception e) when(FatalError.ReportUnlessCanceled(e))
                {
                    throw ExceptionUtilities.Unreachable;
                }
            }
Example #34
0
        public override void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            if (session == null || completionSets == null)
            {
                return;
            }

            ITrackingPoint triggerPoint = session.GetTriggerPoint(TextBuffer);

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

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

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

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

                default:
                    flag = true;
                    break;
                }

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

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

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

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

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

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

                CompletionSet completionSet = new CompletionSet("AlloyCompletions", "Alloy Completions", applicableTo, orderedCompletions, EmptyCompletions);
                completionSets.Add(completionSet);
            }
        }
Example #35
0
 public InputLine(SnapshotSpan snapshotSpan)
 {
     this.SnapshotSpan = snapshotSpan;
     this.Text         = snapshotSpan.GetText();
     this.Flags        = InputLineFlag.Execute;
 }
        public TokenTagCollection Match(SnapshotSpan span)
        {
            var tokenTags = new TokenTagCollection(span);

            string token    = span.GetText();
            int    position = span.Start + token.Length;

            if (_builtInTokens.Contains(token))
            {
                tokenTags.SetClassifierTag(BUILT_IN_TOKEN_TYPE);
            }
            else if (IsFloatingConstant(token))
            {
                tokenTags.SetClassifierTag(FLOAT_TOKEN_TYPE);
            }
            else if (IsIntegerConstant(token))
            {
                var isFloat = false;

                // Now that we have matched with an integer, look ahead to see if we are followed by a decimal
                if (span.Snapshot.GetText(span.End, 1) == ".")
                {
                    var nConsumed = 1;
                    var text      = span.Snapshot.GetText();

                    for (var i = span.End.Position + 1; i < text.Length; i++)
                    {
                        if (char.IsNumber(text[i]))
                        {
                            isFloat = true;
                            nConsumed++;
                        }
                        else if (text[i] == 'f' || text[i] == 'F')
                        {
                            nConsumed++;
                            break;
                        }
                        else if (text[i] == 'l')
                        {
                            if (text[i + 1] == 'f' || text[i + 1] == 'F')
                            {
                                nConsumed += 2;
                            }
                            else
                            {
                                isFloat = false;
                            }

                            break;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (isFloat)
                    {
                        tokenTags.ClassifierTagSpan = new TagSpan <GLSLClassifierTag>(span.Extended(nConsumed), new GLSLClassifierTag(FLOAT_TOKEN_TYPE));
                    }
                }

                if (!isFloat)
                {
                    tokenTags.SetClassifierTag(INT_TOKEN_TYPE);
                }
            }

            return(tokenTags);
        }
Example #37
0
        public InlineRenameSession(
            IThreadingContext threadingContext,
            InlineRenameService renameService,
            Workspace workspace,
            SnapshotSpan triggerSpan,
            IInlineRenameInfo renameInfo,
            IWaitIndicator waitIndicator,
            ITextBufferAssociatedViewService textBufferAssociatedViewService,
            ITextBufferFactoryService textBufferFactoryService,
            IFeatureServiceFactory featureServiceFactory,
            IEnumerable <IRefactorNotifyService> refactorNotifyServices,
            IAsynchronousOperationListener asyncListener)
            : base(threadingContext, assertIsForeground: true)
        {
            // This should always be touching a symbol since we verified that upon invocation
            _renameInfo = renameInfo;

            _triggerDocument = triggerSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
            if (_triggerDocument == null)
            {
                throw new InvalidOperationException(EditorFeaturesResources.The_triggerSpan_is_not_included_in_the_given_workspace);
            }

            _inlineRenameSessionDurationLogBlock = Logger.LogBlock(FunctionId.Rename_InlineSession, CancellationToken.None);

            _workspace = workspace;
            _workspace.WorkspaceChanged += OnWorkspaceChanged;

            _textBufferFactoryService        = textBufferFactoryService;
            _textBufferAssociatedViewService = textBufferAssociatedViewService;
            _textBufferAssociatedViewService.SubjectBuffersConnected += OnSubjectBuffersConnected;

            // Disable completion when an inline rename session starts
            _featureService          = featureServiceFactory.GlobalFeatureService;
            _completionDisabledToken = _featureService.Disable(PredefinedEditorFeatureNames.Completion, this);

            _renameService          = renameService;
            _waitIndicator          = waitIndicator;
            _refactorNotifyServices = refactorNotifyServices;
            _asyncListener          = asyncListener;
            _triggerView            = textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).FirstOrDefault(v => v.HasAggregateFocus) ??
                                      textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).First();

            _optionSet = renameInfo.ForceRenameOverloads
                ? workspace.Options.WithChangedOption(RenameOptions.RenameOverloads, true)
                : workspace.Options;

            _initialRenameText   = triggerSpan.GetText();
            this.ReplacementText = _initialRenameText;

            _baseSolution    = _triggerDocument.Project.Solution;
            this.UndoManager = workspace.Services.GetService <IInlineRenameUndoManager>();

            _debuggingWorkspaceService = workspace.Services.GetService <IDebuggingWorkspaceService>();
            _debuggingWorkspaceService.BeforeDebuggingStateChanged += OnBeforeDebuggingStateChanged;

            if (_renameInfo is IInlineRenameInfoWithFileRename renameInfoWithFileRename)
            {
                FileRenameInfo = renameInfoWithFileRename.GetFileRenameInfo();
            }
            else
            {
                FileRenameInfo = InlineRenameFileRenameInfo.NotAllowed;
            }

            InitializeOpenBuffers(triggerSpan);
        }
Example #38
0
        public IList <ClassificationSpan> GetClassificationSpans(SnapshotSpan span)         // from IClassifier
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            _snapshot = span.Snapshot;

            var appSettings = ProbeEnvironment.CurrentAppSettings;
            var fileName    = VsTextUtil.TryGetDocumentFileName(span.Snapshot.TextBuffer);

            var tracker   = TextBufferStateTracker.GetTrackerForTextBuffer(span.Snapshot.TextBuffer);
            var spans     = new List <ClassificationSpan>();
            var state     = tracker.GetStateForPosition(span.Start.Position, span.Snapshot, fileName, appSettings);
            var tokenInfo = new ProbeClassifierScanner.TokenInfo();

            var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(span.Snapshot.TextBuffer);

            if (fileStore == null)
            {
                return(new List <ClassificationSpan>());
            }

            var model = fileStore.GetMostRecentModel(appSettings, fileName, span.Snapshot, "GetClassificationSpans");

            _scanner.SetSource(span.GetText(), span.Start.Position, span.Snapshot, model);

            var disableDeadCode = ProbeToolsPackage.Instance.EditorOptions.DisableDeadCode;

            DisabledSectionTracker disabledSectionTracker = null;

            if (disableDeadCode)
            {
                disabledSectionTracker = new DisabledSectionTracker(model.DisabledSections);
                if (disabledSectionTracker.SetOffset(_scanner.PositionOffset))
                {
                    state |= State.Disabled;
                }
                else
                {
                    state &= ~State.Disabled;
                }
            }
            else
            {
                state &= ~State.Disabled;
            }

            while (_scanner.ScanTokenAndProvideInfoAboutIt(tokenInfo, ref state))
            {
                var classificationType = GetClassificationType(tokenInfo.Type);
                if (classificationType != null)
                {
                    spans.Add(new ClassificationSpan(new SnapshotSpan(_snapshot, new Span(span.Start.Position + tokenInfo.StartIndex, tokenInfo.Length)), classificationType));
                }

                if (disableDeadCode)
                {
                    if (disabledSectionTracker.Advance(_scanner.PositionOffset + _scanner.Position))
                    {
                        state |= State.Disabled;
                    }
                    else
                    {
                        state &= ~State.Disabled;
                    }
                }
                else
                {
                    state &= ~State.Disabled;
                }
            }

            return(spans);
        }
Example #39
0
        private bool TryGoToDefinition()
        {
            ITextBuffer buffer = _textView.TextBuffer;

            _classifier = _provider.ClassifierAggregatorService.GetClassifier(buffer);

            ITextSnapshot snapshot = buffer.CurrentSnapshot;

            XElement doc = ReadXmlDocument(snapshot.GetText());

            if (doc == null)
            {
                return(false);
            }

            if (doc.Name != NodeNameCommandTable)
            {
                return(false);
            }

            SnapshotPoint currentPoint = _textView.Caret.Position.BufferPosition;

            IList <ClassificationSpan> spans = _classifier.GetClassificationSpans(new SnapshotSpan(snapshot, 0, snapshot.Length));

            var firstSpans = spans
                             .Where(s => s.Span.Start < currentPoint.Position)
                             .OrderByDescending(s => s.Span.Start.Position)
                             .ToList();

            ClassificationSpan firstDelimiter = firstSpans.FirstOrDefault(s => s.ClassificationType.IsOfType("XML Attribute Quotes"));

            var lastSpans = spans
                            .Where(s => s.Span.Start >= currentPoint.Position)
                            .OrderBy(s => s.Span.Start.Position)
                            .ToList();

            ClassificationSpan lastDelimiter = lastSpans.FirstOrDefault(s => s.ClassificationType.IsOfType("XML Attribute Quotes"));

            SnapshotSpan?extentTemp = null;

            if (firstDelimiter != null && firstDelimiter.Span.GetText() == "\"\"" && firstDelimiter.Span.Contains(currentPoint))
            {
                extentTemp = new SnapshotSpan(firstDelimiter.Span.Start.Add(1), firstDelimiter.Span.Start.Add(1));
            }
            else if (firstDelimiter != null && lastDelimiter != null && firstDelimiter.Span.GetText() == "\"" && lastDelimiter.Span.GetText() == "\"")
            {
                extentTemp = new SnapshotSpan(firstDelimiter.Span.End, lastDelimiter.Span.Start);
            }

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

            SnapshotSpan extent = extentTemp.Value;

            var currentValue = extent.GetText();

            XElement currentXmlNode = GetCurrentXmlNode(doc, extent);

            if (currentXmlNode == null)
            {
                return(false);
            }

            var containingAttributeSpans = spans
                                           .Where(s => s.Span.Contains(extent.Start) &&
                                                  s.Span.Contains(extent) &&
                                                  s.ClassificationType.IsOfType("XML Attribute Value"))
                                           .OrderByDescending(s => s.Span.Start.Position)
                                           .ToList();

            ClassificationSpan containingAttributeValue = containingAttributeSpans.FirstOrDefault();

            if (containingAttributeValue == null)
            {
                containingAttributeValue = spans
                                           .Where(s => s.Span.Contains(extent.Start) &&
                                                  s.Span.Contains(extent) &&
                                                  s.ClassificationType.IsOfType("XML Attribute Quotes") &&
                                                  s.Span.GetText() == "\"\""
                                                  )
                                           .OrderByDescending(s => s.Span.Start.Position)
                                           .FirstOrDefault();
            }

            if (containingAttributeValue == null)
            {
                return(false);
            }

            ClassificationSpan currentAttr = GetCurrentXmlAttributeName(snapshot, containingAttributeValue, spans);

            if (currentAttr == null)
            {
                return(false);
            }

            var currentNodeName      = currentXmlNode.Name.LocalName;
            var currentAttributeName = currentAttr.Span.GetText();

            if (TryGoToDefinitionInCommandTable(snapshot, doc, currentXmlNode, currentNodeName, currentAttributeName, currentValue))
            {
                return(true);
            }

            return(false);
        }
        public IEnumerable <ITagSpan <IOutliningRegionTag> > GetTags(NormalizedSnapshotSpanCollection spans)
        {
            if (spans.Count == 0)
            {
                yield break;
            }

            List <Region> currentRegions  = this.regions;
            ITextSnapshot currentSnapshot = this.snapshot;
            SnapshotSpan  entire          = new SnapshotSpan(spans[0].Start, spans[spans.Count - 1].End).TranslateTo(currentSnapshot, SpanTrackingMode.EdgeExclusive);
            int           startLineNumber = entire.Start.GetContainingLine().LineNumber;
            int           endLineNumber   = entire.End.GetContainingLine().LineNumber;

            foreach (var region in currentRegions)
            {
                if (region.StartLine <= endLineNumber && region.EndLine >= startLineNumber)
                {
                    var startLine = currentSnapshot.GetLineFromLineNumber(region.StartLine);

                    // Note: if we revoke this condition, clicking (+) button 'twice' would expand the region while Ctrl+M,M works as expected.
                    if (!HasReservedBlockKeywords(startLine, "function", "module", "constructor", "void", "class"))
                    {
                        var endLine     = currentSnapshot.GetLineFromLineNumber(region.EndLine);
                        var contentSpan = new SnapshotSpan(startLine.Start + region.StartOffset, endLine.End);
                        //the region starts at the beginning of the "[", and goes until the *end* of the line that contains the "]".
                        yield return(new TagSpan <IOutliningRegionTag>(contentSpan, new OutliningRegionTag(false, false, ellipsis, contentSpan.GetText())));
                    }
                }
            }
        }
        private static void CommentSpan(
            Document document, ICommentSelectionService service, SnapshotSpan span,
            ArrayBuilder <TextChange> textChanges, ArrayBuilder <CommentTrackingSpan> trackingSpans, CancellationToken cancellationToken)
        {
            var(firstLine, lastLine) = DetermineFirstAndLastLine(span);

            if (span.IsEmpty && firstLine.IsEmptyOrWhitespace())
            {
                // No selection, and on an empty line, don't do anything.
                return;
            }

            if (!span.IsEmpty && string.IsNullOrWhiteSpace(span.GetText()))
            {
                // Just whitespace selected, don't do anything.
                return;
            }

            // Get the information from the language as to how they'd like to comment this region.
            var commentInfo = service.GetInfoAsync(document, span.Span.ToTextSpan(), cancellationToken).WaitAndGetResult(cancellationToken);

            if (!commentInfo.SupportsBlockComment && !commentInfo.SupportsSingleLineComment)
            {
                // Neither type of comment supported.
                return;
            }

            if (commentInfo.SupportsBlockComment && !commentInfo.SupportsSingleLineComment)
            {
                // Only block comments supported here.  If there is a span, just surround that
                // span with a block comment.  If tehre is no span then surround the entire line
                // with a block comment.
                if (span.IsEmpty)
                {
                    var firstNonWhitespaceOnLine = firstLine.GetFirstNonWhitespacePosition();
                    var insertPosition           = firstNonWhitespaceOnLine ?? firstLine.Start;

                    span = new SnapshotSpan(span.Snapshot, Span.FromBounds(insertPosition, firstLine.End));
                }

                AddBlockComment(span, textChanges, trackingSpans, commentInfo);
            }
            else if (!commentInfo.SupportsBlockComment && commentInfo.SupportsSingleLineComment)
            {
                // Only single line comments supported here.
                AddSingleLineComments(span, textChanges, trackingSpans, firstLine, lastLine, commentInfo);
            }
            else
            {
                // both comment forms supported.  Do a block comment only if a portion of code is
                // selected on a single line, otherwise comment out all the lines using single-line
                // comments.
                if (!span.IsEmpty &&
                    !SpanIncludesAllTextOnIncludedLines(span) &&
                    firstLine.LineNumber == lastLine.LineNumber)
                {
                    AddBlockComment(span, textChanges, trackingSpans, commentInfo);
                }
                else
                {
                    AddSingleLineComments(span, textChanges, trackingSpans, firstLine, lastLine, commentInfo);
                }
            }
        }
        /// <summary>
        /// Returns tags on demand.
        /// </summary>
        /// <param name="spans">Spans collection to get tags for.</param>
        /// <returns>Squiggle tags in provided spans.</returns>
        public IEnumerable <ITagSpan <IErrorTag> > GetTags(NormalizedSnapshotSpanCollection spans)
        {
            if (spans.Count == 0)
            {
                yield break;
            }

            ITextSnapshot snapshot = spans[0].Snapshot;

            foreach (var misspelling in _misspellingAggregator.GetTags(spans))
            {
                var misspellingSpans = misspelling.Span.GetSpans(snapshot);
                if (misspellingSpans.Count != 1)
                {
                    continue;
                }

                SnapshotSpan errorSpan = misspellingSpans[0];

                yield return(new TagSpan <IErrorTag>(
                                 errorSpan,
                                 new SpellSquiggleTag(SquiggleTagger.SpellingErrorType, errorSpan.GetText())));
            }
        }
Example #43
0
        protected virtual TaggedContentSpan TagComments(SnapshotSpan snapshotSpan, IMappingTagSpan <IClassificationTag> tagSpan)
        {
            // find spans that the language service has already classified as comments ...
            if (IsComment(tagSpan.Tag.ClassificationType) == false)
            {
                return(null);
            }
            var text = snapshotSpan.GetText();
            //NOTE: markup comment span does not include comment start token
            var endOfCommentStartToken = GetCommentStartIndex(text);

            if (endOfCommentStartToken < 0)
            {
                return(null);
            }
            var tl           = text.Length;
            var commentStart = endOfCommentStartToken;

            while (commentStart < tl)
            {
                if (Char.IsWhiteSpace(text[commentStart]))
                {
                    ++commentStart;
                }
                else
                {
                    break;
                }
            }

            var contentEnd = GetCommentEndIndex(text);

            ClassificationTag ctag  = null;
            CommentLabel      label = null;
            var contentStart        = 0;

            foreach (var item in Config.Instance.Labels)
            {
                var c = commentStart + item.LabelLength;
                if (c >= tl ||
                    text.IndexOf(item.Label, commentStart, item.Comparison) != commentStart)
                {
                    continue;
                }

                var followingChar = text[c];
                if (item.AllowPunctuationDelimiter && Char.IsPunctuation(followingChar))
                {
                    c++;
                }
                else if (!Char.IsWhiteSpace(followingChar))
                {
                    continue;
                }

                if (label == null || label.LabelLength < item.LabelLength)
                {
                    ctag         = __CommentClassifications[(int)item.StyleID];
                    label        = item;
                    contentStart = c;
                }
            }

            if (contentStart == 0 || ctag == null)
            {
                return(null);
            }

            // ignore whitespaces in content
            while (contentStart < tl)
            {
                if (Char.IsWhiteSpace(text[contentStart]))
                {
                    ++contentStart;
                }
                else
                {
                    break;
                }
            }
            while (contentEnd > contentStart)
            {
                if (Char.IsWhiteSpace(text[contentEnd - 1]))
                {
                    --contentEnd;
                }
                else
                {
                    break;
                }
            }

            return(label.StyleApplication == CommentStyleApplication.Tag
                                ? new TaggedContentSpan(ctag, snapshotSpan.Snapshot, snapshotSpan.Start + commentStart, label.LabelLength, contentStart - commentStart, contentEnd - contentStart)
                                : label.StyleApplication == CommentStyleApplication.Content
                                ? new TaggedContentSpan(ctag, snapshotSpan.Snapshot, snapshotSpan.Start + contentStart, contentEnd - contentStart, 0, contentEnd - contentStart)
                                : new TaggedContentSpan(ctag, snapshotSpan.Snapshot, snapshotSpan.Start + commentStart, contentEnd - commentStart, contentStart - commentStart, contentEnd - contentStart));
        }
Example #44
0
        public IEnumerable <ITagSpan <IOutliningRegionTag> > GetTags(NormalizedSnapshotSpanCollection spans)
        {
            if (spans.Count == 0)
            {
                yield break;
            }

            List <Region> currentRegions  = this.regions;
            ITextSnapshot currentSnapshot = this.snapshot;
            SnapshotSpan  entire          = new SnapshotSpan(spans[0].Start, spans[spans.Count - 1].End).TranslateTo(currentSnapshot, SpanTrackingMode.EdgeExclusive);
            int           startLineNumber = entire.Start.GetContainingLine().LineNumber;
            int           endLineNumber   = entire.End.GetContainingLine().LineNumber;

            foreach (var region in currentRegions)
            {
                if (region.StartLine <= endLineNumber && region.EndLine >= startLineNumber)
                {
                    var    startLine = currentSnapshot.GetLineFromLineNumber(region.StartLine);
                    string lineText  = startLine.GetText().Trim();

                    if (!lineText.Contains("function"))
                    {
                        var endLine     = currentSnapshot.GetLineFromLineNumber(region.EndLine);
                        var contentSpan = new SnapshotSpan(startLine.Start + region.StartOffset, endLine.End);
                        //the region starts at the beginning of the "[", and goes until the *end* of the line that contains the "]".
                        yield return(new TagSpan <IOutliningRegionTag>(contentSpan, new OutliningRegionTag(false, false, ellipsis, contentSpan.GetText())));
                    }
                }
            }
        }
Example #45
0
        private void ToolTipLegacy(SnapshotPoint triggerPoint, Point p)
        {
            DateTime      time1    = DateTime.Now;
            ITextSnapshot snapshot = this._textView.TextSnapshot;

            (AsmTokenTag tag, SnapshotSpan? keywordSpan) = AsmDudeToolsStatic.GetAsmTokenTag(this._aggregator, triggerPoint);
            if (keywordSpan.HasValue)
            {
                SnapshotSpan tagSpan      = keywordSpan.Value;
                string       keyword      = tagSpan.GetText();
                string       keywordUpper = keyword.ToUpper();

                //AsmDudeToolsStatic.Output_INFO(string.Format("{0}:ToolTipLegacy: keyword=\"{1}\"; type={2}; file=\"{3}\"", this.ToString(), keyword, tag.Type, AsmDudeToolsStatic.GetFilename(this._textView.TextBuffer)));
                ITrackingSpan applicableTo = snapshot.CreateTrackingSpan(tagSpan, SpanTrackingMode.EdgeInclusive);

                // check if a tooltip window is already visible for the applicable span
                if ((this._legacySpan != null) && this._legacySpan.OverlapsWith(tagSpan))
                {
                    AsmDudeToolsStatic.Output_INFO(string.Format("{0}:ToolTipLegacy: tooltip is already visible. span = {1}, content = {2}", this.ToString(), this._legacySpan.ToString(), applicableTo.GetText(this._textView.TextSnapshot)));
                    return;
                }

                switch (tag.Type)
                {
                case AsmTokenType.Mnemonic:     // intentional fall through
                case AsmTokenType.Jump:
                {
                    (Mnemonic mnemonic, AttType type) = AsmSourceTools.ParseMnemonic_Att(keywordUpper, true);

                    InstructionTooltipWindow instructionTooltipWindow = new InstructionTooltipWindow(AsmDudeToolsStatic.GetFontColor())
                    {
                        Owner = this,         // set the owner of this windows such that we can manually close this window
                    };
                    instructionTooltipWindow.SetDescription(mnemonic, AsmDudeTools.Instance);
                    instructionTooltipWindow.SetPerformanceInfo(mnemonic, AsmDudeTools.Instance);
                    instructionTooltipWindow.Margin = new Thickness(7.0);

                    Border border = new Border()
                    {
                        BorderBrush     = System.Windows.Media.Brushes.LightGray,
                        BorderThickness = new Thickness(1.0),
                        CornerRadius    = new CornerRadius(2.0),
                        Background      = AsmDudeToolsStatic.GetBackgroundColor(),
                        Child           = instructionTooltipWindow,
                    };

                    // cleanup old window remnants
                    if (this._legacyTooltipWindow != null)
                    {
                        AsmDudeToolsStatic.Output_INFO(string.Format("{0}:ToolTipLegacy: going to cleanup old window remnants.", this.ToString()));
                        if (this._legacyTooltipWindow.IsLoaded)
                        {
                            this._legacyTooltipWindow = null;
                        }
                        else
                        {
                            this._legacyTooltipWindow?.Close();
                        }
                    }

                    this._legacyTooltipWindow = new Window
                    {
                        WindowStyle   = WindowStyle.None,
                        ResizeMode    = ResizeMode.NoResize,
                        SizeToContent = SizeToContent.WidthAndHeight,
                        ShowInTaskbar = false,
                        Left          = p.X + 15, // placement slightly to the right
                        Top           = p.Y + 5,  // placement slightly lower such that the code that is selected is visible
                        //TODO find the space to the left and if not enough space is available, place the window more to the left
                        Content = border,
                    };
                    this._legacyTooltipWindow.LostKeyboardFocus += (o, i) =>
                    {
                        //AsmDudeToolsStatic.Output_INFO("AsmQuickInfoController:LostKeyboardFocus: going to close the tooltip window.");
                        try
                        {
                            (o as Window).Close();
                        }
                        catch (Exception e)
                        {
                            AsmDudeToolsStatic.Output_WARNING(string.Format("{0}:ToolTipLegacy: e={1}", this.ToString(), e.Message));
                        }
                    };
                    this._legacySpan = tagSpan;
                    this._legacyTooltipWindow.Show();
                    this._legacyTooltipWindow.Focus();         //give the tooltip window focus, such that we can use the lostKeyboardFocus event to close this window;
                    break;
                }

                default: break;
                }
                //AsmDudeToolsStatic.Output_INFO("AsmQuickInfoSource:AugmentQuickInfoSession: applicableToSpan=\"" + applicableToSpan + "\"; quickInfoContent,Count=" + quickInfoContent.Count);
                AsmDudeToolsStatic.Print_Speed_Warning(time1, "QuickInfo ToolTipLegacy");
            }
        }
Example #46
0
        public virtual IList <ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            if (m_textBuffer.EditInProgress || span.IsEmpty)
            {
                return(s_EmptySpan);
            }

            List <ClassificationSpan> classifications = new List <ClassificationSpan>();
            ClassificationSpan        cspan           = new ClassificationSpan(span, _stringClassificationType);
            var lines   = span.GetText().TrimEnd();
            int baseoff = 0;

            foreach (var line in lines.Split('\n'))
            {
                if (line.Length == 0)
                {
                    baseoff++;
                    continue;
                }
                int off = 0;
                while (isWhitespace(line[off]))
                {
                    off++;
                }

                int skip = 1;
                switch (line[off])
                {
                case '#':
                {
                    off++;
                    while (isWhitespace(line[off]))
                    {
                        off++;
                        skip++;
                    }

                    if (line.IndexOfAny(new [] { ' ', '\t', '\v' }, off) < 0)
                    {
                        classifications.Add(CreateClassificationSpan(span, span.Start + off - skip, skip, _commentClassificationType, new haruna.mutable.ClassifierDefinition()
                            {
                                classifier = haruna.Constants.classifier_nsis_comment
                            }));
                        cspan = CreateClassificationSpan(span, span.Start + off, line.Length - off, _macroClassificationType, new haruna.mutable.ClassifierDefinition()
                            {
                                classifier = haruna.Constants.classifier_nsis_condition
                            });
                    }
                    else
                    {
                        off  -= skip;
                        cspan = CreateClassificationSpan(span, span.Start + off, line.Length - off, _commentClassificationType, new haruna.mutable.ClassifierDefinition()
                            {
                                classifier = haruna.Constants.classifier_nsis_comment
                            });
                    }
                }
                break;

                case ';':
                {
                    cspan = CreateClassificationSpan(span, span.Start + off, line.Length - off, _commentClassificationType, new haruna.mutable.ClassifierDefinition()
                        {
                            classifier = haruna.Constants.classifier_nsis_comment
                        });
                }
                break;

                default:
                    cspan = CreateClassificationSpan(span, span.Start + off, line.Length - off, _stringClassificationType, new haruna.mutable.ClassifierDefinition()
                    {
                        classifier = haruna.Constants.classifier_nsis_string
                    });
                    break;
                }
                classifications.Add(cspan);
            }
            return(classifications);
        }
 static bool HasInvalidFileExtension(SnapshotSpan span) => !span.GetText().StripQuotation().ToLower().EndsWithAny(".master", ".ascx");
Example #48
0
        private void CreateTag(SyntaxToken startToken, SyntaxToken endToken, bool isImplementation)
        {
            if (startToken == null || !startToken.Span.IsInRootFile ||
                endToken == null || !endToken.Span.IsInRootFile)
            {
                return;
            }

            var span = new Span(startToken.Span.End, endToken.Span.End - startToken.Span.End);

            if (_snapshot.GetLineNumberFromPosition(span.Start) == _snapshot.GetLineNumberFromPosition(span.End))
            {
                return;
            }

            var snapshotSpan = new SnapshotSpan(_snapshot, span);
            var tag          = new OutliningRegionTag(false, isImplementation, "...", snapshotSpan.GetText());
            var tagSpan      = new TagSpan <IOutliningRegionTag>(snapshotSpan, tag);

            _results.Add(tagSpan);
        }
Example #49
0
        public IEnumerable <ITagSpan <IUrlTag> > GetTags(NormalizedSnapshotSpanCollection spans)
        {
            if (!enableLinks)
            {
                yield break;
            }

            ITextSnapshotLine line = null;

            foreach (var span in spans)
            {
                int pos = span.Start;

                // We check full lines so make sure we don't re-check the same line again
                if (line != null && line.ExtentIncludingLineBreak.End.Position > pos)
                {
                    continue;
                }

                for (;;)
                {
                    if (line != null && line.ExtentIncludingLineBreak.End.Position == pos)
                    {
                        if (line.Snapshot.LineCount == line.LineNumber + 1)
                        {
                            break;
                        }
                        line = line.Snapshot.GetLineFromLineNumber(line.LineNumber + 1);
                    }
                    else
                    {
                        Debug.Assert(line == null || pos > line.ExtentIncludingLineBreak.End.Position);
                        line = span.Snapshot.GetLineFromPosition(pos);
                    }

                    if (line.Length != 0 && line.Length <= maxLineLength)
                    {
                        var lineText  = line.GetText();
                        var uriFinder = new UriFinder(lineText);
                        for (;;)
                        {
                            var res = uriFinder.GetNext();
                            if (res == null)
                            {
                                break;
                            }
                            Debug.Assert(res.Value.Length != 0);
                            if (res.Value.Length == 0)
                            {
                                break;
                            }
                            int start = line.Start.Position + res.Value.Start;
                            int end   = start + res.Value.Length;
                            Debug.Assert(end <= line.Snapshot.Length);
                            if (end > line.Snapshot.Length)
                            {
                                break;
                            }
                            var uriSpan = new SnapshotSpan(line.Snapshot, start, res.Value.Length);
                            var uri     = TryCreateUri(uriSpan.GetText());
                            if (uri == null)
                            {
                                continue;
                            }
                            yield return(new TagSpan <IUrlTag>(uriSpan, new UrlTag(uri)));
                        }
                    }

                    pos = line.ExtentIncludingLineBreak.End;
                    if (pos >= span.End)
                    {
                        break;
                    }
                }
            }
        }
        public IEnumerable <ITagSpan <TextMarkerTag> > GetTags(NormalizedSnapshotSpanCollection spans)
        {
            if (!settings.XmlMatchTagsEnabled)
            {
                yield break;
            }
            if (spans.Count == 0)
            {
                yield break;
            }
            if (!currentSpan.HasValue)
            {
                yield break;
            }

            SnapshotSpan current = currentSpan.Value;

            if (current.Snapshot != spans[0].Snapshot)
            {
                current = current.TranslateTo(spans[0].Snapshot, SpanTrackingMode.EdgePositive);
            }

            SnapshotSpan currentTag = CompleteTag(current);
            String       text       = currentTag.GetText();

            // avoid processing statements or xml declarations
            if (text.Contains('?'))
            {
                yield break;
            }

            SnapshotSpan?complementTag = null;

            if (text.StartsWith("</"))
            {
                complementTag = FindOpeningTag(current.Snapshot, currentTag.End, current.GetText());
                if (complementTag != null)
                {
                    complementTag = ExtendOpeningTag(complementTag.Value);
                }
            }
            else
            {
                String searchFor = "</" + current.GetText() + ">";
                currentTag    = ExtendOpeningTag(currentTag);
                complementTag = FindClosingTag(current.Snapshot, currentTag.Start, searchFor);
            }

            var defaultTag   = new TextMarkerTag("bracehighlight");
            var alternateTag = new TextMarkerTag("other error");

            if (complementTag.HasValue)
            {
                yield return(new TagSpan <TextMarkerTag>(currentTag, defaultTag));

                yield return(new TagSpan <TextMarkerTag>(complementTag.Value, defaultTag));
            }
            else
            {
                // no matching tag found, or element has no content
                yield return(new TagSpan <TextMarkerTag>(currentTag,
                                                         currentTag.GetText().EndsWith("/>") ? defaultTag : alternateTag));
            }
        }