当前位置: 首页>>代码示例>>C#>>正文


C# Document.WithText方法代码示例

本文整理汇总了C#中Microsoft.CodeAnalysis.Document.WithText方法的典型用法代码示例。如果您正苦于以下问题:C# Document.WithText方法的具体用法?C# Document.WithText怎么用?C# Document.WithText使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.CodeAnalysis.Document的用法示例。


在下文中一共展示了Document.WithText方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken token)
        {
            var sourceText = await document.GetTextAsync(token).ConfigureAwait(false);

            var startIndex = sourceText.Lines.IndexOf(diagnostic.Location.SourceSpan.Start);
            int endIndex = startIndex;

            for (var i = startIndex + 1; i < sourceText.Lines.Count; i++)
            {
                if (!string.IsNullOrWhiteSpace(sourceText.Lines[i].ToString()))
                {
                    endIndex = i - 1;
                    break;
                }
            }

            if (endIndex >= (startIndex + 1))
            {
                var replaceSpan = TextSpan.FromBounds(sourceText.Lines[startIndex + 1].SpanIncludingLineBreak.Start, sourceText.Lines[endIndex].SpanIncludingLineBreak.End);
                var newSourceText = sourceText.Replace(replaceSpan, string.Empty);
                return document.WithText(newSourceText);
            }

            return document;
        }
开发者ID:nvincent,项目名称:StyleCopAnalyzers,代码行数:25,代码来源:SA1507CodeFixProvider.cs

示例2: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Location location, CancellationToken cancellationToken)
        {
            var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
            var sourceSpan = location.SourceSpan;

            return document.WithText(text.WithChanges(GetTextChange(text, sourceSpan)));
        }
开发者ID:Romanx,项目名称:StyleCopAnalyzers,代码行数:7,代码来源:SA1005CodeFixProvider.cs

示例3: TryGetDocumentWithFullyQualifiedTypeName

        private bool TryGetDocumentWithFullyQualifiedTypeName(Document document, out TextSpan updatedTextSpan, out Document documentWithFullyQualifiedTypeName)
        {
            documentWithFullyQualifiedTypeName = null;
            updatedTextSpan = default(TextSpan);

            var surfaceBufferFieldSpan = new VsTextSpan[1];
            if (snippetExpansionClient.ExpansionSession.GetFieldSpan(_fieldName, surfaceBufferFieldSpan) != VSConstants.S_OK)
            {
                return false;
            }

            SnapshotSpan subjectBufferFieldSpan;
            if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out subjectBufferFieldSpan))
            {
                return false;
            }

            var originalTextSpan = new TextSpan(subjectBufferFieldSpan.Start, subjectBufferFieldSpan.Length);
            updatedTextSpan = new TextSpan(subjectBufferFieldSpan.Start, _fullyQualifiedName.Length);

            var textChange = new TextChange(originalTextSpan, _fullyQualifiedName);
            var newText = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None).WithChanges(textChange);

            documentWithFullyQualifiedTypeName = document.WithText(newText);
            return true;
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:26,代码来源:AbstractSnippetFunctionSimpleTypeName.cs

示例4: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

            TextChange textChange = new TextChange(new TextSpan(diagnostic.Location.SourceSpan.Start, 1), string.Empty);
            return document.WithText(text.WithChanges(textChange));
        }
开发者ID:Romanx,项目名称:StyleCopAnalyzers,代码行数:8,代码来源:SA1626CodeFixProvider.cs

示例5: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken token)
        {
            var newLine = document.Project.Solution.Workspace.Options.GetOption(FormattingOptions.NewLine, LanguageNames.CSharp);

            var sourceText = await document.GetTextAsync(token).ConfigureAwait(false);
            var textChange = new TextChange(diagnostic.Location.SourceSpan, newLine);

            return document.WithText(sourceText.WithChanges(textChange));
        }
开发者ID:endjin,项目名称:StyleCopAnalyzers,代码行数:9,代码来源:SA1507CodeFixProvider.cs

示例6: ReplaceWithUtcNowAsync

 private async Task<Document> ReplaceWithUtcNowAsync(Document document, TextSpan span, CancellationToken cancellationToken)
 {
     var text = await document.GetTextAsync();
     var repl = "DateTime.UtcNow";
     if (Regex.Replace(text.GetSubText(span).ToString(),@"\s+",string.Empty) == "System.DateTime.Now")
         repl = "System.DateTime.UtcNow";
     var newtext = text.Replace(span, repl);
     return document.WithText(newtext);
 }
开发者ID:LiamMorrow,项目名称:DateTimeNowBanisher,代码行数:9,代码来源:CodeFixProvider.cs

示例7: GetTransformedDocumentAsync

 private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var indentationOptions = IndentationOptions.FromDocument(document);
     SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
     return document.WithText(sourceText.WithChanges(FixDiagnostic(indentationOptions, sourceText, diagnostic)));
 }
开发者ID:neugenes,项目名称:StyleCopAnalyzers,代码行数:6,代码来源:SA1027CodeFixProvider.cs

示例8: FixEndOfFileAsync

 /// <summary>
 /// Fixes the whitespace at the end of a document.
 /// </summary>
 /// <param name="document">The document to be changed.</param>
 /// <param name="diagnostic">The diagnostic to fix.</param>
 /// <param name="newlineAtEndOfFile">A <see cref="EndOfFileHandling"/> value indicating the desired behavior.</param>
 /// <param name="cancellationToken">The cancellation token associated with the fix action.</param>
 /// <returns>The transformed document.</returns>
 private static async Task<Document> FixEndOfFileAsync(Document document, Diagnostic diagnostic, EndOfFileHandling newlineAtEndOfFile, CancellationToken cancellationToken)
 {
     var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
     string replacement = newlineAtEndOfFile == EndOfFileHandling.Omit ? string.Empty : "\r\n";
     return document.WithText(text.WithChanges(new TextChange(diagnostic.Location.SourceSpan, replacement)));
 }
开发者ID:jmecosta,项目名称:StyleCopAnalyzers,代码行数:14,代码来源:SA1518CodeFixProvider.cs

示例9: GetSingleAnalyzerDocumentAsync

        private static async Task<Document> GetSingleAnalyzerDocumentAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, CodeFixProvider codeFixProvider, int? codeFixIndex, Document document, int maxNumberOfIterations, CancellationToken cancellationToken)
        {
            var previousDiagnostics = ImmutableArray.Create<Diagnostic>();

            bool done;
            do
            {
                var analyzerDiagnostics = await GetSortedDiagnosticsFromDocumentsAsync(analyzers, new[] { document }, cancellationToken).ConfigureAwait(false);
                if (analyzerDiagnostics.Length == 0)
                {
                    break;
                }

                if (!AreDiagnosticsDifferent(analyzerDiagnostics, previousDiagnostics))
                {
                    break;
                }

                if (--maxNumberOfIterations < 0)
                {
                    Assert.True(false, "The upper limit for the number of code fix iterations was exceeded");
                }

                previousDiagnostics = analyzerDiagnostics;

                done = true;
                for (var i = 0; i < analyzerDiagnostics.Length; i++)
                {
                    var actions = new List<CodeAction>();
                    var context = new CodeFixContext(document, analyzerDiagnostics[i], (a, d) => actions.Add(a), cancellationToken);
                    await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(false);

                    if (actions.Count > 0)
                    {
                        var fixedDocument = await ApplyFixAsync(document, actions.ElementAt(codeFixIndex.GetValueOrDefault(0)), cancellationToken).ConfigureAwait(false);
                        if (fixedDocument != document)
                        {
                            done = false;
                            var newText = await fixedDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);

                            // workaround for issue #936 - force re-parsing to get the same sort of syntax tree as the original document.
                            document = document.WithText(newText);
                            break;
                        }
                    }
                }
            }
            while (!done);

            return document;
        }
开发者ID:journeyman,项目名称:StyleCopAnalyzers,代码行数:51,代码来源:CodeFixVerifier.cs

示例10: DeleteMember

        private Document DeleteMember(Document document, SyntaxNode node)
        {
            var text = document.GetTextAsync(CancellationToken.None)
                               .WaitAndGetResult_CodeModel(CancellationToken.None);

            // We want to delete all the leading trivia from the node back to,
            // but not including:
            //  * the first preprocessor directive
            //  - or -
            //  * the first comment after a white-space only line
            // We also want to delete all the trailing trivia

            var deletionEnd = node.FullSpan.End;

            var deletionStart = node.SpanStart;

            int contiguousEndOfLines = 0;
            foreach (var trivia in node.GetLeadingTrivia().Reverse())
            {
                if (trivia.IsDirective)
                {
                    break;
                }

                if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
                {
                    if (contiguousEndOfLines > 0)
                    {
                        break;
                    }
                    else
                    {
                        contiguousEndOfLines++;
                    }
                }
                else if (trivia.Kind() != SyntaxKind.WhitespaceTrivia)
                {
                    contiguousEndOfLines = 0;
                }

                deletionStart = trivia.FullSpan.Start;
            }

            text = text.Replace(TextSpan.FromBounds(deletionStart, deletionEnd), string.Empty);

            return document.WithText(text);
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:47,代码来源:CSharpCodeModelService.cs

示例11: ForkNewDocument

        private static Document ForkNewDocument(CopyData copyData, Document document, TextSpan span)
        {
            // here we assume paste data is what is copied before.
            // we will check this assumption when things are actually pasted.
            var newText = document.GetTextAsync().Result.ToString().Remove(span.Start, span.Length).Insert(span.Start, copyData.Text);

            // fork solution
            return document.WithText(SourceText.From(newText));
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:9,代码来源:PasteHandler.cs

示例12: GetTransformedDocumentAsync

 private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var settings = SettingsHelper.GetStyleCopSettings(document.Project.AnalyzerOptions, cancellationToken);
     SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
     return document.WithText(sourceText.WithChanges(FixDiagnostic(settings.Indentation, sourceText, diagnostic)));
 }
开发者ID:Romanx,项目名称:StyleCopAnalyzers,代码行数:6,代码来源:SA1027CodeFixProvider.cs

示例13: ApplyDocumentToBuffer

        private void ApplyDocumentToBuffer(Document document, SpanChange spanSource, out SourceTextContainer container, out Document documentBackedByTextBuffer)
        {
            var contentTypeService = document.Project.LanguageServices.GetService<IContentTypeLanguageService>();
            var contentType = contentTypeService.GetDefaultContentType();

            TextView.TextBuffer.ChangeContentType(contentType, null);

            var documentText = document.GetTextAsync().Result.ToString();
            SpanToShow = spanSource.GetSpan();

            using (var edit = TextView.TextBuffer.CreateEdit())
            {
                edit.Replace(new Span(0, TextView.TextBuffer.CurrentSnapshot.Length), documentText);
                edit.Apply();
            }

            container = TextView.TextBuffer.AsTextContainer();
            documentBackedByTextBuffer = document.WithText(container.CurrentText);
        }
开发者ID:JinGuoGe,项目名称:roslyn,代码行数:19,代码来源:PreviewUpdater.cs

示例14: TryGetSimplifiedTypeNameInCaseContext

        protected override bool TryGetSimplifiedTypeNameInCaseContext(Document document, string fullyQualifiedTypeName, string firstEnumMemberName, int startPosition, int endPosition, CancellationToken cancellationToken, out string simplifiedTypeName)
        {
            simplifiedTypeName = string.Empty;
            var typeAnnotation = new SyntaxAnnotation();

            var str = "case " + fullyQualifiedTypeName + "." + firstEnumMemberName + ":" + Environment.NewLine + " break;";
            var textChange = new TextChange(new TextSpan(startPosition, endPosition - startPosition), str);
            var typeSpanToAnnotate = new TextSpan(startPosition + "case ".Length, fullyQualifiedTypeName.Length);

            var textWithCaseAdded = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).WithChanges(textChange);
            var documentWithCaseAdded = document.WithText(textWithCaseAdded);

            var syntaxRoot = documentWithCaseAdded.GetSyntaxRootSynchronously(cancellationToken);
            var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == typeSpanToAnnotate);

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

            var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation));
            var documentWithAnnotations = documentWithCaseAdded.WithSyntaxRoot(updatedRoot);

            var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).Result;
            simplifiedTypeName = simplifiedDocument.GetSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString();
            return true;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:27,代码来源:SnippetFunctionGenerateSwitchCases.cs

示例15: RemoveSemicolonTextAsync

 private static async Task<Document> RemoveSemicolonTextAsync(Document document, SyntaxToken token, CancellationToken cancellationToken)
 {
     SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
     TextLine line = sourceText.Lines.GetLineFromPosition(token.SpanStart);
     if (sourceText.ToString(line.Span).Trim() == token.Text)
     {
         // remove the line containing the semicolon token
         TextChange textChange = new TextChange(line.SpanIncludingLineBreak, string.Empty);
         return document.WithText(sourceText.WithChanges(textChange));
     }
     else
     {
         // remove just the semicolon
         TextChange textChange = new TextChange(token.Span, string.Empty);
         return document.WithText(sourceText.WithChanges(textChange));
     }
 }
开发者ID:endjin,项目名称:StyleCopAnalyzers,代码行数:17,代码来源:SA1106CodeFixProvider.cs


注:本文中的Microsoft.CodeAnalysis.Document.WithText方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。