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


C# Document.GetTextAsync方法代码示例

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


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

示例1: CreateRule

            public IFormattingRule CreateRule(Document document, int position)
            {
                var visualStudioWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
                if (visualStudioWorkspace == null)
                {
                    return _noopRule;
                }

                var containedDocument = visualStudioWorkspace.GetHostDocument(document.Id) as ContainedDocument;
                if (containedDocument == null)
                {
                    return _noopRule;
                }

                var textContainer = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None).Container;
                var buffer = textContainer.TryGetTextBuffer() as IProjectionBuffer;
                if (buffer == null)
                {
                    return _noopRule;
                }

                using (var pooledObject = SharedPools.Default<List<TextSpan>>().GetPooledObject())
                {
                    var spans = pooledObject.Object;

                    var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
                    var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);

                    spans.AddRange(containedDocument.GetEditorVisibleSpans());

                    for (var i = 0; i < spans.Count; i++)
                    {
                        var visibleSpan = spans[i];
                        if (visibleSpan.IntersectsWith(position) || visibleSpan.End == position)
                        {
                            return containedDocument.GetBaseIndentationRule(root, text, spans, i);
                        }
                    }

                    // in razor (especially in @helper tag), it is possible for us to be asked for next line of visible span
                    var line = text.Lines.GetLineFromPosition(position);
                    if (line.LineNumber > 0)
                    {
                        line = text.Lines[line.LineNumber - 1];

                        // find one that intersects with previous line
                        for (var i = 0; i < spans.Count; i++)
                        {
                            var visibleSpan = spans[i];
                            if (visibleSpan.IntersectsWith(line.Span))
                            {
                                return containedDocument.GetBaseIndentationRule(root, text, spans, i);
                            }
                        }
                    }

                    throw new InvalidOperationException();
                }
            }
开发者ID:GloryChou,项目名称:roslyn,代码行数:59,代码来源:VisualStudioFormattingRuleFactoryServiceFactory.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: GetInfoAsync

        internal static async Task<DebugLocationInfo> GetInfoAsync(Document document, int position, CancellationToken cancellationToken)
        {
            string name = null;
            int lineOffset = 0;

            // Note that we get the current partial solution here.  Technically, this means that we may
            // not fully understand the signature of the member.  But that's ok.  We just need this
            // symbol so we can create a display string to put into the debugger.  If we try to
            // find the document in the "CurrentSolution" then when we try to get the semantic 
            // model below then it might take a *long* time as all dependent compilations are built.
            var tree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
            var token = root.FindToken(position);
            SyntaxNode memberDecl = token.GetAncestor<MemberDeclarationSyntax>();

            // field or event field declarations may contain multiple variable declarators. Try finding the correct one.
            // If the position does not point to one, try using the first one.
            if (memberDecl != null &&
                (memberDecl.Kind() == SyntaxKind.FieldDeclaration || memberDecl.Kind() == SyntaxKind.EventFieldDeclaration))
            {
                SeparatedSyntaxList<VariableDeclaratorSyntax> variableDeclarators = ((BaseFieldDeclarationSyntax)memberDecl).Declaration.Variables;

                foreach (var declarator in variableDeclarators)
                {
                    if (declarator.FullSpan.Contains(token.FullSpan))
                    {
                        memberDecl = declarator;
                        break;
                    }
                }

                if (memberDecl == null)
                {
                    memberDecl = variableDeclarators.Count > 0 ? variableDeclarators[0] : null;
                }
            }

            if (memberDecl != null)
            {
                var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                var memberSymbol = semanticModel.GetDeclaredSymbol(memberDecl, cancellationToken);

                if (memberSymbol != null)
                {
                    var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
                    var lineNumber = text.Lines.GetLineFromPosition(position).LineNumber;

                    var accessor = token.GetAncestor<AccessorDeclarationSyntax>();
                    var memberLine = accessor == null
                        ? text.Lines.GetLineFromPosition(memberDecl.SpanStart).LineNumber
                        : text.Lines.GetLineFromPosition(accessor.SpanStart).LineNumber;

                    name = memberSymbol.ToDisplayString(s_nameFormat);
                    lineOffset = lineNumber - memberLine;
                    return new DebugLocationInfo(name, lineOffset);
                }
            }

            return default(DebugLocationInfo);
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:60,代码来源:LocationInfoGetter.cs

示例5: AbstractSourceTreeItem

        public AbstractSourceTreeItem(Document document, TextSpan sourceSpan, ushort glyphIndex, int commonPathElements = 0)
            : base(glyphIndex)
        {
            // We store the document ID, line and offset for navigation so that we
            // still provide reasonable navigation if the user makes changes elsewhere
            // in the document other than inserting or removing lines.

            _workspace = document.Project.Solution.Workspace;
            _documentId = document.Id;
            _projectName = document.Project.Name;
            _filePath = GetFilePath(document, commonPathElements);
            _sourceSpan = sourceSpan;

            var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
            var textLine = text.Lines.GetLineFromPosition(_sourceSpan.Start);
            _textLineString = textLine.ToString();

            _lineNumber = textLine.LineNumber;
            _offset = sourceSpan.Start - textLine.Start;

            var spanInSecondaryBuffer = text.GetVsTextSpanForLineOffset(_lineNumber, _offset);

            VsTextSpan spanInPrimaryBuffer;
            var succeeded = spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(_workspace, _documentId, out spanInPrimaryBuffer);

            _mappedLineNumber = succeeded ? spanInPrimaryBuffer.iStartLine : _lineNumber;
            _mappedOffset = succeeded ? spanInPrimaryBuffer.iStartIndex : _offset;
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:28,代码来源:AbstractSourceTreeItem.cs

示例6: GetFormattingChangesAfterKeystroke

        public static async Task<IEnumerable<LinePositionSpanTextChange>> GetFormattingChangesAfterKeystroke(Workspace workspace, OptionSet options, Document document, int position, char character)
        {
            var tree = await document.GetSyntaxTreeAsync();

            if (character == '\n')
            {
                // format previous line on new line
                var lines = (await document.GetTextAsync()).Lines;
                var targetLine = lines[lines.GetLineFromPosition(position).LineNumber - 1];
                if (!string.IsNullOrWhiteSpace(targetLine.Text.ToString(targetLine.Span)))
                {
                    return await GetFormattingChangesForRange(workspace, options, document, targetLine.Start, targetLine.End);
                }
            }
            else if (character == '}' || character == ';')
            {
                // format after ; and }
                var node = FindFormatTarget(tree, position);
                if (node != null)
                {
                    return await GetFormattingChangesForRange(workspace, options, document, node.FullSpan.Start, node.FullSpan.End);
                }
            }

            return Enumerable.Empty<LinePositionSpanTextChange>();
        }
开发者ID:robbert229,项目名称:omnisharp-roslyn,代码行数:26,代码来源:Formatting.cs

示例7: UpdateBuffer

        private void UpdateBuffer(Document document, SpanChange spanSource, out SourceTextContainer container, out Document documentBackedByTextBuffer)
        {
            if (_previewWorkspace != null)
            {
                _previewWorkspace.CloseDocument(_currentDocument, _previewWorkspace.CurrentSolution.GetDocument(_currentDocument).GetTextAsync().Result);

                // Put the new document into the current preview solution
                var updatedSolution = _previewWorkspace.CurrentSolution.WithDocumentText(document.Id, document.GetTextAsync().Result);
                var updatedDocument = updatedSolution.GetDocument(document.Id);

                ApplyDocumentToBuffer(updatedDocument, spanSource, out container, out documentBackedByTextBuffer);

                _previewWorkspace.TryApplyChanges(documentBackedByTextBuffer.Project.Solution);
                _previewWorkspace.OpenDocument(document.Id);
                _currentDocument = document.Id;
            }
            else
            {
                _currentDocument = document.Id;

                ApplyDocumentToBuffer(document, spanSource, out container, out documentBackedByTextBuffer);

                _previewWorkspace = new PreviewDialogWorkspace(documentBackedByTextBuffer.Project.Solution);
                _previewWorkspace.OpenDocument(document.Id);
            }
        }
开发者ID:JinGuoGe,项目名称:roslyn,代码行数:26,代码来源:PreviewUpdater.cs

示例8: IsTriggerCharacter

 public static async Task<bool> IsTriggerCharacter([NotNull] this ISignatureHelpProvider provider, Document document, int position)
 {
     if (provider == null) throw new ArgumentNullException(nameof(provider));
     var text = await document.GetTextAsync().ConfigureAwait(false);
     var character = text.GetSubText(new TextSpan(position, 1))[0];
     return provider.IsTriggerCharacter(character);
 }
开发者ID:mjheitland,项目名称:TableTweaker,代码行数:7,代码来源:SignatureHelpProviderExtensions.cs

示例9: CreateAsync

		public static new async Task<SemanticDocument> CreateAsync(Document document, CancellationToken cancellationToken)
		{
			var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
			var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
			var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
			return new SemanticDocument(document, text, root.SyntaxTree, root, model);
		}
开发者ID:pabloescribanoloza,项目名称:monodevelop,代码行数:7,代码来源:SemanticDocument.cs

示例10: 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

示例11: SourceListItem

        public SourceListItem(Document document, TextSpan sourceSpan, ushort glyphIndex)
            : base(glyphIndex)
        {
            _workspace = document.Project.Solution.Workspace;

            // We store the document ID, line and offset for navigation so that we
            // still provide reasonable navigation if the user makes changes elsewhere
            // in the document other than inserting or removing lines.
            _documentId = document.Id;

            var filePath = document.FilePath;

            var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
            var textLine = text.Lines.GetLineFromPosition(sourceSpan.Start);

            _lineNumber = textLine.LineNumber;
            _offset = sourceSpan.Start - textLine.Start;

            var spanInSecondaryBuffer = text.GetVsTextSpanForLineOffset(_lineNumber, _offset);

            VsTextSpan spanInPrimaryBuffer;
            var succeeded = spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(_workspace, document.Id, out spanInPrimaryBuffer);

            var mappedLineNumber = succeeded ? spanInPrimaryBuffer.iStartLine : _lineNumber;
            var mappedOffset = succeeded ? spanInPrimaryBuffer.iStartIndex : _offset;

            SetDisplayProperties(filePath, mappedLineNumber, mappedOffset, _lineNumber, _offset, textLine.ToString(), sourceSpan.Length);
        }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:28,代码来源:SourceListItem.cs

示例12: 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

示例13: 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

示例14: 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

示例15: DoAsync

        public async Task<IList<string>> DoAsync(
            Document document,
            int position,
            string locationName,
            CancellationToken cancellationToken)
        {
            var result = SpecializedCollections.EmptyList<string>();

            var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
            var snapshot = text.FindCorrespondingEditorTextSnapshot();
            locationName = locationName ?? string.Empty;

            // Get the prior values we've computed.
            var locationToExpressionsMap = snapshot != null
                                         ? _snapshotToExpressions.GetValue(snapshot, _ => new Dictionary<string, LinkedList<IList<string>>>())
                                         : new Dictionary<string, LinkedList<IList<string>>>();

            var cachedExpressionLists = locationToExpressionsMap.GetOrAdd(locationName,
                _ => new LinkedList<IList<string>>());

            // Determine the right expressions for this position.
            var expressions = await _proximityExpressionsGetter.GetProximityExpressionsAsync(document, position, cancellationToken).ConfigureAwait(false);

            // If we get a new set of expressions, then add it to the list and evict any values we
            // no longer need.
            if (expressions != null)
            {
                if (cachedExpressionLists.Count == 0 ||
                    !cachedExpressionLists.First.Value.SetEquals(expressions))
                {
                    cachedExpressionLists.AddFirst(expressions);
                    while (cachedExpressionLists.Count > MaxCacheLength)
                    {
                        cachedExpressionLists.RemoveLast();
                    }
                }
            }

            // Return all the unique values from the previous and current invocation.  However, if
            // these are not the current values, then pull out any expressions that are not valid in
            // our current context.
            if (cachedExpressionLists.Any())
            {
                var list = new List<string>();
                foreach (var expr in cachedExpressionLists.Flatten())
                {
                    if (await _proximityExpressionsGetter.IsValidAsync(document, position, expr, cancellationToken).ConfigureAwait(false))
                    {
                        list.Add(expr);
                    }
                }

                result = list.Distinct().ToList();
            }

            return result;
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:57,代码来源:CachedProximityExpressionsGetter.cs


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