本文整理汇总了C#中Document.GetOptionsAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Document.GetOptionsAsync方法的具体用法?C# Document.GetOptionsAsync怎么用?C# Document.GetOptionsAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Document
的用法示例。
在下文中一共展示了Document.GetOptionsAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetCodeActionAsync
private async Task<Tuple<CodeAction, string>> GetCodeActionAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
var result = await ExtractMethodService.ExtractMethodAsync(
document,
textSpan,
cancellationToken: cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(result);
if (result.Succeeded || result.SucceededWithSuggestion)
{
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var description = documentOptions.GetOption(ExtractMethodOptions.AllowMovingDeclaration) ?
FeaturesResources.Extract_Method_plus_Local : FeaturesResources.Extract_Method;
var codeAction = new MyCodeAction(description, (c) => AddRenameAnnotationAsync(result.Document, result.InvocationNameToken, c));
var methodBlock = result.MethodDeclarationNode;
return Tuple.Create<CodeAction, string>(codeAction, methodBlock.ToString());
}
return null;
}
示例2: GetDesiredIndentation
public IndentationResult? GetDesiredIndentation(
Document document, int lineNumber, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var sourceText = root.SyntaxTree.GetText(cancellationToken);
var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var lineToBeIndented = sourceText.Lines[lineNumber];
var formattingRules = GetFormattingRules(document, lineToBeIndented.Start);
// There are two important cases for indentation. The first is when we're simply
// trying to figure out the appropriate indentation on a blank line (i.e. after
// hitting enter at the end of a line, or after moving to a blank line). The
// second is when we're trying to figure out indentation for a non-blank line
// (i.e. after hitting enter in the middle of a line, causing tokens to move to
// the next line). If we're in the latter case, we defer to the Formatting engine
// as we need it to use all its rules to determine where the appropriate location is
// for the following tokens to go.
if (ShouldUseSmartTokenFormatterInsteadOfIndenter(formattingRules, root, lineToBeIndented, documentOptions, cancellationToken))
{
return null;
}
var indenter = GetIndenter(
document.GetLanguageService<ISyntaxFactsService>(),
root.SyntaxTree, lineToBeIndented, formattingRules,
documentOptions, cancellationToken);
return indenter.GetDesiredIndentation(document);
}
示例3: AddSimplifierAnnotationsAsync
private async Task<Document> AddSimplifierAnnotationsAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
FixAllState fixAllState, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
// Find all nodes to simplify corresponding to diagnostic spans.
var nodesToSimplify = new List<SyntaxNode>();
foreach (var diagnostic in diagnostics)
{
string codeActionEquivalenceKey;
var node = GetNodeToSimplify(root, model, diagnostic, options, out codeActionEquivalenceKey, cancellationToken);
if (node != null && fixAllState.CodeActionEquivalenceKey == codeActionEquivalenceKey)
{
nodesToSimplify.Add(node);
}
}
// Add simplifier and formatter annotations to all nodes to simplify.
// If the fix all provider needs to fixup any of the parent nodes, then we iterate through each of the nodesToSimplify
// and fixup any parenting node, computing a new document with required simplifier annotations in each iteration.
// Otherwise, if the fix all provider doesn't need parent fixup, we just add simplifier annotation to all nodesToSimplify.
if (!NeedsParentFixup)
{
root = root.ReplaceNodes(nodesToSimplify, (o, n) =>
n.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation));
}
else
{
// Add a custom annotation to nodesToSimplify so we can get back to them later.
var annotation = new SyntaxAnnotation();
root = root.ReplaceNodes(nodesToSimplify, (o, n) =>
o.WithAdditionalAnnotations(annotation));
document = document.WithSyntaxRoot(root);
while (true)
{
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var annotatedNodes = root.GetAnnotatedNodes(annotation);
// Get the next un-processed node to simplify, processed nodes should have simplifier annotation.
var annotatedNode = annotatedNodes.FirstOrDefault(n => !n.HasAnnotation(Simplifier.Annotation));
if (annotatedNode == null)
{
// All nodesToSimplify have been processed.
// Remove all the custom annotations added for tracking nodesToSimplify.
root = root.ReplaceNodes(annotatedNodes, (o, n) => o.WithoutAnnotations(annotation));
break;
}
document = await AddSimplifyAnnotationsAsync(document, annotatedNode, cancellationToken).ConfigureAwait(false);
}
}
return document.WithSyntaxRoot(root);
}
示例4: GetFormattingChangesAsync
public async Task<IList<TextChange>> GetFormattingChangesAsync(Document document, TextSpan? textSpan, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var span = textSpan.HasValue ? textSpan.Value : new TextSpan(0, root.FullSpan.Length);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, span);
return Formatter.GetFormattedTextChanges(root, new TextSpan[] { formattingSpan }, document.Project.Solution.Workspace, options, cancellationToken);
}
示例5: AnalyzeSyntaxAsync
public async Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken)
{
// it has an assumption that this will not be called concurrently for same document.
// in fact, in current design, it won't be even called concurrently for different documents.
// but, can be called concurrently for different documents in future if we choose to.
Contract.ThrowIfFalse(document.IsFromPrimaryBranch());
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
if (!documentOptions.GetOption(InternalFeatureOnOffOptions.TodoComments))
{
return;
}
// use tree version so that things like compiler option changes are considered
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
var existingData = await _state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData != null)
{
// check whether we can use the data as it is (can happen when re-using persisted data from previous VS session)
if (CheckVersions(document, textVersion, syntaxVersion, existingData))
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Project.Solution, document.Id, existingData.Items);
return;
}
}
var service = document.GetLanguageService<ITodoCommentService>();
if (service == null)
{
return;
}
var tokens = await _todoCommentTokens.GetTokensAsync(document, cancellationToken).ConfigureAwait(false);
var comments = await service.GetTodoCommentsAsync(document, tokens, cancellationToken).ConfigureAwait(false);
var items = await CreateItemsAsync(document, comments, cancellationToken).ConfigureAwait(false);
var data = new Data(textVersion, syntaxVersion, items);
await _state.PersistAsync(document, data, cancellationToken).ConfigureAwait(false);
// * NOTE * cancellation can't throw after this point.
if (existingData == null || existingData.Items.Length > 0 || data.Items.Length > 0)
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Project.Solution, document.Id, data.Items);
}
}
示例6: GetTokensAsync
public async Task<ImmutableArray<TodoCommentDescriptor>> GetTokensAsync(Document document, CancellationToken cancellationToken)
{
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var optionText = documentOptions.GetOption(TodoCommentOptions.TokenList);
var lastInfo = _lastTokenInfo;
if (lastInfo != null && lastInfo.OptionText == optionText)
{
return lastInfo.Tokens;
}
var tokens = Parse(optionText);
System.Threading.Interlocked.CompareExchange(ref _lastTokenInfo, new TokenInfo(optionText, tokens), lastInfo);
return tokens;
}
示例7: SupportsFormattingOnTypedCharacter
public bool SupportsFormattingOnTypedCharacter(Document document, char ch)
{
var options = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent) == FormattingOptions.IndentStyle.Smart;
// We consider the proper placement of a close curly when it is typed at the start of the
// line to be a smart-indentation operation. As such, even if "format on typing" is off,
// if "smart indent" is on, we'll still format this. (However, we won't touch anything
// else in teh block this close curly belongs to.).
//
// TODO(cyrusn): Should we expose an option for this? Personally, i don't think so.
// If a user doesn't want this behavior, they can turn off 'smart indent' and control
// everything themselves.
if (ch == '}' && smartIndentOn)
{
return true;
}
// If format-on-typing is not on, then we don't support formatting on any other characters.
var autoFormattingOnTyping = options.GetOption(FeatureOnOffOptions.AutoFormattingOnTyping);
if (!autoFormattingOnTyping)
{
return false;
}
if (ch == '}' && !options.GetOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace))
{
return false;
}
if (ch == ';' && !options.GetOption(FeatureOnOffOptions.AutoFormattingOnSemicolon))
{
return false;
}
// don't auto format after these keys if smart indenting is not on.
if ((ch == '#' || ch == 'n') && !smartIndentOn)
{
return false;
}
return _supportedChars.Contains(ch);
}
示例8: SupportsFormattingOnTypedCharacter
public bool SupportsFormattingOnTypedCharacter(Document document, char ch)
{
var options = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent) == FormattingOptions.IndentStyle.Smart;
if ((ch == '}' && !options.GetOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace) && !smartIndentOn) ||
(ch == ';' && !options.GetOption(FeatureOnOffOptions.AutoFormattingOnSemicolon)))
{
return false;
}
// don't auto format after these keys if smart indenting is not on.
if ((ch == '#' || ch == 'n') && !smartIndentOn)
{
return false;
}
return _supportedChars.Contains(ch);
}
示例9: GetDesiredIndentation
public IndentationResult? GetDesiredIndentation(Document document, int lineNumber, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var sourceText = root.SyntaxTree.GetText(cancellationToken);
var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var lineToBeIndented = sourceText.Lines[lineNumber];
var formattingRules = GetFormattingRules(document, lineToBeIndented.Start);
// enter on a token case.
if (ShouldUseSmartTokenFormatterInsteadOfIndenter(formattingRules, root, lineToBeIndented, documentOptions, cancellationToken))
{
return null;
}
var indenter = GetIndenter(
document.GetLanguageService<ISyntaxFactsService>(),
root.SyntaxTree, lineToBeIndented, formattingRules,
documentOptions, cancellationToken);
return indenter.GetDesiredIndentation();
}
示例10: AddImportsAsync
public async Task<Document> AddImportsAsync(
Document document, IEnumerable<TextSpan> spans,
OptionSet options, CancellationToken cancellationToken)
{
options = options ?? await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
// Create a simple interval tree for simplification spans.
var spansTree = new SimpleIntervalTree<TextSpan>(TextSpanIntervalIntrospector.Instance, spans);
Func<SyntaxNodeOrToken, bool> isInSpan = nodeOrToken =>
spansTree.GetOverlappingIntervals(nodeOrToken.FullSpan.Start, nodeOrToken.FullSpan.Length).Any();
var nodesWithExplicitNamespaces = root.DescendantNodesAndSelf().Where(n => isInSpan(n) && GetExplicitNamespaceSymbol(n, model) != null).ToList();
var namespacesToAdd = new HashSet<INamespaceSymbol>();
namespacesToAdd.AddRange(nodesWithExplicitNamespaces.Select(
n => GetExplicitNamespaceSymbol(n, model)));
var generator = SyntaxGenerator.GetGenerator(document);
var imports = namespacesToAdd.Select(ns => generator.NamespaceImportDeclaration(ns.ToDisplayString()).WithAdditionalAnnotations(Simplifier.Annotation))
.ToArray();
// annotate these nodes so they get simplified later
var newRoot = root.ReplaceNodes(
nodesWithExplicitNamespaces,
(o, r) => r.WithAdditionalAnnotations(Simplifier.Annotation));
var placeSystemNamespaceFirst = options.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language);
var addImportsService = document.GetLanguageService<IAddImportsService>();
var finalRoot = addImportsService.AddImports(
model.Compilation, newRoot, newRoot, imports, placeSystemNamespaceFirst);
return document.WithSyntaxRoot(finalRoot);
}
示例11: FormatTokenAsync
private async Task<IList<TextChange>> FormatTokenAsync(Document document, SyntaxToken token, IEnumerable<IFormattingRule> formattingRules, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var formatter = CreateSmartTokenFormatter(options, formattingRules, root);
var changes = await formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).ConfigureAwait(false);
return changes;
}
示例12: GetFormattingChangesOnReturnAsync
public async Task<IList<TextChange>> GetFormattingChangesOnReturnAsync(Document document, int caretPosition, CancellationToken cancellationToken)
{
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
if (!options.GetOption(FeatureOnOffOptions.AutoFormattingOnReturn))
{
return null;
}
var formattingRules = this.GetFormattingRules(document, caretPosition);
// first, find the token user just typed.
SyntaxToken token = await GetTokenBeforeTheCaretAsync(document, caretPosition, cancellationToken).ConfigureAwait(false);
if (token.IsMissing)
{
return null;
}
string text = null;
if (IsInvalidToken(token, ref text))
{
return null;
}
// Check to see if the token is ')' and also the parent is a using statement. If not, bail
if (TokenShouldNotFormatOnReturn(token))
{
return null;
}
// if formatting range fails, do format token one at least
var changes = await FormatRangeAsync(document, token, formattingRules, cancellationToken).ConfigureAwait(false);
if (changes.Count > 0)
{
return changes;
}
// if we can't, do normal smart indentation
return await FormatTokenAsync(document, token, formattingRules, cancellationToken).ConfigureAwait(false);
}
示例13: GetFormattingChangesAsync
public async Task<IList<TextChange>> GetFormattingChangesAsync(Document document, char typedChar, int caretPosition, CancellationToken cancellationToken)
{
var formattingRules = this.GetFormattingRules(document, caretPosition);
// first, find the token user just typed.
var token = await GetTokenBeforeTheCaretAsync(document, caretPosition, cancellationToken).ConfigureAwait(false);
if (token.IsMissing ||
!ValidSingleOrMultiCharactersTokenKind(typedChar, token.Kind()) ||
token.IsKind(SyntaxKind.EndOfFileToken, SyntaxKind.None))
{
return null;
}
var service = document.GetLanguageService<ISyntaxFactsService>();
if (service != null && service.IsInNonUserCode(token.SyntaxTree, caretPosition, cancellationToken))
{
return null;
}
var shouldNotFormat = await TokenShouldNotFormatOnTypeCharAsync(token, cancellationToken).ConfigureAwait(false);
if (shouldNotFormat)
{
return null;
}
// don't attempt to format on close brace if autoformat on close brace feature is off, instead just smart indent
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var autoFormattingCloseBraceOff =
!options.GetOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace) ||
!options.GetOption(FeatureOnOffOptions.AutoFormattingOnTyping);
bool smartIndentOnly = token.IsKind(SyntaxKind.CloseBraceToken) && autoFormattingCloseBraceOff;
if (smartIndentOnly)
{
// if we're only doing smart indent, then ignore all edits to this token that occur before
// the span of the token. They're irrelevant and may screw up other code the user doesn't
// want touched.
var tokenEdits = await FormatTokenAsync(document, token, formattingRules, cancellationToken).ConfigureAwait(false);
var filteredEdits = tokenEdits.Where(t => t.Span.Start >= token.FullSpan.Start).ToList();
return filteredEdits;
}
// if formatting range fails, do format token one at least
var changes = await FormatRangeAsync(document, token, formattingRules, cancellationToken).ConfigureAwait(false);
if (changes.Count > 0)
{
return changes;
}
return await FormatTokenAsync(document, token, formattingRules, cancellationToken).ConfigureAwait(false);
}
示例14: FormatAndApply
protected override void FormatAndApply(Document document, int position, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var endToken = root.FindToken(position);
if (endToken.IsMissing)
{
return;
}
var ranges = FormattingRangeHelper.FindAppropriateRange(endToken, useDefaultRange: false);
if (ranges == null)
{
return;
}
var startToken = ranges.Value.Item1;
if (startToken.IsMissing || startToken.Kind() == SyntaxKind.None)
{
return;
}
var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var changes = Formatter.GetFormattedTextChanges(root, new TextSpan[] { TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) }, document.Project.Solution.Workspace, options,
rules: null, // use default
cancellationToken: cancellationToken);
document.ApplyTextChanges(changes.ToArray(), cancellationToken);
}
示例15: GetFormattingChangesOnPasteAsync
public async Task<IList<TextChange>> GetFormattingChangesOnPasteAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, textSpan);
var service = document.GetLanguageService<ISyntaxFormattingService>();
if (service == null)
{
return SpecializedCollections.EmptyList<TextChange>();
}
var rules = new List<IFormattingRule>() { new PasteFormattingRule() };
rules.AddRange(service.GetDefaultFormattingRules());
return Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(formattingSpan), document.Project.Solution.Workspace, options, rules, cancellationToken);
}