private void OnPostChanged(object sender, EventArgs e) { if (!_changeSpan.HasValue) { return; } var changeSpan = _changeSpan.Value; var snapshot = _textBuffer.CurrentSnapshot; var text = snapshot.GetText(changeSpan); if (text.Length == GenerateKey.Length && _comparer.Equals(text, GenerateKey)) { InsertGuid(changeSpan); _changeSpan = null; } else if (text.Length >= GenerateKey.Length) { _changeSpan = null; } else if (!GenerateKey.StartsWith(text, StringComparison.OrdinalIgnoreCase)) { _changeSpan = null; } }
public void NavigateToFile(FileEntryViewModel fileEntry, Span?span) { // Using "Post" is important: it allows the newly opened document to // receive the focus. SynchronizationContextProvider.UIContext.Post(() => OpenDocumentHelper.OpenDocument(fileEntry.Path, _ => span)); }
private static int Distance(Span?maybeA, TextSpan?maybeB) { // If we don't have a text span or target point we cannot calculate the distance between them if (!maybeA.HasValue || !maybeB.HasValue) { return(int.MaxValue); } var a = maybeA.Value; var b = maybeB.Value; // The distance of two spans is symetric sumation of: // - the distance of a's start to b's start // - the distance of a's end to b's end // // This particular metric has been chosen because it is both simple // and uses the all the information in both spans. A weighting (i.e. // the distance of starts is more important) could be added but it // didn't seem necessary. // // E.g.: for spans [ ] and $ $ the distance is distanceOfStarts+distanceOfEnds: // $ $ [ ] has distance 2+3 // $ [ ]$ has distance 1+0 // $[ ]$ has distance 0+0 // $ [] $ has distance 1+3 // $[] $ has distance 0+4 var startsDistance = Math.Abs(a.Start - b.Start); var endsDistance = Math.Abs(a.End - b.End); return(startsDistance + endsDistance); }
public void Tokenizer_ShouldTokenizeExpWithoutErrors(string file) { using (var stream = File.Open($@"..\..\..\..\test\{file}.exp", FileMode.Open, FileAccess.Read)) using (var reader = new StreamReader(stream)) { var errors = new List <ParsingError>(); var tokens = Tokenizer.Tokenize(reader, errors).ToArray(); foreach (var error in errors) { Console.WriteLine(error.ToString()); } Span?lastSpan = null; foreach (var token in tokens) { if (token == Token.Eof) { break; } Assert.IsTrue(token.Span.Start < token.Span.End); if (lastSpan.HasValue) { Assert.IsTrue(token.Span.Start >= lastSpan.Value.End); } lastSpan = token.Span; } Assert.AreEqual(0, errors.Count); } }
private static void IgnoreActivity <T>(T activity, Span?span) where T : IActivity { if (span is not null && activity is IW3CActivity w3cActivity) { if (activity.Parent is null || activity.Parent.StartTimeUtc < span.StartTime.UtcDateTime) { // If we ignore the activity and there's an existing active span // We modify the activity spanId with the one in the span // The reason for that is in case this ignored activity is used // for propagation then the current active span will appear as parentId // in the context propagation, and we will keep the entire trace. // TraceId w3cActivity.TraceId = string.IsNullOrWhiteSpace(span.Context.RawTraceId) ? span.TraceId.ToString() : span.Context.RawTraceId; // SpanId w3cActivity.ParentSpanId = string.IsNullOrWhiteSpace(span.Context.RawSpanId) ? span.SpanId.ToString("x16") : span.Context.RawSpanId; // We clear internals Id and ParentId values to force recalculation. w3cActivity.RawId = null; w3cActivity.RawParentId = null; } } }
private static (int index, bool containsPoint) IndexOfTagSpanNearPoint(NormalizedSpanCollection spans, int point) { Debug.Assert(spans.Count > 0); Span?tagBefore = null; Span?tagAfter = null; for (int i = 0; i < spans.Count; i++) { tagBefore = tagAfter; tagAfter = spans[i]; // Case 0: point falls within error tag. We use explicit comparisons instead // of 'Contains' so that we match a tag even if the caret at the end of it. if ((point >= tagAfter.Value.Start) && (point <= tagAfter.Value.End)) { // Return tag containing the point. return(i, true); } // Case 1: point falls between two tags. if ((tagBefore != null) && (tagBefore.Value.End < point) && (tagAfter.Value.Start > point)) { // Return tag following the point. return(i, false); } } // Case 2: point falls after all tags. return(-1, false); }
/// <summary> /// Checks if a tag's header is visible /// </summary> /// <param name="start">Start position of code block</param> /// <param name="end">End position of code block</param> /// <param name="visibleSpan">the visible span in the textview</param> /// <param name="snapshot">reference to text snapshot. Used for caret check</param> /// <returns>true if the tag is visible (or if all tags are shown)</returns> private bool IsTagVisible(int start, int end, Span?visibleSpan, ITextSnapshot snapshot) { var isVisible = false; // Check general condition if (CBETagPackage.CBEVisibilityMode == (int)CBEOptionPage.VisibilityModes.Always || !visibleSpan.HasValue) { isVisible = true; } // Check visible span if (!isVisible) { var val = visibleSpan.Value; isVisible = (start < val.Start && end >= val.Start && end <= val.End); } // Check if caret is in this line if (isVisible && _TextView != null) { var caretIndex = _TextView.Caret.Position.BufferPosition.Position; var lineStart = Math.Min(caretIndex, end); var lineEnd = Math.Max(caretIndex, end); if (lineStart == lineEnd) { return(false); } else if (lineStart >= 0 && lineEnd <= snapshot.Length) { var line = snapshot.GetText(lineStart, lineEnd - lineStart); return(line.Contains('\n')); } } return(isVisible); }
private static List <Tuple <string, string> > Classify(string markdown, Span?subSpan = null) { if (subSpan == null) { var spanStart = markdown.IndexOf("(<"); if (spanStart >= 0) { markdown = markdown.Remove(spanStart, 2); var spanEnd = markdown.IndexOf(">)", spanStart); if (spanEnd < 0) { throw new ArgumentException("Markdown (<...>) span indicator must be well-formed", "markdown"); } markdown = markdown.Remove(spanEnd, 2); subSpan = Span.FromBounds(spanStart, spanEnd); } } var crlf = newline.Replace(markdown, "\r\n"); var lf = newline.Replace(markdown, "\n"); var cr = newline.Replace(markdown, "\r"); // Test newline equivalence on the full source // string. We cannot pass the subspan because // newline replacements will move its indices. // Also, this part is only to test the parser, // which doesn't get subspans anyway. var fullResult = RunParseCase(crlf); RunParseCase(lf).Should().Equal(fullResult, "LF should be the same as CRLF"); RunParseCase(cr).Should().Equal(fullResult, "CR should be the same as CRLF"); return(RunParseCase(markdown, subSpan)); }
/// <summary> /// Attempts to insert Roxygen documentation block based /// on the user function signature. /// </summary> public static bool TryInsertBlock(ITextBuffer textBuffer, AstRoot ast, int position) { // First determine if position is right before the function declaration var snapshot = textBuffer.CurrentSnapshot; ITextSnapshotLine line = null; var lineNumber = snapshot.GetLineNumberFromPosition(position); for (int i = lineNumber; i < snapshot.LineCount; i++) { line = snapshot.GetLineFromLineNumber(i); if (line.Length > 0) { break; } } if (line == null || line.Length == 0) { return(false); } Variable v; int offset = line.Length - line.GetText().TrimStart().Length + 1; if (line.Start + offset >= snapshot.Length) { return(false); } IFunctionDefinition fd = FunctionDefinitionExtensions.FindFunctionDefinition(textBuffer, ast, line.Start + offset, out v); if (fd != null && v != null && !string.IsNullOrEmpty(v.Name)) { int definitionStart = Math.Min(v.Start, fd.Start); Span?insertionSpan = GetRoxygenBlockPosition(snapshot, definitionStart); if (insertionSpan.HasValue) { string lineBreak = snapshot.GetLineFromPosition(position).GetLineBreakText(); if (string.IsNullOrEmpty(lineBreak)) { lineBreak = "\n"; } string block = GenerateRoxygenBlock(v.Name, fd, lineBreak); if (block.Length > 0) { if (insertionSpan.Value.Length == 0) { textBuffer.Insert(insertionSpan.Value.Start, block + lineBreak); } else { textBuffer.Replace(insertionSpan.Value, block); } return(true); } } } return(false); }
public void Add(IGlyphTextMarkerImpl marker, Span?span) { allMarkers.Add(marker); if (span != null) { inDocMarkers.Add(marker, span.Value); } }
public ImagePreviewToolTipMouseProcessor(IWpfTextView view, ITextStructureNavigator navigator, IToolTipProviderFactory toolTipProviderFactory, ITextDocument textDocument) { this.spanSearcher = new StringSpanSearcher(view, navigator); this.toolTipProvider = toolTipProviderFactory.GetToolTipProvider(view); this.textDocument = textDocument; this.shownSpan = null; }
void ClearToolTipIfShown() { if (shownSpan == null) { return; } this.shownSpan = null; this.toolTipProvider.ClearToolTip(); }
private bool TryParseEscapeSequence(ref StringPart part) { int start = this.text.Position; text.Next(); if (escapeChar.IndexOf(text.Char()) >= 0) { text.Next(); part = new StringPart(new Span(text.Position - 2, 2)); return(true); } if (Char.IsDigit(text.Char()) && Char.IsDigit(text.NChar()) && Char.IsDigit(text.NNChar())) { // a trigraph text.Skip(3); part = new StringPart(new Span(text.Position - 4, 4)); return(true); } if (text.Char() == '0' && !Char.IsDigit(text.NChar())) { // \0 text.Next(); part = new StringPart(new Span(text.Position - 2, 2)); return(true); } if (text.Char() == 'u') { text.Next(); text.Mark(); Span?span = TryParseShortUnicode(); if (span.HasValue) { part = new StringPart(span.Value); return(true); } text.BackToMark(); } if (text.Char() == 'U') { text.Next(); text.Mark(); Span?span = TryParseLongUnicode(); if (span.HasValue) { part = new StringPart(span.Value); return(true); } text.BackToMark(); } // unrecognized sequence, return it as error text.Next(); int length = text.Position - start; part = new StringPart(new Span(start, length), StringPartType.EscapeSequenceError); return(true); }
private async Task <(DocumentId?, SyntaxNode?)> GetDocumentIdAndNodeAsync( Solution solution, CodeLensDescriptor descriptor, Span?span, CancellationToken cancellationToken ) { if (span is null) { return(default);
public TextSpan?Intersection(Span span) { Span?intersection = this.Span.Intersection(span); if (intersection.HasValue) { return(new TextSpan?(new TextSpan(this.LineBreaks, intersection.Value))); } return(null); }
public static bool IgnoreByOperationName <T>(T activity, Span?span) where T : IActivity { if (ShouldIgnoreByOperationName(activity)) { IgnoreActivity(activity, span); return(true); } return(false); }
public Span?Next() { while (!text.EndOfLine) { if (text.Char() == '\\') { text.Next(); if (escapeChar.IndexOf(text.Char()) >= 0) { text.Next(); return(new Span(text.Position - 2, 2)); } if (Char.IsDigit(text.Char()) && Char.IsDigit(text.NChar()) && Char.IsDigit(text.NNChar())) { // a trigraph text.Skip(3); return(new Span(text.Position - 4, 4)); } if (text.Char() == '0' && !Char.IsDigit(text.NChar())) { // \0 text.Next(); return(new Span(text.Position - 2, 2)); } if (text.Char() == 'u') { text.Next(); text.Mark(); Span?span = TryParseShortUnicode(); if (span.HasValue) { return(span.Value); } text.BackToMark(); } if (text.Char() == 'U') { text.Next(); text.Mark(); Span?span = TryParseLongUnicode(); if (span.HasValue) { return(span.Value); } text.BackToMark(); } } else { text.Next(); } } return(null); }
private static List <Tuple <string, string> > RunParseCase(string markdown, Span?subSpan = null) { var artifacts = new ArtifactCollection(new MarkdownCodeArtifactProcessor()); artifacts.Build(markdown); var classifier = new MarkdownClassifier(artifacts, new MockClassificationTypeRegistry()); return(classifier.GetClassificationSpans(new SnapshotSpan(new MockSnapshot(markdown), subSpan ?? new Span(0, markdown.Length))) .Select(cs => Tuple.Create(cs.ClassificationType.Classification, markdown.Substring(cs.Span.Start, cs.Span.Length))) .ToList()); }
public TextSpan?Overlap(Span span) { Span?overlap = this.Span.Overlap(span); if (overlap.HasValue) { return(new TextSpan?(new TextSpan(this.LineBreaks, overlap.Value))); } return(null); }
public static Span Union(this Span x, Span?y) { if (y == null) { return(x); } return(Span.FromBounds( Math.Min(x.Start, y.Value.Start), Math.Max(x.End, y.Value.End))); }
public static Span Union(this Span x, Span?y) { if (y is not { } other) { return(x); } return(Span.FromBounds( Math.Min(x.Start, other.Start), Math.Max(x.End, other.End))); }
public void Add(IGlyphTextMarkerImpl marker, Span?span) { allMarkers.Add(marker); if (span != null) { inDocMarkers.Add(marker, span.Value); if (marker.SelectedMarkerTypeName != null) { SelectedMarkersInDocumentCount++; } } }
protected override void Write(WpfRenderer renderer, EmphasisInline obj) { if (renderer == null) { throw new ArgumentNullException(nameof(renderer)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } Span?span = null; switch (obj.DelimiterChar) { case '*': case '_': span = obj.DelimiterCount == 2 ? (Span) new Bold() : new Italic(); break; case '~': span = new Span(); span.SetResourceReference(FrameworkContentElement.StyleProperty, obj.DelimiterCount == 2 ? Styles.StrikeThroughStyleKey : Styles.SubscriptStyleKey); break; case '^': span = new Span(); span.SetResourceReference(FrameworkContentElement.StyleProperty, Styles.SuperscriptStyleKey); break; case '+': span = new Span(); span.SetResourceReference(FrameworkContentElement.StyleProperty, Styles.InsertedStyleKey); break; case '=': span = new Span(); span.SetResourceReference(FrameworkContentElement.StyleProperty, Styles.MarkedStyleKey); break; } if (span != null) { renderer.Push(span); renderer.WriteChildren(obj); renderer.Pop(); } else { renderer.WriteChildren(obj); } }
/// <summary> /// Returns the overlap with the given span, or null if there is no overlap. /// </summary> /// <param name="simpleSpan">The span to check.</param> /// <returns>The overlap of the spans, or null if the overlap is empty.</returns> public SnapshotSpan?Overlap(Span simpleSpan) { Span?overlap = this.Span.Overlap(simpleSpan); if (overlap != null) { return(new SnapshotSpan(this.Snapshot, overlap.Value)); } else { return(null); } }
public override int Read() { CheckDisposed(); if (_position == End) { return -1; } else if (_bufferSpan == null || !(_position >= _bufferSpan.Value.Start && _position < _bufferSpan.Value.End)) { int bufferLength = Math.Min(BufferSize, _snapshot.Length - _position); _buffer = _snapshot.GetText(_position, bufferLength); _bufferSpan = new Span(_position, bufferLength); } return _buffer[_position++ - _bufferSpan.Value.Start]; }
public override void Write(string text, object reference, DecompilerReferenceFlags flags, object color) { if (reference == this.reference && (flags & DecompilerReferenceFlags.Definition) != 0 && referenceSpan == null) { int start = NextPosition; base.Write(text, reference, flags, color); referenceSpan = new Span(start, Length - start); } else { base.Write(text, reference, flags, color); } }
/// <summary> /// Computes the intersection with the given span, or null if there is no intersection. /// </summary> /// <param name="simpleSpan"> /// The span to check. /// </param> /// <returns> /// The intersection of the spans, or null if the intersection is empty. /// </returns> public SnapshotSpan?Intersection(Span simpleSpan) { Span?intersection = this.Span.Intersection(simpleSpan); if (intersection != null) { return(new SnapshotSpan(this.Snapshot, intersection.Value)); } else { return(null); } }
/// <summary> /// Constructs an instance of the <see cref="IStructureTag"/>. /// </summary> /// <remarks> /// StructureTag is intended to replace <see cref="IBlockTag"/> and offers more explicit control /// of the block structure adornments. This class operates on the pay-to-play principle, in that, /// it will allow you to create a tag with just a subset of fields, but if a field is missing, it /// will attempt to guess the missing fields from the information that it has. The most useful example /// of this is to omit the GuideLineSpan and GuideLineHorizontalAnchor point to have the API guess /// them from the HeaderSpan and StatementSpan indentation. If enough information is missing, the tag /// does nothing. /// </remarks> /// <param name="snapshot">The snapshot used to generate this StructureTag.</param> /// <param name="outliningSpan">The block contents, used to determine the collapse region.</param> /// <param name="headerSpan">The control statement at the start of the block.</param> /// <param name="guideLineSpan"> /// The vertical span within which the block structure guide is drawn. /// If this member is omitted, it is computed from the HeaderSpan and the OutliningSpan via heuristics.</param> /// <param name="guideLineHorizontalAnchor"> /// A point capturing the horizontal offset at which the guide is drawn. /// If this member is omitted, it is computed from the HeaderSpan and the OutliningSpan via heuristics.</param> /// <param name="type">The structure type of the block.</param> /// <param name="isCollapsible">If true, block will have block adornments.</param> /// <param name="isDefaultCollapsed">If true, block is collapsed by default.</param> /// <param name="isImplementation">Defines whether or not the block defines a region following a function declaration.</param> /// <param name="collapsedForm">The form the block appears when collapsed.</param> /// <param name="collapsedHintForm">The form of the collapsed region tooltip.</param> public StructureTag( ITextSnapshot snapshot, Span?outliningSpan = null, Span?headerSpan = null, Span?guideLineSpan = null, int?guideLineHorizontalAnchor = null, string type = null, bool isCollapsible = false, bool isDefaultCollapsed = false, bool isImplementation = false, object collapsedForm = null, object collapsedHintForm = null) { if (snapshot == null) { throw new ArgumentNullException(nameof(snapshot)); } if (outliningSpan != null && outliningSpan.Value.End > snapshot.Length) { throw new ArgumentOutOfRangeException(nameof(outliningSpan)); } if (headerSpan != null && headerSpan.Value.End > snapshot.Length) { throw new ArgumentOutOfRangeException(nameof(headerSpan)); } if (guideLineSpan != null && guideLineSpan.Value.End > snapshot.Length) { throw new ArgumentOutOfRangeException(nameof(guideLineSpan)); } if (guideLineHorizontalAnchor != null && guideLineHorizontalAnchor.Value > snapshot.Length) { throw new ArgumentOutOfRangeException(nameof(guideLineHorizontalAnchor)); } this.Snapshot = snapshot; this.OutliningSpan = outliningSpan; this.HeaderSpan = headerSpan; this.GuideLineSpan = guideLineSpan; this.GuideLineHorizontalAnchorPoint = guideLineHorizontalAnchor; this.Type = type; this.IsCollapsible = isCollapsible; this.IsDefaultCollapsed = isDefaultCollapsed; this.IsImplementation = isImplementation; this.collapsedForm = collapsedForm; this.collapsedHintForm = collapsedHintForm; }
private void OnTextViewLayoutChanged(object sender, TextViewLayoutChangedEventArgs e) { // get new visible span var visibleSpan = GetVisibleSpan(_TextView); if (visibleSpan == null || !visibleSpan.HasValue) { return; } // only if new visible span is different from old if (!_VisibleSpan.HasValue || _VisibleSpan.Value.Start != visibleSpan.Value.Start || _VisibleSpan.Value.End < visibleSpan.Value.End) { // invalidate new and/or old visible span List <Span> invalidSpans = new List <Span>(); var newSpan = visibleSpan.Value; if (!_VisibleSpan.HasValue) { invalidSpans.Add(newSpan); } else { var oldSpan = _VisibleSpan.Value; // invalidate two spans if old and new do not overlap if (newSpan.Start > oldSpan.End || newSpan.End < oldSpan.Start) { invalidSpans.Add(newSpan); invalidSpans.Add(oldSpan); } else { // invalidate one big span (old and new joined) invalidSpans.Add(newSpan.Join(oldSpan)); } } _VisibleSpan = visibleSpan; // refresh tags foreach (var span in invalidSpans) { if (CBETagPackage.CBEVisibilityMode != (int)CBEOptionPage.VisibilityModes.Always) { InvalidateSpan(span, false); } } } }
private bool TryParseEscapeSequence(ref StringPart part) { text.Next(); if (escapeChar.IndexOf(text.Char()) >= 0) { text.Next(); part = new StringPart(new Span(text.Position - 2, 2)); return(true); } if (Char.IsDigit(text.Char()) && Char.IsDigit(text.NChar()) && Char.IsDigit(text.NNChar())) { // a trigraph text.Skip(3); part = new StringPart(new Span(text.Position - 4, 4)); return(true); } if (text.Char() == '0' && !Char.IsDigit(text.NChar())) { // \0 text.Next(); part = new StringPart(new Span(text.Position - 2, 2)); return(true); } if (text.Char() == 'u') { text.Next(); text.Mark(); Span?span = TryParseShortUnicode(); if (span.HasValue) { part = new StringPart(span.Value); return(true); } text.BackToMark(); } if (text.Char() == 'U') { text.Next(); text.Mark(); Span?span = TryParseLongUnicode(); if (span.HasValue) { part = new StringPart(span.Value); return(true); } text.BackToMark(); } return(false); }
public void GetWordSpan(string content, int position, int start, int length) { var tb = new TextBufferMock(content, RContentTypeDefinition.ContentType); Span?span = RTextStructure.GetWordSpan(tb.CurrentSnapshot, position); if (span.HasValue) { span.Value.Start.Should().Be(start); span.Value.Length.Should().Be(length); } else { length.Should().Be(0); start.Should().Be(0); } }
private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e) { _foregroundObject.AssertIsForeground(); // The formatted span refers to the span of the textview's buffer that is visible. // If it changes, then we want to reclassify. Note: the span might not change if // text were overwritten. However, in the case of text-edits, we'll hear about // through other means as we have an EventSource for that purpose. This event // source is for knowing if the user moves the view around. This handles direct // moves using the caret/scrollbar, as well as moves that happen because someone // jumped directly to a location using goto-def. It also handles view changes // caused by the user collapsing an outlining region. var lastSpan = _span; var lastViewTextSnapshot = _viewTextSnapshot; var lastViewVisualSnapshot = _viewVisualSnapshot; _span = _textView.TextViewLines.FormattedSpan.Span; _viewTextSnapshot = _textView.TextSnapshot; _viewVisualSnapshot = _textView.VisualSnapshot; if (_span != lastSpan) { // The span changed. This could have happened for a few different reasons. // If none of the view's text snapshots changed, then it was because of scrolling. if (_viewTextSnapshot == lastViewTextSnapshot && _viewVisualSnapshot == lastViewVisualSnapshot) { // We scrolled. RaiseChanged(_scrollChangeDelay); } else { // text changed in some way. RaiseChanged(_textChangeDelay); } } }
/// <summary> /// Constructor /// </summary> /// <param name="reference">Reference or null</param> /// <param name="flags">Flags</param> public TextReference(object reference, DecompilerReferenceFlags flags) { Reference = reference; Flags = flags; Span = null; }
/// <summary> /// Constructor /// </summary> /// <param name="reference">Reference or null</param> /// <param name="flags">Flags</param> /// <param name="span">Span</param> public TextReference(object reference, DecompilerReferenceFlags flags, Span span) { Reference = reference; Flags = flags; Span = span; }