internal int ComputeCurrentParameter(ITextSnapshot snapshot, AstRoot ast, int position) { ParameterInfo parameterInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, snapshot, position); int index = 0; if (parameterInfo != null) { index = parameterInfo.ParameterIndex; if (parameterInfo.NamedParameter) { // A function f <- function(foo, bar) is said to have formal parameters "foo" and "bar", // and the call f(foo=3, ba=13) is said to have (actual) arguments "foo" and "ba". // R first matches all arguments that have exactly the same name as a formal parameter. // Two identical argument names cause an error. Then, R matches any argument names that // partially matches a(yet unmatched) formal parameter. But if two argument names partially // match the same formal parameter, that also causes an error. Also, it only matches // formal parameters before ... So formal parameters after ... must be specified using // their full names. Then the unnamed arguments are matched in positional order to // the remaining formal arguments. int argumentIndexInSignature = _signatureInfo.GetArgumentIndex(parameterInfo.ParameterName, REditorSettings.PartialArgumentNameMatch); if (argumentIndexInSignature >= 0) { index = argumentIndexInSignature; } } } return index; }
public static ITagSpan<IClassificationTag> ToTagSpan(this TextSpan span, ITextSnapshot snapshot, IClassificationType classificationType) { return new TagSpan<IClassificationTag>( new SnapshotSpan(snapshot, span.Start, span.Length), new ClassificationTag(classificationType) ); }
private AlloyOutliningTaggerWalker(ITreeNodeStream input, ReadOnlyCollection<IToken> tokens, AlloyOutliningTaggerProvider provider, ITextSnapshot snapshot) : base(input, snapshot, provider.OutputWindowService) { _tokens = tokens; _provider = provider; _snapshot = snapshot; }
internal static AntlrParseResultEventArgs ParseSnapshot(ITextSnapshot snapshot) { Stopwatch timer = Stopwatch.StartNew(); ITokenSource tokenSource = new GrammarLexer(new AntlrInputStream(snapshot.GetText())); CommonTokenStream tokenStream = new CommonTokenStream(tokenSource); GrammarParser.GrammarSpecContext parseResult; GrammarParser parser = new GrammarParser(tokenStream); List<ParseErrorEventArgs> errors = new List<ParseErrorEventArgs>(); try { parser.Interpreter.PredictionMode = PredictionMode.Sll; parser.RemoveErrorListeners(); parser.BuildParseTree = true; parser.ErrorHandler = new BailErrorStrategy(); parseResult = parser.grammarSpec(); } catch (ParseCanceledException ex) { if (!(ex.InnerException is RecognitionException)) throw; tokenStream.Reset(); parser.Interpreter.PredictionMode = PredictionMode.Ll; //parser.AddErrorListener(DescriptiveErrorListener.Default); parser.SetInputStream(tokenStream); parser.ErrorHandler = new DefaultErrorStrategy(); parseResult = parser.grammarSpec(); } return new AntlrParseResultEventArgs(snapshot, errors, timer.Elapsed, tokenStream.GetTokens(), parseResult); }
private GherkinFileScopeChange FullParse(ITextSnapshot textSnapshot, GherkinDialect gherkinDialect) { visualStudioTracer.Trace("Start full parsing", ParserTraceCategory); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); partialParseCount = 0; var gherkinListener = new GherkinTextBufferParserListener(gherkinDialect, textSnapshot, projectScope.Classifications); var scanner = new GherkinScanner(gherkinDialect, textSnapshot.GetText(), 0); scanner.Scan(gherkinListener); var gherkinFileScope = gherkinListener.GetResult(); var result = new GherkinFileScopeChange( gherkinFileScope, true, true, gherkinFileScope.GetAllBlocks(), Enumerable.Empty<IGherkinFileBlock>()); stopwatch.Stop(); TraceFinishParse(stopwatch, "full", result); return result; }
public void ForceParse(ITextSnapshot snapshot) { isParsing.WaitOne(100); nextTextSnapshotToParse.Enqueue(snapshot); DoParse(); NotifyChanges(snapshot, events); }
private void InsertEmbedString(ITextSnapshot snapshot, string dataUri) { using (EditorExtensionsPackage.UndoContext((DisplayText))) { Declaration dec = _url.FindType<Declaration>(); if (dec != null && dec.Parent != null && !(dec.Parent.Parent is FontFaceDirective)) // No declaration in LESS variable definitions { RuleBlock rule = _url.FindType<RuleBlock>(); string text = dec.Text; if (dec != null && rule != null) { Declaration match = rule.Declarations.FirstOrDefault(d => d.PropertyName != null && d.PropertyName.Text == "*" + dec.PropertyName.Text); if (!text.StartsWith("*", StringComparison.Ordinal) && match == null) _span.TextBuffer.Insert(dec.AfterEnd, "*" + text + "/* For IE 6 and 7 */"); } } _span.TextBuffer.Replace(_span.GetSpan(snapshot), dataUri); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); EditorExtensionsPackage.ExecuteCommand("Edit.CollapsetoDefinitions"); } }
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; } }
private bool PossibleTypeArgument(ITextSnapshot snapshot, SyntaxToken token, CancellationToken cancellationToken) { var node = token.Parent as BinaryExpressionSyntax; // type argument can be easily ambiguous with normal < operations if (node == null || node.Kind() != SyntaxKind.LessThanExpression || node.OperatorToken != token) { return false; } // use binding to see whether it is actually generic type or method var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } var model = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); // Analyze node on the left of < operator to verify if it is a generic type or method. var leftNode = node.Left; if (leftNode is ConditionalAccessExpressionSyntax) { // If node on the left is a conditional access expression, get the member binding expression // from the innermost conditional access expression, which is the left of < operator. // e.g: Case a?.b?.c< : we need to get the conditional access expression .b?.c and analyze its // member binding expression (the .c) to see if it is a generic type/method. // Case a?.b?.c.d< : we need to analyze .c.d // Case a?.M(x => x?.P)?.M2< : We need to analyze .M2 leftNode = leftNode.GetInnerMostConditionalAccessExpression().WhenNotNull; } var info = model.GetSymbolInfo(leftNode, cancellationToken); return info.CandidateSymbols.Any(IsGenericTypeOrMethod); }
/// <summary> /// Asynchronously constructs a line map from a <paramref name="snapshot"/> and <paramref name="code"/>. /// </summary> /// <param name="snapshot">The current text snapshot.</param> /// <param name="code">The code to derive a line map from.</param> /// <param name="cancelToken">Cancellation token.</param> /// <returns> /// A <see cref="LineMap"/> if <paramref name="code"/> was parsed correctly, /// <c>null</c> if there was invalid code or it was canceled. /// </returns> internal static Task<LineMap> ConstructAsync(ITextSnapshot snapshot, string code, CancellationToken cancelToken) { if (snapshot == null) throw new ArgumentNullException ("snapshot"); if (code == null) throw new ArgumentNullException ("code"); return Task<LineMap>.Factory.StartNew (() => { try { var tree = SyntaxTree.Parse (code, cancellationToken: cancelToken); if (tree.Errors.Any (p => p.ErrorType == ErrorType.Error)) return null; var identifier = new IdentifyingVisitor(); tree.AcceptVisitor (identifier); var spans = new Dictionary<int, ITrackingSpan> (identifier.LineMap.Count); foreach (var kvp in identifier.LineMap) { ITextSnapshotLine line = snapshot.GetLineFromLineNumber (kvp.Value - 1); ITrackingSpan span = snapshot.CreateTrackingSpan (line.Extent, SpanTrackingMode.EdgeExclusive); spans.Add (kvp.Key, span); } return (cancelToken.IsCancellationRequested) ? null : new LineMap (spans); } catch (OperationCanceledException) { return null; } }, cancelToken); }
public List<MarkerLine> GetMarkerLinesForFile(ITextSnapshot textSnapshot) { var lines = new List<MarkerLine>(); if (_threadFixPlugin == null || _threadFixPlugin.MarkerLookUp == null) { return lines; } var filename = textSnapshot.TextBuffer.GetTextDocument().FilePath.ToLower(); var markers = new List<VulnerabilityMarker>(); if(_threadFixPlugin.MarkerLookUp.TryGetValue(filename, out markers) && !string.IsNullOrEmpty(filename)) { foreach (var marker in markers) { if (marker.LineNumber.HasValue && marker.LineNumber.Value > 0 && marker.LineNumber.Value < textSnapshot.LineCount) { lines.Add(new MarkerLine(textSnapshot.GetLineFromLineNumber(marker.LineNumber.Value - 1), marker.GenericVulnName)); } } } return lines; }
public SnapshotPoint GetCaretPositionInSubjectBuffer(SnapshotPoint viewCaretPosition, ITextSnapshot bufferSnapshot) { var currentModelSpanInView = GetCurrentSpanInView(viewCaretPosition.Snapshot); SnapshotSpan currentModelSpanInSubjectBuffer = GetCurrentSpanInSubjectBuffer(bufferSnapshot); return currentModelSpanInSubjectBuffer.Start + (viewCaretPosition - currentModelSpanInView.Start); }
private void InsertEmbedString(ITextSnapshot snapshot, string dataUri) { using (WebEssentialsPackage.UndoContext((DisplayText))) { _span.TextBuffer.Replace(_span.GetSpan(snapshot), dataUri); } }
private static SnapshotSourceText CreateText(ITextSnapshot editorSnapshot) { var strongBox = s_textBufferLatestSnapshotMap.GetOrCreateValue(editorSnapshot.TextBuffer); var text = strongBox.Value; if (text != null && text._reiteratedVersion == editorSnapshot.Version.ReiteratedVersionNumber) { if (text.Length == editorSnapshot.Length) { return text; } else { // In editors with non-compliant Undo/Redo implementations, you can end up // with two Versions with the same ReiteratedVersionNumber but with very // different text. We've never provably seen this problem occur in Visual // Studio, but we have seen crashes that look like they could have been // caused by incorrect results being returned from this cache. try { throw new InvalidOperationException( $"The matching cached SnapshotSourceText with <Reiterated Version, Length> = <{text._reiteratedVersion}, {text.Length}> " + $"does not match the given editorSnapshot with <{editorSnapshot.Version.ReiteratedVersionNumber}, {editorSnapshot.Length}>"); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } } } text = new SnapshotSourceText(editorSnapshot, editorSnapshot.TextBuffer.GetEncodingOrUTF8()); strongBox.Value = text; return text; }
public FakeTextSnapshotLine(ITextSnapshot snapshot, string text, int position, int lineNumber) { Snapshot = snapshot; this._text = text; LineNumber = lineNumber; Start = new SnapshotPoint(snapshot, position); }
internal void Parse(ITextSnapshot snapshot, out LanguageService.SyntaxTree.ITokenStream TokenStream, string path) { string source = snapshot.GetText(); // Currently we "eat" all Exception that might be raised // by XSharpSyntaxTree.ParseText TokenStream = null; try { LanguageService.CodeAnalysis.SyntaxTree tree = XSharpSyntaxTree.ParseText(source, null, path); var syntaxRoot = tree.GetRoot(); // Get the antlr4 parse tree root var xtree = ((LanguageService.CodeAnalysis.XSharp.Syntax.CompilationUnitSyntax)syntaxRoot).XSource; TokenStream = ((LanguageService.CodeAnalysis.XSharp.Syntax.CompilationUnitSyntax)syntaxRoot).XTokenStream; // var walker = new LanguageService.SyntaxTree.Tree.ParseTreeWalker(); var discover = new XSharpTreeDiscover(); discover.Snapshot = snapshot; discover.xsharpBraceCloseType = xsharpBraceCloseType; discover.xsharpBraceOpenType = xsharpBraceOpenType; discover.xsharpIdentifierType = xsharpIdentifierType; discover.xsharpRegionStartType = xsharpRegionStartType; discover.xsharpRegionStopType = xsharpRegionStopType; // Walk the tree. The TreeDiscover class will collect the tags. walker.Walk(discover, xtree); this.tags = discover.tags; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } }
public SemanticTaggerVisitor(HlslClassificationService classificationService, ITextSnapshot snapshot, List<ITagSpan<IClassificationTag>> results, CancellationToken cancellationToken) { _classificationService = classificationService; _snapshot = snapshot; _results = results; _cancellationToken = cancellationToken; }
public ClassificationParseResult(ITextSnapshot snapshot, Token tokens, Comment[] comments, Directive[] directives) { Snapshot = snapshot; Tokens = tokens; Comments = comments; Directives = directives; }
protected override IEnumerable<DiagnosticBase> GetDiagnostics(ITextSnapshot snapshot, CancellationToken cancellationToken) { SemanticModel semanticModel; if (!snapshot.TryGetSemanticModel(cancellationToken, out semanticModel)) return Enumerable.Empty<DiagnosticBase>(); return semanticModel.GetDiagnostics(); }
public SnapshotPoint? GetPoint(ITextSnapshot targetSnapshot, PositionAffinity affinity) { try { return _trackingPoint.GetPoint(targetSnapshot); } catch (ArgumentException) { return null; } }
public TextChangeArgs(ITextSnapshot oldSnapshot, Span oldSpan, ITextSnapshot newSnapshot, Span newSpan) { OldSnapshot = oldSnapshot; OldSpan = oldSpan; NewSnapshot = newSnapshot; NewSpan = newSpan; }
private ICompletionContext CreateCompletionContext(ISassStylesheet stylesheet, int position, ITextSnapshot snapshot) { ParseItem current = stylesheet as Stylesheet; if (position >= 0) { var previousCharacterIndex = FindPreceedingCharacter(position-1, snapshot); if (previousCharacterIndex != position) current = stylesheet.Children.FindItemContainingPosition(previousCharacterIndex); current = current ?? stylesheet.Children.FindItemContainingPosition(position); if (current is TokenItem) current = current.Parent; if (current != null && !IsUnclosed(current) && previousCharacterIndex != position) { current = stylesheet.Children.FindItemContainingPosition(position); if (current is TokenItem) current = current.Parent; } } current = current ?? stylesheet as Stylesheet; return new CompletionContext { Document = Editor.Document, Current = current, //Predecessor = predecessor, Position = position, Cache = Cache, DocumentTextProvider = new SnapshotTextProvider(snapshot) }; }
public UDNParsingResults(string path, ITextSnapshot snapshot, MarkdownPackage package, Markdown markdown, FolderDetails folderDetails) { var log = new OutputPaneLogger(); ParsedSnapshot = snapshot; // Use the Publish Flag combo box to set the markdown details. markdown.PublishFlags.Clear(); // Always include public markdown.PublishFlags.Add(Settings.Default.PublicAvailabilitiesString); foreach (var flagName in package.PublishFlags) { markdown.PublishFlags.Add(flagName); } Errors = new List<ErrorDetail>(); Images = new List<ImageConversion>(); Attachments = new List<AttachmentConversionDetail>(); Document = markdown.ParseDocument(ParsedSnapshot.GetText(), Errors, Images, Attachments, folderDetails); DoxygenHelper.SetTrackedSymbols(Document.TransformationData.FoundDoxygenSymbols); CommonUnrealFunctions.CopyDocumentsImagesAndAttachments( path, log, folderDetails.AbsoluteHTMLPath, folderDetails.Language, folderDetails.CurrentFolderFromMarkdownAsTopLeaf, Images, Attachments); // Create common directories like css includes top level images etc. // Needs to be created everytime the document is generated to allow // changes to these files to show in the preview window without // restarting VS. CommonUnrealFunctions.CreateCommonDirectories( folderDetails.AbsoluteHTMLPath, folderDetails.AbsoluteMarkdownPath, log); }
public GherkinTextBufferPartialParserListener(GherkinDialect gherkinDialect, ITextSnapshot textSnapshot, GherkinFileEditorClassifications classifications, IGherkinFileScope previousScope, int changeLastLine, int changeLineDelta) : base(gherkinDialect, textSnapshot, classifications) { this.previousScope = previousScope; this.changeLastLine = changeLastLine; this.changeLineDelta = changeLineDelta; }
public IEnumerable<HunkRangeInfo> GetGitDiffFor(ITextDocument textDocument, ITextSnapshot snapshot) { string fileName = textDocument.FilePath; GitFileStatusTracker tracker = new GitFileStatusTracker(Path.GetDirectoryName(fileName)); if (!tracker.IsGit) yield break; GitFileStatus status = tracker.GetFileStatus(fileName); if (status == GitFileStatus.New || status == GitFileStatus.Added) yield break; HistogramDiff diff = new HistogramDiff(); diff.SetFallbackAlgorithm(null); string currentText = snapshot.GetText(); byte[] preamble = textDocument.Encoding.GetPreamble(); byte[] content = textDocument.Encoding.GetBytes(currentText); if (preamble.Length > 0) { byte[] completeContent = new byte[preamble.Length + content.Length]; Buffer.BlockCopy(preamble, 0, completeContent, 0, preamble.Length); Buffer.BlockCopy(content, 0, completeContent, preamble.Length, content.Length); content = completeContent; } byte[] previousContent = null; //GetPreviousRevision(tracker, fileName); RawText b = new RawText(content); RawText a = new RawText(previousContent ?? new byte[0]); EditList edits = diff.Diff(RawTextComparator.DEFAULT, a, b); foreach (Edit edit in edits) yield return new HunkRangeInfo(snapshot, edit, a, b); }
private static SyntaxConcept[] Parse(ITextSnapshot snapshot, out bool success) { var sb = new StringBuilder(); sb.Append("format=json tokens="); var dsl = snapshot.GetText(); sb.Append(Encoding.UTF8.GetByteCount(dsl)); var either = Compiler.CompileDsl(sb, null, dsl, cms => (ParseResult)Serializer.ReadObject(cms)); if (!either.Success) { success = false; Parsed(snapshot, new ParsedArgs(either.Error)); return new SyntaxConcept[0]; } var result = either.Value; if (result.Error != null) { var msg = (result.Error.Line >= 0 ? "Line: " + result.Error.Line + ". " : string.Empty) + result.Error.Error; Parsed(snapshot, new ParsedArgs(msg)); } else Parsed(snapshot, new ParsedArgs()); success = result.Error == null; if (result.Tokens == null) return EmptyResult; return result.Tokens.ToArray(); }
public ParsingResult(Settings settings, ITextSnapshot textSnapshot, IEnumerable<TextSpan> attributeSpans) { TextSnapshot = textSnapshot; AttributeSpans = attributeSpans.ToImmutableArray(); }
private void ProcessJsonObjectPropertyValues(JsonObjectNode rootNode, ITextSnapshot snapshot) { foreach (var jsonPropertyValuePair in rootNode.PropertyValues) { ProcessValue(snapshot, jsonPropertyValuePair.Value); } }
public UpperCaseSuggestedAction(ITrackingSpan span) { _span = span; _snapshot = span.TextBuffer.CurrentSnapshot; _upper = span.GetText(_snapshot).ToUpper(); _display = string.Format("Convert '{0}' to upper case", span.GetText(_snapshot)); }
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 string GetText(ITextSnapshot snapshot) { var span = GetSpan(snapshot.Version); return(snapshot.GetText(span)); }
public static TextEdit CreateEmpty(ITextSnapshot snapshot) { return(new TextEdit(snapshot, 0, 0, String.Empty)); }
public TextEdit(ITextSnapshot snapshot, int position, int length, string text) { this.Span = new SnapshotSpan(snapshot, position, length); this.Text = text; }
public override void Process(string fileName, int offset, string xamlElement, string linePadding, ITextSnapshot snapshot, TagList tags, List <TagSuppression> suppressions = null) { this.ProcessCalled = true; this.ProcessCalledCount += 1; this.Offset = offset; this.AllOffsets.Add(this.ProcessCalledCount, offset); this.XamlElement = xamlElement; this.AllXamlElements.Add(this.ProcessCalledCount, xamlElement); }
public static Result <SnapshotSpan> GetCurrentSpan(this IVsTextLineMarker marker, ITextSnapshot snapshot) { var span = GetCurrentSpan(marker); return(span.IsError ? Result.CreateError(span.HResult) : span.Value.ToSnapshotSpan(snapshot)); }
public override void Process(int offset, string xamlElement, string linePadding, ITextSnapshot snapshot, List <IRapidXamlAdornmentTag> tags) { var(uidExists, uid) = this.GetOrGenerateUid(xamlElement, Attributes.Header); this.CheckForHardCodedAttribute( Elements.DatePicker, Attributes.Header, AttributeType.InlineOrElement, StringRes.Info_XamlAnalysisHardcodedStringDatePickerHeaderMessage, xamlElement, snapshot, offset, uidExists, uid, Guid.Empty, tags); }
public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> quickInfoContent, out ITrackingSpan applicableToSpan) { applicableToSpan = null; if (session.TextView.TextBuffer == this.TextBuffer) { ITextSnapshot currentSnapshot = this.TextBuffer.CurrentSnapshot; SnapshotPoint?triggerPoint = session.GetTriggerPoint(currentSnapshot); if (!triggerPoint.HasValue) { return; } foreach (var span in this.Aggregator.GetTags(new SnapshotSpan(triggerPoint.Value, triggerPoint.Value))) { if (!span.Tag.ClassificationType.IsOfType(AntlrClassificationTypeNames.LexerRule) && !span.Tag.ClassificationType.IsOfType(AntlrClassificationTypeNames.ParserRule)) { continue; } NormalizedSnapshotSpanCollection spans = span.Span.GetSpans(currentSnapshot); if (spans.Count == 1) { SnapshotSpan span2 = spans[0]; SnapshotSpan span3 = span.Span.GetSpans(span.Span.AnchorBuffer)[0]; if (span2.Length == span3.Length) { SnapshotSpan span4 = spans[0]; if (span4.Contains(triggerPoint.Value)) { StringBuilder builder = new StringBuilder(); string ruleName = span2.GetText(); var rules = BackgroundParser.RuleSpans; KeyValuePair <ITrackingSpan, ITrackingPoint> value; if (rules == null || !rules.TryGetValue(ruleName, out value)) { #if DEBUG if (span.Tag.ClassificationType.IsOfType(AntlrClassificationTypeNames.LexerRule)) { builder.Append("Found an unknown lexer rule."); } else { builder.Append("Found an unknown parser rule."); } #else return; #endif } else { SnapshotPoint ruleSeek = value.Value.GetPoint(triggerPoint.Value.Snapshot); if (span2.Contains(ruleSeek)) { return; } builder.Append(value.Key.GetText(span2.Snapshot)); } //builder.AppendLine(span.Tag.Url.OriginalString); //builder.Append(Strings.UrlQuickInfoFollowLink); quickInfoContent.Add(builder.ToString()); applicableToSpan = currentSnapshot.CreateTrackingSpan((Span)spans[0], SpanTrackingMode.EdgeExclusive); } } } } } }
public SnapshotSpan GetSpan(ITextSnapshot snapshot) { return(new SnapshotSpan(snapshot, GetSpan(snapshot.Version))); }
private static ITrackingSpan CreateTrackingSpan(ITextSnapshot snapshot, Span span) { return(snapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive)); }
public SnapshotPoint GetStartPoint(ITextSnapshot snapshot) { var span = GetSpan(snapshot.Version); return(new SnapshotPoint(snapshot, span.Start)); }
internal void Create(params string[] lines) { _buffer = CreateTextBuffer(lines); _snapshot = _buffer.CurrentSnapshot; }
public SnapshotPoint GetEndPoint(ITextSnapshot snapshot) { return(new SnapshotPoint(_snapshot, _start + _length)); }
public void SetSnapshot(ITextSnapshot snapshot) { _visualSpan = _visualSpan.Value.TranslateTo(snapshot, SpanTrackingMode.EdgeInclusive); }
public GherkinTextBufferParserListener(GherkinDialect gherkinDialect, ITextSnapshot textSnapshot, IProjectScope projectScope) : base(gherkinDialect, textSnapshot, projectScope) { }
private void Start(CancellationToken cancellationToken) { // this is where the caret should go after the change SnapshotPoint pos = TextView.Caret.Position.BufferPosition; ITrackingPoint beforeTrackingPoint = pos.Snapshot.CreateTrackingPoint(pos.Position, PointTrackingMode.Negative); ITextSnapshot snapshot = SubjectBuffer.CurrentSnapshot; SnapshotPoint closingSnapshotPoint = ClosingPoint.GetPoint(snapshot); if (closingSnapshotPoint.Position < 1) { Debug.Fail("The closing point was not found at the expected position."); EndSession(); return; } SnapshotPoint openingSnapshotPoint = closingSnapshotPoint.Subtract(1); if (openingSnapshotPoint.GetChar() != OpeningBrace) { // there is a bug in editor brace completion engine on projection buffer that already fixed in vs_pro. until that is FIed to use // I will make this not to assert // Debug.Fail("The opening brace was not found at the expected position."); EndSession(); return; } OpeningPoint = snapshot.CreateTrackingPoint(openingSnapshotPoint, PointTrackingMode.Positive); var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (!_session.CheckOpeningPoint(this, cancellationToken)) { EndSession(); return; } using (ITextUndoTransaction undo = CreateUndoTransaction()) { // insert the closing brace using (ITextEdit edit = SubjectBuffer.CreateEdit()) { edit.Insert(closingSnapshotPoint, ClosingBrace.ToString()); if (edit.HasFailedChanges) { Debug.Fail("Unable to insert closing brace"); // exit without setting the closing point which will take us off the stack edit.Cancel(); undo.Cancel(); return; } else { snapshot = edit.Apply(); } } SnapshotPoint beforePoint = beforeTrackingPoint.GetPoint(TextView.TextSnapshot); // switch from positive to negative tracking so it stays against the closing brace ClosingPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(ClosingPoint.GetPoint(snapshot), PointTrackingMode.Negative); Debug.Assert(ClosingPoint.GetPoint(snapshot).Position > 0 && (new SnapshotSpan(ClosingPoint.GetPoint(snapshot).Subtract(1), 1)) .GetText().Equals(ClosingBrace.ToString()), "The closing point does not match the closing brace character"); // move the caret back between the braces TextView.Caret.MoveTo(beforePoint); _session.AfterStart(this, cancellationToken); undo.Complete(); } }
protected override IOutliningRegionTag CreateTag( IOutliningRegionTag parentTag, ITextSnapshot snapshot, BlockSpan region) { return(new RegionTag(this, snapshot, region)); }
internal static bool EndsWithLineBreak(this ITextSnapshot snapshot) { int length = snapshot.Length; return(length > 0 && (snapshot[length - 1] == '\n' || snapshot[length - 1] == '\r')); }
internal void SetSnapshotAndUpdate(ITextSnapshot snapshot, double deltaX, double deltaY, IList <ITextViewLine> newOrReformattedLines, IList <ITextViewLine> translatedLines) { //Go through all the added visuals and invalidate or transform as appropriate. List <AdornmentAndData> newVisuals = new List <AdornmentAndData>(_elements.Count); for (int i = 0; (i < _elements.Count); ++i) { AdornmentAndData data = _elements[i]; if (!data.VisualSpan.HasValue) { newVisuals.Add(data); if (data.Behavior == AdornmentPositioningBehavior.ViewportRelative) { data.Translate(deltaX, deltaY); } } else { data.SetSnapshot(snapshot); SnapshotSpan span = data.VisualSpan.Value; if ((!_view.TextViewLines.IntersectsBufferSpan(span)) || (GetCrossingLine(newOrReformattedLines, span) != null)) { //Either visual is no longer visible or it crosses a line //that was reformatted. this.RemoveTranslatableVisual(data); } else { newVisuals.Add(data); switch (data.Behavior) { case AdornmentPositioningBehavior.TextRelative: case (AdornmentPositioningBehavior)(AdornmentPositioningBehavior2.TextRelativeVerticalOnly): { ITextViewLine line = GetCrossingLine(translatedLines, span); if (line != null) { data.Translate((data.Behavior == AdornmentPositioningBehavior.TextRelative) ? 0.0 : deltaX, line.DeltaY); } else if (data.Behavior == (AdornmentPositioningBehavior)(AdornmentPositioningBehavior2.TextRelativeVerticalOnly)) { data.Translate(deltaX, 0.0); } break; } case AdornmentPositioningBehavior.ViewportRelative: { data.Translate(deltaX, deltaY); break; } } } } } _elements = newVisuals; }
internal static SnapshotSpan GetExtent(this ITextSnapshot snapshot) { return(new SnapshotSpan(snapshot, 0, snapshot.Length)); }
public void Disable(ITextSnapshot snapshot) { Enabled = false; TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, new Span(0, snapshot.Length)))); }
public static bool IsCaretInLibraryStatement(ITextView textView) { try { SnapshotPoint?bufferPosition = REditorDocument.MapCaretPositionFromView(textView); if (bufferPosition.HasValue) { ITextSnapshot snapshot = bufferPosition.Value.Snapshot; int caretPosition = bufferPosition.Value.Position; ITextSnapshotLine line = snapshot.GetLineFromPosition(caretPosition); if (line.Length < 8 || caretPosition < line.Start + 8 || snapshot[caretPosition - 1] != '(') { return(false); } int start = -1; int end = -1; for (int i = caretPosition - 2; i >= 0; i--) { if (!char.IsWhiteSpace(snapshot[i])) { end = i + 1; break; } } if (end <= 0) { return(false); } for (int i = end - 1; i >= 0; i--) { if (char.IsWhiteSpace(snapshot[i])) { start = i + 1; break; } else if (i == 0) { start = 0; break; } } if (start < 0 || end <= start) { return(false); } start -= line.Start; end -= line.Start; string s = line.GetText().Substring(start, end - start); if (s == "library" || s == "require") { return(true); } } } catch (ArgumentException) { } return(false); }
internal static bool EndsWith(this ITextSnapshot snapshot, char c) { int length = snapshot.Length; return(length > 0 && snapshot[length - 1] == c); }
public static ITagSpan <TTag> GetTagSpan <TTag>(this ITextSnapshot snapshot, Span span, TTag tag) where TTag : ITag { return(new TagSpan <TTag>(new SnapshotSpan(snapshot, span), tag)); }
private bool IsCodeBlock(ITextSnapshot surfaceSnapshot, int position, char ch) { return(CheckCode(surfaceSnapshot, position, ch, CSharpRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor, CSharpRazorBlock)); }
public static SnapshotSpan GetSpanFromBounds(this ITextSnapshot snapshot, int start, int end) { return(new SnapshotSpan(snapshot, Span.FromBounds(start, end))); }
public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, int startLine, int startIndex, int endLine, int endIndex) { return(TryGetSpan(snapshot, startLine, startIndex, endLine, endIndex).Value); }
public static int GetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex) { return(TryGetPosition(snapshot, lineNumber, columnIndex).Value); }
public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, Span span) { return(new SnapshotSpan(snapshot, span)); }
/// <summary> /// Convert a <see cref="LinePositionSpan"/> to <see cref="TextSpan"/>. /// </summary> public static TextSpan GetTextSpan(this ITextSnapshot snapshot, LinePositionSpan span) { return(TextSpan.FromBounds( GetPosition(snapshot, span.Start.Line, span.Start.Character), GetPosition(snapshot, span.End.Line, span.End.Character))); }
public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, int start, int length) { return(new SnapshotSpan(snapshot, new Span(start, length))); }