本文整理汇总了C#中Microsoft.CodeAnalysis.Text.SourceText.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# SourceText.ToString方法的具体用法?C# SourceText.ToString怎么用?C# SourceText.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.Text.SourceText
的用法示例。
在下文中一共展示了SourceText.ToString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestIsEmpty
private static void TestIsEmpty(SourceText text)
{
Assert.Equal(0, text.Length);
Assert.Same(string.Empty, text.ToString());
Assert.Equal(1, text.Lines.Count);
Assert.Equal(0, text.Lines[0].Span.Length);
}
示例2: GetItems
private ImmutableArray<CompletionItem> GetItems(SourceText text, Document document, int position, CompletionTrigger triggerInfo, CancellationToken cancellationToken)
{
var line = text.Lines.GetLineFromPosition(position);
var lineText = text.ToString(TextSpan.FromBounds(line.Start, position));
var match = s_directiveRegex.Match(lineText);
if (!match.Success)
{
return ImmutableArray<CompletionItem>.Empty;
}
var quotedPathGroup = match.Groups[1];
var quotedPath = quotedPathGroup.Value;
var endsWithQuote = PathCompletionUtilities.EndsWithQuote(quotedPath);
if (endsWithQuote && (position >= line.Start + match.Length))
{
return ImmutableArray<CompletionItem>.Empty;
}
var buffer = text.Container.GetTextBuffer();
var snapshot = text.FindCorrespondingEditorTextSnapshot();
if (snapshot == null)
{
return ImmutableArray<CompletionItem>.Empty;
}
var fileSystem = CurrentWorkingDirectoryDiscoveryService.GetService(snapshot);
// TODO: https://github.com/dotnet/roslyn/issues/5263
// Avoid dependency on a specific resolver.
// The search paths should be provided by specialized workspaces:
// - InteractiveWorkspace for interactive window
// - ScriptWorkspace for loose .csx files (we don't have such workspace today)
var searchPaths = (document.Project.CompilationOptions.SourceReferenceResolver as SourceFileResolver)?.SearchPaths ?? ImmutableArray<string>.Empty;
var helper = new FileSystemCompletionHelper(
this,
GetTextChangeSpan(text, position, quotedPathGroup),
fileSystem,
Glyph.OpenFolder,
Glyph.CSharpFile,
searchPaths: searchPaths,
allowableExtensions: new[] { ".csx" },
itemRules: s_rules);
var pathThroughLastSlash = this.GetPathThroughLastSlash(text, position, quotedPathGroup);
return helper.GetItems(pathThroughLastSlash, documentPath: null);
}
示例3: TestTemporaryStorage
private void TestTemporaryStorage(ITemporaryStorageService temporaryStorageService, SourceText text)
{
// create a temporary storage location
var temporaryStorage = temporaryStorageService.CreateTemporaryTextStorage(System.Threading.CancellationToken.None);
// write text into it
temporaryStorage.WriteTextAsync(text).Wait();
// read text back from it
var text2 = temporaryStorage.ReadTextAsync().Result;
Assert.NotSame(text, text2);
Assert.Equal(text.ToString(), text2.ToString());
temporaryStorage.Dispose();
}
示例4: GetItems
private ImmutableArray<CompletionItem> GetItems(SourceText text, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var line = text.Lines.GetLineFromPosition(position);
var lineText = text.ToString(TextSpan.FromBounds(line.Start, position));
var match = s_directiveRegex.Match(lineText);
if (!match.Success)
{
return ImmutableArray<CompletionItem>.Empty;
}
var quotedPathGroup = match.Groups[1];
var quotedPath = quotedPathGroup.Value;
var endsWithQuote = PathCompletionUtilities.EndsWithQuote(quotedPath);
if (endsWithQuote && (position >= line.Start + match.Length))
{
return ImmutableArray<CompletionItem>.Empty;
}
var buffer = text.Container.GetTextBuffer();
var snapshot = text.FindCorrespondingEditorTextSnapshot();
if (snapshot == null)
{
return ImmutableArray<CompletionItem>.Empty;
}
var fileSystem = PathCompletionUtilities.GetCurrentWorkingDirectoryDiscoveryService(snapshot);
var searchPaths = ImmutableArray.Create<string>(fileSystem.CurrentDirectory);
var helper = new FileSystemCompletionHelper(
this,
GetTextChangeSpan(text, position, quotedPathGroup),
fileSystem,
Glyph.OpenFolder,
Glyph.CSharpFile,
searchPaths: searchPaths,
allowableExtensions: new[] { ".csx" },
itemRules: ItemRules.Instance);
var pathThroughLastSlash = this.GetPathThroughLastSlash(text, position, quotedPathGroup);
return helper.GetItems(pathThroughLastSlash, documentPath: null);
}
示例5: FixDiagnostic
private static TextChange FixDiagnostic(IndentationOptions indentationOptions, SourceText sourceText, Diagnostic diagnostic)
{
TextSpan span = diagnostic.Location.SourceSpan;
TextLine startLine = sourceText.Lines.GetLineFromPosition(span.Start);
string text = sourceText.ToString(TextSpan.FromBounds(startLine.Start, span.End));
StringBuilder replacement = StringBuilderPool.Allocate();
int column = 0;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == '\t')
{
var offsetWithinTabColumn = column % indentationOptions.TabSize;
var spaceCount = indentationOptions.TabSize - offsetWithinTabColumn;
if (i >= span.Start - startLine.Start)
{
replacement.Append(' ', spaceCount);
}
column += spaceCount;
}
else
{
if (i >= span.Start - startLine.Start)
{
replacement.Append(c);
}
if (c == '\n')
{
column = 0;
}
else
{
column++;
}
}
}
return new TextChange(span, StringBuilderPool.ReturnAndFree(replacement));
}
示例6: SerializeSourceText
public void SerializeSourceText(ITemporaryStorageWithName storage, SourceText text, ObjectWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
writer.WriteInt32((int)text.ChecksumAlgorithm);
writer.WriteString(text.Encoding?.WebName);
// TODO: refactor this part in its own abstraction (Bits) that has multiple sub types
// rather than using enums
if (storage != null && storage.Name != null)
{
writer.WriteInt32((int)SerializationKinds.MemoryMapFile);
writer.WriteString(storage.Name);
writer.WriteInt64(storage.Size);
return;
}
writer.WriteInt32((int)SerializationKinds.Bits);
writer.WriteString(text.ToString());
}
示例7: ConvertClassifications
protected IEnumerable<SymbolDisplayPart> ConvertClassifications(SourceText text, IEnumerable<ClassifiedSpan> classifications)
{
var parts = new List<SymbolDisplayPart>();
ClassifiedSpan? lastSpan = null;
foreach (var span in classifications)
{
// If there is space between this span and the last one, then add a space.
if (lastSpan != null && lastSpan.Value.TextSpan.End != span.TextSpan.Start)
{
parts.AddRange(Space());
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, text.ToString(span.TextSpan)));
lastSpan = span;
}
}
return parts;
}
开发者ID:reudismam,项目名称:roslyn,代码行数:24,代码来源:AbstractSymbolDisplayService.AbstractSymbolDescriptionBuilder.cs
示例8: ConvertClassifications
private static List<SymbolDisplayPart> ConvertClassifications(
SourceText sourceText, int startPosition, IEnumerable<ClassifiedSpan> classifiedSpans, bool insertSourceTextInGaps = false)
{
var parts = new List<SymbolDisplayPart>();
foreach (var span in classifiedSpans)
{
// If there is space between this span and the last one, then add a space.
if (startPosition != span.TextSpan.Start)
{
if (insertSourceTextInGaps)
{
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null,
sourceText.ToString(TextSpan.FromBounds(
startPosition, span.TextSpan.Start))));
}
else
{
parts.AddRange(Space());
}
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, sourceText.ToString(span.TextSpan)));
startPosition = span.TextSpan.End;
}
}
return parts;
}
示例9: ApplyDocumentTextChanged
protected override async void ApplyDocumentTextChanged (DocumentId id, SourceText text)
{
var document = GetDocument (id);
if (document == null)
return;
bool isOpen;
var filePath = document.FilePath;
Projection projection = null;
foreach (var entry in ProjectionList) {
var p = entry.Projections.FirstOrDefault (proj => proj?.Document?.FileName != null && FilePath.PathComparer.Equals (proj.Document.FileName, filePath));
if (p != null) {
filePath = entry.File.FilePath;
projection = p;
break;
}
}
var data = TextFileProvider.Instance.GetTextEditorData (filePath, out isOpen);
// Guard against already done changes in linked files.
// This shouldn't happen but the roslyn merging seems not to be working correctly in all cases :/
if (document.GetLinkedDocumentIds ().Length > 0 && isOpen && !(text.GetType ().FullName == "Microsoft.CodeAnalysis.Text.ChangedText")) {
return;
}
SourceText formerText;
lock (changedFiles) {
if (changedFiles.TryGetValue (filePath, out formerText)) {
if (formerText.Length == text.Length && formerText.ToString () == text.ToString ())
return;
}
changedFiles [filePath] = text;
}
SourceText oldFile;
if (!isOpen || !document.TryGetText (out oldFile)) {
oldFile = await document.GetTextAsync ();
}
var changes = text.GetTextChanges (oldFile).OrderByDescending (c => c.Span.Start).ToList ();
int delta = 0;
if (!isOpen) {
delta = ApplyChanges (projection, data, changes);
var formatter = CodeFormatterService.GetFormatter (data.MimeType);
if (formatter.SupportsPartialDocumentFormatting) {
var mp = GetMonoProject (CurrentSolution.GetProject (id.ProjectId));
string currentText = data.Text;
foreach (var change in changes) {
delta -= change.Span.Length - change.NewText.Length;
var startOffset = change.Span.Start - delta;
if (projection != null) {
int originalOffset;
if (projection.TryConvertFromProjectionToOriginal (startOffset, out originalOffset))
startOffset = originalOffset;
}
string str;
if (change.NewText.Length == 0) {
str = formatter.FormatText (mp.Policies, currentText, TextSegment.FromBounds (Math.Max (0, startOffset - 1), Math.Min (data.Length, startOffset + 1)));
} else {
str = formatter.FormatText (mp.Policies, currentText, new TextSegment (startOffset, change.NewText.Length));
}
data.ReplaceText (startOffset, change.NewText.Length, str);
}
}
data.Save ();
if (projection != null) {
await UpdateProjectionsDocuments (document, data);
} else {
OnDocumentTextChanged (id, new MonoDevelopSourceText (data), PreservationMode.PreserveValue);
}
FileService.NotifyFileChanged (filePath);
} else {
var formatter = CodeFormatterService.GetFormatter (data.MimeType);
var documentContext = IdeApp.Workbench.Documents.FirstOrDefault (d => FilePath.PathComparer.Compare (d.FileName, filePath) == 0);
var root = await projectChanges.NewProject.GetDocument (id).GetSyntaxRootAsync ();
var annotatedNode = root.DescendantNodesAndSelf ().FirstOrDefault (n => n.HasAnnotation (TypeSystemService.InsertionModeAnnotation));
SyntaxToken? renameTokenOpt = root.GetAnnotatedNodesAndTokens (Microsoft.CodeAnalysis.CodeActions.RenameAnnotation.Kind)
.Where (s => s.IsToken)
.Select (s => s.AsToken ())
.Cast<SyntaxToken?> ()
.FirstOrDefault ();
if (documentContext != null) {
var editor = (TextEditor)data;
await Runtime.RunInMainThread (async () => {
using (var undo = editor.OpenUndoGroup ()) {
var oldVersion = editor.Version;
delta = ApplyChanges (projection, data, changes);
var versionBeforeFormat = editor.Version;
if (formatter.SupportsOnTheFlyFormatting) {
foreach (var change in changes) {
delta -= change.Span.Length - change.NewText.Length;
var startOffset = change.Span.Start - delta;
if (projection != null) {
int originalOffset;
if (projection.TryConvertFromProjectionToOriginal (startOffset, out originalOffset))
//.........这里部分代码省略.........
示例10: GetBodyStartPoint
private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace)
{
Debug.Assert(!openBrace.IsMissing);
var openBraceLine = text.Lines.GetLineFromPosition(openBrace.Span.End);
var textAfterBrace = text.ToString(TextSpan.FromBounds(openBrace.Span.End, openBraceLine.End));
return string.IsNullOrWhiteSpace(textAfterBrace)
? new VirtualTreePoint(openBrace.SyntaxTree, text, text.Lines[openBraceLine.LineNumber + 1].Start)
: new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End);
}
示例11: WithReplaceFirst
internal static SourceText WithReplaceFirst(SourceText text, string oldText, string newText)
{
var oldFullText = text.ToString();
int offset = oldFullText.IndexOf(oldText, StringComparison.Ordinal);
int length = oldText.Length;
var span = new TextSpan(offset, length);
var newFullText = oldFullText.Substring(0, offset) + newText + oldFullText.Substring(span.End);
return SourceText.From(newFullText);
}
示例12: Collapse
private TextChange Collapse(SourceText newText, List<TextChange> changes)
{
if (changes.Count == 0)
{
return new TextChange(new TextSpan(0, 0), "");
}
else if (changes.Count == 1)
{
return changes[0];
}
// The span we want to replace goes from the start of the first span to the end of
// the last span.
var totalOldSpan = TextSpan.FromBounds(changes.First().Span.Start, changes.Last().Span.End);
// We figure out the text we're replacing with by actually just figuring out the
// new span in the newText and grabbing the text out of that. The newSpan will
// start from the same position as the oldSpan, but it's length will be the old
// span's length + all the deltas we accumulate through each text change. i.e.
// if the first change adds 2 characters and the second change adds 4, then
// the newSpan will be 2+4=6 characters longer than the old span.
var sumOfDeltas = changes.Sum(c => c.NewText.Length - c.Span.Length);
var totalNewSpan = new TextSpan(totalOldSpan.Start, totalOldSpan.Length + sumOfDeltas);
return new TextChange(totalOldSpan, newText.ToString(totalNewSpan));
}
示例13: WriteText
public void WriteText(SourceText text, CancellationToken cancellationToken = default(CancellationToken))
{
// Decompose the SourceText into it's underlying parts, since we use it as a key
// into many other caches that don't expect it to be held
_text = text.ToString();
_encoding = text.Encoding;
}
示例14: ConvertClassificationsToParts
internal static ImmutableArray<SymbolDisplayPart> ConvertClassificationsToParts(
SourceText sourceText, int startPosition, IEnumerable<ClassifiedSpan> classifiedSpans)
{
var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance();
foreach (var span in classifiedSpans)
{
// If there is space between this span and the last one, then add a space.
if (startPosition != span.TextSpan.Start)
{
parts.AddRange(Space());
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, sourceText.ToString(span.TextSpan)));
startPosition = span.TextSpan.End;
}
}
return parts.ToImmutableAndFree();
}
示例15: AdjustStaleClassification
internal static ClassifiedSpan AdjustStaleClassification(SourceText rawText, ClassifiedSpan classifiedSpan)
{
// If we marked this as an identifier and it should now be a keyword
// (or vice versa), then fix this up and return it.
var classificationType = classifiedSpan.ClassificationType;
// Check if the token's type has changed. Note: we don't check for "wasPPKeyword &&
// !isPPKeyword" here. That's because for fault tolerance any identifier will end up
// being parsed as a PP keyword eventually, and if we have the check here, the text
// flickers between blue and black while typing. See
// http://vstfdevdiv:8080/web/wi.aspx?id=3521 for details.
var wasKeyword = classificationType == ClassificationTypeNames.Keyword;
var wasIdentifier = classificationType == ClassificationTypeNames.Identifier;
// We only do this for identifiers/keywords.
if (wasKeyword || wasIdentifier)
{
// Get the current text under the tag.
var span = classifiedSpan.TextSpan;
var text = rawText.ToString(span);
// Now, try to find the token that corresponds to that text. If
// we get 0 or 2+ tokens, then we can't do anything with this.
// Also, if that text includes trivia, then we can't do anything.
var token = SyntaxFactory.ParseToken(text);
if (token.Span.Length == span.Length)
{
// var and dynamic are not contextual keywords. They are always identifiers
// (that we classify as keywords). Because we are just parsing a token we don't
// know if we're in the right context for them to be identifiers or keywords.
// So, we base on decision on what they were before. i.e. if we had a keyword
// before, then assume it stays a keyword if we see 'var' or 'dynamic.
var isKeyword = SyntaxFacts.IsKeywordKind(token.CSharpKind())
|| (wasKeyword && SyntaxFacts.GetContextualKeywordKind(text) != SyntaxKind.None)
|| (wasKeyword && token.ToString() == "var")
|| (wasKeyword && token.ToString() == "dynamic");
var isIdentifier = token.CSharpKind() == SyntaxKind.IdentifierToken;
// We only do this for identifiers/keywords.
if (isKeyword || isIdentifier)
{
if ((wasKeyword && !isKeyword) ||
(wasIdentifier && !isIdentifier))
{
// It changed! Return the new type of tagspan.
return new ClassifiedSpan(
isKeyword ? ClassificationTypeNames.Keyword : ClassificationTypeNames.Identifier, span);
}
}
}
}
// didn't need to do anything to this one.
return classifiedSpan;
}