public static void CheckPositionConsistency(AstNode node, string currentFileName, IDocument currentDocument = null) { if (currentDocument == null) { currentDocument = new ReadOnlyDocument(File.ReadAllText(currentFileName)); } string comment = "(" + node.GetType().Name + " at " + node.StartLocation + " in " + currentFileName + ")"; var pred = node.StartLocation <= node.EndLocation; if (!pred) { PrintNode(node); } Assert.IsTrue(pred, "StartLocation must be before EndLocation " + comment); var prevNodeEnd = node.StartLocation; var prevNode = node; for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) { bool assertion = child.StartLocation >= prevNodeEnd; if (!assertion) { PrintNode(prevNode); PrintNode(node); } Assert.IsTrue(assertion, currentFileName + ": Child " + child.GetType() + " (" + child.StartLocation + ")" + " must start after previous sibling " + prevNode.GetType() + "(" + prevNode.StartLocation + ")"); CheckPositionConsistency(child, currentFileName, currentDocument); prevNodeEnd = child.EndLocation; prevNode = child; } Assert.IsTrue(prevNodeEnd <= node.EndLocation, "Last child must end before parent node ends " + comment); }
public static void RandomTests(string filePath, int count, CSharpFormattingOptions policy = null, TextEditorOptions options = null) { if (File.Exists(filePath)) { var code = File.ReadAllText(filePath); var document = new ReadOnlyDocument(code); policy = policy ?? FormattingOptionsFactory.CreateMono(); options = options ?? new TextEditorOptions { IndentBlankLines = false }; var engine = new CacheIndentEngine(new CSharpIndentEngine(document, options, policy) { EnableCustomIndentLevels = true }); Random rnd = new Random(); for (int i = 0; i < count; i++) { int offset = rnd.Next(document.TextLength); engine.Update(offset); if (engine.CurrentIndent.Length == 0) { continue; } } } else { Assert.Fail("File " + filePath + " doesn't exist."); } }
public static CacheIndentEngine CreateEngine(string text, CSharpFormattingOptions formatOptions = null, TextEditorOptions options = null) { if (formatOptions == null) { formatOptions = FormattingOptionsFactory.CreateMono(); formatOptions.AlignToFirstIndexerArgument = formatOptions.AlignToFirstMethodCallArgument = true; } var sb = new StringBuilder(); int offset = 0; for (int i = 0; i < text.Length; i++) { var ch = text [i]; if (ch == '$') { offset = i; continue; } sb.Append(ch); } var document = new ReadOnlyDocument(sb.ToString()); options = options ?? new TextEditorOptions { EolMarker = "\n" }; var result = new CacheIndentEngine(new CSharpIndentEngine(document, options, formatOptions)); result.Update(offset); return(result); }
static int GetIndex(string text) { var editorText = new StringBuilder(); int trigger = 0, end = 0; for (int i = 0; i < text.Length; i++) { if (text[i] == '@') { trigger = editorText.Length; continue; } if (text[i] == '$') { end = editorText.Length; continue; } editorText.Append(text [i]); } var doc = new ReadOnlyDocument(editorText.ToString()); var pctx = new CSharpProjectContent(); var rctx = new CSharpTypeResolveContext(pctx.CreateCompilation().MainAssembly); var ctxProvider = new DefaultCompletionContextProvider(doc, new CSharpUnresolvedFile()); var engine = new CSharpParameterCompletionEngine(doc, ctxProvider, new ParameterCompletionTests.TestFactory(pctx), pctx, rctx); return(engine.GetCurrentParameterIndex(trigger, end)); }
SearchedFile SearchForIssues(FileName fileName, ITextSource fileContent, IEnumerable <IssueManager.IssueProvider> providers, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var context = SDRefactoringContext.Create(fileName, fileContent, TextLocation.Empty, cancellationToken); ReadOnlyDocument document = null; IHighlighter highlighter = null; var results = new List <SearchResultMatch>(); foreach (var provider in providers) { cancellationToken.ThrowIfCancellationRequested(); foreach (var issue in provider.GetIssues(context)) { if (document == null) { document = new ReadOnlyDocument(fileContent, fileName); highlighter = SD.EditorControlService.CreateHighlighter(document); highlighter.BeginHighlighting(); } results.Add(SearchResultMatch.Create(document, issue.Start, issue.End, highlighter)); } } if (highlighter != null) { highlighter.Dispose(); } if (results.Count > 0) { return(new SearchedFile(fileName, results)); } else { return(null); } }
public void InputWithSyntaxError2() { var document = new ReadOnlyDocument("a.b.c.;"); var result = _parser.Parse(new CSharpLexer(document.CreateReader())); Assert.IsNotNull(result.Root); Assert.IsTrue(result.SyntaxErrors.Count > 0); }
public void FindLocalReferences(ParseInformation parseInfo, ITextSource fileContent, IVariable variable, ICompilation compilation, Action <SearchResultMatch> callback, CancellationToken cancellationToken) { var csParseInfo = parseInfo as CSharpFullParseInformation; if (csParseInfo == null) { throw new ArgumentException("Parse info does not have SyntaxTree"); } ReadOnlyDocument document = null; IHighlighter highlighter = null; new FindReferences().FindLocalReferences( variable, csParseInfo.UnresolvedFile, csParseInfo.SyntaxTree, compilation, delegate(AstNode node, ResolveResult result) { if (document == null) { document = new ReadOnlyDocument(fileContent, parseInfo.FileName); highlighter = SD.EditorControlService.CreateHighlighter(document); highlighter.BeginHighlighting(); } var region = new DomRegion(parseInfo.FileName, node.StartLocation, node.EndLocation); int offset = document.GetOffset(node.StartLocation); int length = document.GetOffset(node.EndLocation) - offset; var builder = SearchResultsPad.CreateInlineBuilder(node.StartLocation, node.EndLocation, document, highlighter); var defaultTextColor = highlighter != null ? highlighter.DefaultTextColor : null; callback(new SearchResultMatch(parseInfo.FileName, node.StartLocation, node.EndLocation, offset, length, builder, defaultTextColor)); }, cancellationToken); if (highlighter != null) { highlighter.Dispose(); } }
public void CorrectInput2() { var document = new ReadOnlyDocument("a.b.c;"); var result = _parser.Parse(new CSharpLexer(document.CreateReader())); Assert.IsNotNull(result.Root); Assert.AreEqual(0, result.SyntaxErrors.Count); }
public void InputWithIrrecoverableSyntaxError() { var document = new ReadOnlyDocument("3 + 4"); var result = _parser.Parse(new CSharpLexer(document.CreateReader())); Assert.IsNull(result.Root); Assert.IsTrue(result.SyntaxErrors.Count > 0); }
public Common.DomRegion ResolveTypeByName(string typeName, string typeMemberName) { if (Project == null) { return(Common.DomRegion.Empty); } var code = $"class dummy11111 {{ System.Type t = typeof({typeName}); }}"; var location = new ReadOnlyDocument(code).GetLocation(code.Length - 6); var syntaxTree = new CSharpParser().Parse(code, "dummy11111.cs"); syntaxTree.Freeze(); var unresolvedFile = syntaxTree.ToTypeSystem(); Project = Project.AddOrUpdateFiles(unresolvedFile); var compilation = Project.CreateCompilation(); var result = ResolveAtLocation.Resolve(compilation, unresolvedFile, syntaxTree, location); var type = (result as TypeResolveResult).Type as DefaultResolvedTypeDefinition; if (type != null) { var asm = type.ParentAssembly; if (asm.UnresolvedAssembly is IUnresolvedAssembly) //referenced assembly { FileLocation document = new Reflector().ReconstructToFile(asm, type, memberName: typeMemberName); return(document.ToDomRegion().ToCommon()); } } return(Common.DomRegion.Empty); }
static CSharpIndentEngine CreateEngine(string text) { var policy = FormattingOptionsFactory.CreateMono(); var sb = new StringBuilder(); int offset = 0; for (int i = 0; i < text.Length; i++) { var ch = text [i]; if (ch == '$') { offset = i; continue; } sb.Append(ch); } var document = new ReadOnlyDocument(sb.ToString()); var options = new TextEditorOptions(); var result = new CSharpIndentEngine(document, options, policy); result.UpdateToOffset(offset); return(result); }
void AddCommentTags(SyntaxTree cu, IList<TagComment> tagComments, ITextSource fileContent, FileName fileName, ref IDocument document) { foreach (var comment in cu.Descendants.OfType<Comment>()) { if (comment.CommentType == CommentType.InactiveCode) continue; string match; if (comment.Content.ContainsAny(TaskListTokens, 0, out match)) { if (document == null) document = new ReadOnlyDocument(fileContent, fileName); int commentSignLength = comment.CommentType == CommentType.Documentation || comment.CommentType == CommentType.MultiLineDocumentation ? 3 : 2; int commentEndSignLength = comment.CommentType == CommentType.MultiLine || comment.CommentType == CommentType.MultiLineDocumentation ? 2 : 0; int commentStartOffset = document.GetOffset(comment.StartLocation) + commentSignLength; int commentEndOffset = document.GetOffset(comment.EndLocation) - commentEndSignLength; int endOffset; int searchOffset = 0; // HACK: workaround for parser bug: uses \n instead of \r\n in comment.Content string commentContent = document.GetText(commentStartOffset, Math.Min(commentEndOffset - commentStartOffset + 1, commentEndOffset - commentStartOffset)); do { int start = commentStartOffset + searchOffset; int absoluteOffset = document.IndexOf(match, start, document.TextLength - start, StringComparison.Ordinal); var startLocation = document.GetLocation(absoluteOffset); endOffset = Math.Min(document.GetLineByNumber(startLocation.Line).EndOffset, commentEndOffset); string content = document.GetText(absoluteOffset, endOffset - absoluteOffset); if (content.Length < match.Length) { // HACK: workaround parser bug with multi-line documentation comments break; } tagComments.Add(new TagComment(content.Substring(0, match.Length), new DomRegion(cu.FileName, startLocation.Line, startLocation.Column), content.Substring(match.Length))); searchOffset = endOffset - commentStartOffset; } while (commentContent.ContainsAny(TaskListTokens, searchOffset, out match)); } } }
public ParseInformation Parse(FileName fileName, ITextSource fileContent, bool fullParseInformationRequested, IProject parentProject, CancellationToken cancellationToken) { var csharpProject = parentProject as AlProject; AlParser parser = new AlParser(csharpProject != null ? csharpProject.CompilerSettings : null); SyntaxTree cu = parser.Parse(fileContent, fileName); cu.Freeze(); AlUnresolvedFile file = cu.ToTypeSystem(); ParseInformation parseInfo; if (fullParseInformationRequested) parseInfo = new AlFullParseInformation(file, fileContent.Version, cu); else parseInfo = new ParseInformation(file, fileContent.Version, fullParseInformationRequested); IDocument document = fileContent as IDocument; AddCommentTags(cu, parseInfo.TagComments, fileContent, parseInfo.FileName, ref document); if (fullParseInformationRequested) { if (document == null) document = new ReadOnlyDocument(fileContent, parseInfo.FileName); ((AlFullParseInformation)parseInfo).newFoldings = CreateNewFoldings(cu, document); } return parseInfo; }
public IEnumerable <string> FindReferences(string editorText, string pattern, ResolveResult target, string fileName) { var references = new List <string>(); IDocument document = null; Type patternType = target.GetType(); string targetReflectionName = target.ToString(); if (target is MemberResolveResult) //the caret is on the member implementation { targetReflectionName = targetReflectionName.Replace("MemberResolveResult", "CSharpInvocationResolveResult"); patternType = typeof(CSharpInvocationResolveResult); } //we are looking for the member invocation code. //For example: "[CSharpInvocationResolveResult [Method Test.Who():System.Void]]" foreach (Match m in Regex.Matches(editorText, pattern)) { var match = ResolveFromPosition(editorText, m.Index, fileName); if (match != null && match.GetType() == patternType && match.ToString() == targetReflectionName) { if (document == null) { document = new ReadOnlyDocument(editorText); } int position = m.Index; var location = document.GetLocation(position); var line = document.GetLineByOffset(position); string lineText = editorText.GetTextOf(line); Tuple <int, int> decoration = CSScriptHelper.GetDecorationInfo(editorText); if (decoration.Item1 != -1) //the file content is no the actual one but an auto-generated (decorated) { if (position > decoration.Item1) { position -= decoration.Item2; string actualText = File.ReadAllText(fileName); if (actualText != editorText) { document = new ReadOnlyDocument(actualText); location = document.GetLocation(position); line = document.GetLineByOffset(position); lineText = actualText.GetTextOf(line); } } } references.Add(string.Format("{0}({1},{2}): {3}", fileName, location.Line, location.Column, lineText.Trim())); } } return(references); }
void RenameAllReferences(List<SearchResultMatch> references) { SearchResultMatch firstResult = references.First(); var document = new ReadOnlyDocument(SD.FileService.GetFileContent(firstResult.FileName)); string name = document.GetText(firstResult.StartOffset, firstResult.Length); string newName = GetNewName(name); if (ShouldRenameReference(newName, name)) { ApplyRenames(references, newName); } }
static SearchResultMatch CreateSearchResultMatch(ReferenceEntry entry) { ITextSource textSource = SD.FileService.GetFileContent(entry.fileName); var document = new ReadOnlyDocument(textSource, entry.fileName); TextLocation start = document.GetLocation(entry.minChar); TextLocation end = document.GetLocation(entry.minChar + entry.length); IHighlighter highlighter = SD.EditorControlService.CreateHighlighter(document); return(SearchResultMatch.Create(document, start, end, highlighter)); }
internal static IParameterDataProvider CreateProvider(string text) { string parsedText; string editorText; int cursorPosition = text.IndexOf('$'); int endPos = text.IndexOf('$', cursorPosition + 1); if (endPos == -1) { parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1); } else { parsedText = text.Substring(0, cursorPosition) + new string (' ', endPos - cursorPosition) + text.Substring(endPos + 1); editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1); cursorPosition = endPos - 1; } var doc = new ReadOnlyDocument(editorText); IProjectContent pctx = new CSharpProjectContent(); pctx = pctx.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var compilationUnit = new CSharpParser().Parse(parsedText, "program.cs"); var parsedFile = compilationUnit.ToTypeSystem(); pctx = pctx.UpdateProjectContent(null, parsedFile); var cmp = pctx.CreateCompilation(); var loc = doc.GetLocation(cursorPosition); var engine = new CSharpParameterCompletionEngine(doc, new TestFactory(pctx)); var rctx = new CSharpTypeResolveContext(cmp.MainAssembly); rctx = rctx.WithUsingScope(parsedFile.GetUsingScope(loc).Resolve(cmp)); var curDef = parsedFile.GetInnermostTypeDefinition(loc); if (curDef != null) { rctx = rctx.WithCurrentTypeDefinition(curDef.Resolve(rctx).GetDefinition()); var curMember = parsedFile.GetMember(loc); if (curMember != null) { rctx = rctx.WithCurrentMember(curMember.CreateResolved(rctx)); } } engine.ctx = rctx; engine.CSharpParsedFile = parsedFile; engine.ProjectContent = pctx; engine.Unit = compilationUnit; return(engine.GetParameterDataProvider(cursorPosition, doc.GetCharAt(cursorPosition - 1))); }
public override ICodeCompletionBinding CreateCompletionBinding(string expressionToComplete, ICodeContext context) { if (context == null) throw new ArgumentNullException("context"); string content = GeneratePartialClassContextStub(context); const string caretPoint = "$__Caret_Point__$;"; int caretOffset = content.IndexOf(caretPoint, StringComparison.Ordinal) + expressionToComplete.Length; SD.Log.DebugFormatted("context used for dot completion: {0}", content.Replace(caretPoint, "$" + expressionToComplete + "|$")); var doc = new ReadOnlyDocument(content.Replace(caretPoint, expressionToComplete)); return new CSharpCompletionBinding(context, doc.GetLocation(caretOffset), doc.CreateSnapshot()); }
protected static IDocument GetResult(CSharpFormattingOptions policy, string input) { var adapter = new ReadOnlyDocument(input); var visitor = new AstFormattingVisitor(policy, adapter, factory); var compilationUnit = new CSharpParser().Parse(new StringReader(input)); compilationUnit.AcceptVisitor(visitor, null); return(new ReadOnlyDocument(ApplyChanges(input, visitor.Changes))); }
void RenameAllReferences(List <SearchResultMatch> references) { SearchResultMatch firstResult = references.First(); var document = new ReadOnlyDocument(SD.FileService.GetFileContent(firstResult.FileName)); string name = document.GetText(firstResult.StartOffset, firstResult.Length); string newName = GetNewName(name); if (ShouldRenameReference(newName, name)) { ApplyRenames(references, newName); } }
void AssertOutput(AstNode node) { RemoveTokens(node); StringWriter w = new StringWriter(); w.NewLine = "\n"; node.AcceptVisitor(new CSharpOutputVisitor(TokenWriter.CreateWriterThatSetsLocationsInAST(w), FormattingOptionsFactory.CreateSharpDevelop())); var doc = new ReadOnlyDocument(w.ToString()); ConsistencyChecker.CheckMissingTokens(node, "test.cs", doc); ConsistencyChecker.CheckPositionConsistency(node, "test.cs", doc); }
void FindReferencesInFile(SymbolSearchArgs searchArguments, ISymbol entity, FileName fileName, Action <SearchedFile> callback, CancellationToken cancellationToken) { ITextSource textSource = searchArguments.ParseableFileContentFinder.Create(fileName); if (textSource == null) { return; } int offset = textSource.IndexOf(entity.Name, 0, textSource.TextLength, StringComparison.Ordinal); if (offset < 0) { return; } var parseInfo = SD.ParserService.Parse(fileName, textSource) as XamlFullParseInformation; if (parseInfo == null) { return; } ReadOnlyDocument document = null; IHighlighter highlighter = null; List <SearchResultMatch> results = new List <SearchResultMatch>(); XamlAstResolver resolver = new XamlAstResolver(compilation, parseInfo); do { if (document == null) { document = new ReadOnlyDocument(textSource, fileName); highlighter = SD.EditorControlService.CreateHighlighter(document); highlighter.BeginHighlighting(); } var result = resolver.ResolveAtLocation(document.GetLocation(offset + entity.Name.Length / 2 + 1), cancellationToken); int length = entity.Name.Length; if ((result is TypeResolveResult && ((TypeResolveResult)result).Type.Equals(entity)) || (result is MemberResolveResult && ((MemberResolveResult)result).Member.Equals(entity))) { var region = new DomRegion(fileName, document.GetLocation(offset), document.GetLocation(offset + length)); var builder = SearchResultsPad.CreateInlineBuilder(region.Begin, region.End, document, highlighter); results.Add(new SearchResultMatch(fileName, document.GetLocation(offset), document.GetLocation(offset + length), offset, length, builder, highlighter.DefaultTextColor)); } offset = textSource.IndexOf(entity.Name, offset + length, textSource.TextLength - offset - length, StringComparison.OrdinalIgnoreCase); } while (offset > 0); if (highlighter != null) { highlighter.Dispose(); } if (results.Count > 0) { callback(new SearchedFile(fileName, results)); } }
/// <summary> /// Creates a new DocumentHighlighter instance. /// </summary> public DocumentHighlighter(ReadOnlyDocument document, IHighlightingDefinition definition) { if (document == null) { throw new ArgumentNullException("document"); } if (definition == null) { throw new ArgumentNullException("definition"); } this.document = document; this.definition = definition; InvalidateHighlighting(); }
public void AddCodeBlock(string textContent, bool keepLargeMargin = false) { var document = new ReadOnlyDocument(textContent); var highlightingDefinition = HighlightingManager.Instance.GetDefinition(SyntaxHighlighting); var block = DocumentPrinter.ConvertTextDocumentToBlock(document, highlightingDefinition); block.FontFamily = GetCodeFont(); if (!keepLargeMargin) { block.Margin = new Thickness(0, 6, 0, 6); } AddBlock(block); }
/// <summary> /// Converts a readonly TextDocument to a RichText and applies the provided highlighting definition. /// </summary> public static RichText ConvertTextDocumentToRichText(ReadOnlyDocument document, IHighlightingDefinition highlightingDefinition) { IHighlighter highlighter; if (highlightingDefinition != null) { highlighter = new DocumentHighlighter(document, highlightingDefinition); } else { highlighter = null; } return(ConvertTextDocumentToRichText(document, highlighter)); }
public NRefTypes.DomRegion ToDomRegion() { if (string.IsNullOrEmpty(FileName)) { return(NRefTypes.DomRegion.Empty); } string text = File.ReadAllText(FileName); var doc = new ReadOnlyDocument(text); var startLocation = doc.GetLocation(StartPosition); var endLocation = doc.GetLocation(EndPosition); return(new NRefTypes.DomRegion(FileName, startLocation, endLocation)); }
static public void Undecorate(string text, ref DomRegion region) { int pos = text.IndexOf("///CS-Script auto-class generation"); if (pos != -1) { var injectedLine = new ReadOnlyDocument(text).GetLineByOffset(pos); if (injectedLine.LineNumber < region.BeginLine) { region.BeginLine--; region.EndLine--; } } }
static public Tuple <int, int> GetDecorationInfo(string code) { int pos = code.IndexOf("///CS-Script auto-class generation"); if (pos != -1) { var injectedLine = new ReadOnlyDocument(code).GetLineByOffset(pos); return(new Tuple <int, int>(injectedLine.Offset, injectedLine.Length + Environment.NewLine.Length)); } else { return(new Tuple <int, int>(-1, 0)); } }
public XamlAstResolver(ICompilation compilation, XamlFullParseInformation parseInfo) { if (compilation == null) { throw new ArgumentNullException("compilation"); } if (parseInfo == null) { throw new ArgumentNullException("parseInfo"); } this.compilation = compilation; this.parseInfo = parseInfo; this.textDocument = new ReadOnlyDocument(parseInfo.Text, parseInfo.FileName); }
SearchedFile SearchFile(FileName fileName) { ITextSource source = fileFinder.Create(fileName); if (source == null) { return(null); } ThrowIfCancellationRequested(); ReadOnlyDocument document = null; IHighlighter highlighter = null; int offset = 0; int length = source.TextLength; if (Target == SearchTarget.CurrentSelection && Selection != null) { offset = Selection.Offset; length = Selection.Length; } List <SearchResultMatch> results = new List <SearchResultMatch>(); foreach (var result in strategy.FindAll(source, offset, length)) { ThrowIfCancellationRequested(); if (document == null) { document = new ReadOnlyDocument(source, fileName); highlighter = SD.EditorControlService.CreateHighlighter(document); highlighter.BeginHighlighting(); } var start = document.GetLocation(result.Offset); var end = document.GetLocation(result.Offset + result.Length); var builder = SearchResultsPad.CreateInlineBuilder(start, end, document, highlighter); results.Add(new AvalonEditSearchResultMatch(fileName, start, end, result.Offset, result.Length, builder, highlighter.DefaultTextColor, result)); } if (highlighter != null) { highlighter.Dispose(); } if (results.Count > 0) { return(new SearchedFile(fileName, results)); } else { return(null); } }
internal IDocument GetCompletionDocument(out int offset) { var lineText = GetCurrentLineText(); var line = Doc.GetLineByOffset(Offset); offset = Offset - line.Offset - prompt.Length; var vars = ScriptingEngine.GetVars(); var code = vars + lineText; offset += vars.Length; var doc = new ReadOnlyDocument(new ICSharpCode.NRefactory.Editor.StringTextSource(code), textEditor.FileName); return(doc); }
public override ICodeCompletionBinding CreateCompletionBinding(string expressionToComplete, ICodeContext context) { if (context == null) { throw new ArgumentNullException("context"); } string content = GeneratePartialClassContextStub(context); const string caretPoint = "$__Caret_Point__$;"; int caretOffset = content.IndexOf(caretPoint, StringComparison.Ordinal) + expressionToComplete.Length; SD.Log.DebugFormatted("context used for dot completion: {0}", content.Replace(caretPoint, "$" + expressionToComplete + "|$")); var doc = new ReadOnlyDocument(content.Replace(caretPoint, expressionToComplete)); return(new CSharpCompletionBinding(context, doc.GetLocation(caretOffset), doc.CreateSnapshot())); }
public static void ReadAndTest(string filePath, CSharpFormattingOptions policy = null, TextEditorOptions options = null) { if (File.Exists(filePath)) { filePath = Path.GetFullPath(filePath); var code = File.ReadAllText(filePath); var document = new ReadOnlyDocument(code); if (policy == null) { policy = FormattingOptionsFactory.CreateMono(); policy.AlignToFirstIndexerArgument = policy.AlignToFirstMethodCallArgument = true; } options = options ?? new TextEditorOptions { IndentBlankLines = false, EolMarker = "\n" }; var engine = new CacheIndentEngine(new CSharpIndentEngine(document, options, policy) { EnableCustomIndentLevels = true }); int errors = 0; foreach (var ch in code) { if (options.EolMarker[0] == ch) { if (!(engine.LineBeganInsideMultiLineComment || engine.LineBeganInsideVerbatimString)) { if (engine.CurrentIndent.Length > 0) { if (engine.NeedsReindent) { errors++; Console.WriteLine(string.Format("Indent: {2}, Current indent: {3} in {0}:{1}", filePath, engine.Location.Line, engine.ThisLineIndent.Length, engine.CurrentIndent.Length)); } } } } engine.Push(ch); } Assert.AreEqual(0, errors); } else { Assert.Fail("File " + filePath + " doesn't exist."); } }
public void AddSignatureBlock(string signature, int currentParameterOffset, int currentParameterLength, string currentParameterName) { ParameterName = currentParameterName; var document = new ReadOnlyDocument(signature); var highlightingDefinition = HighlightingManager.Instance.GetDefinition(SyntaxHighlighting); var richText = DocumentPrinter.ConvertTextDocumentToRichText(document, highlightingDefinition).ToRichTextModel(); richText.SetFontWeight(currentParameterOffset, currentParameterLength, FontWeights.Bold); var block = new Paragraph(); block.Inlines.AddRange(richText.CreateRuns(document)); block.FontFamily = GetCodeFont(); block.TextAlignment = TextAlignment.Left; AddBlock(block); }
public void ParseAndCheckPositions() { CSharpParser parser = new CSharpParser(); foreach (string fileName in fileNames) { var currentDocument = new ReadOnlyDocument(File.ReadAllText(fileName)); SyntaxTree syntaxTree = parser.Parse(currentDocument, fileName); if (parser.HasErrors) { continue; } ConsistencyChecker.CheckPositionConsistency(syntaxTree, fileName, currentDocument); ConsistencyChecker.CheckMissingTokens(syntaxTree, fileName, currentDocument); } }
public static CSharpCompletionContext Get(ITextEditor editor, ICodeContext context, TextLocation currentLocation, ITextSource fileContent) { IDocument document = new ReadOnlyDocument(fileContent); var projectContent = context.Compilation.MainAssembly.UnresolvedAssembly as IProjectContent; if (projectContent == null) return null; CSharpParser parser = new CSharpParser(); parser.GenerateTypeSystemMode = false; SyntaxTree cu = parser.Parse(fileContent, Path.GetRandomFileName() + ".cs"); cu.Freeze(); CSharpUnresolvedFile unresolvedFile = cu.ToTypeSystem(); ICompilation compilation = projectContent.AddOrUpdateFiles(unresolvedFile).CreateCompilation(SD.ParserService.GetCurrentSolutionSnapshot()); return new CSharpCompletionContext(editor, EmptyList<string>.Instance, compilation, projectContent, document, unresolvedFile, currentLocation); }
public static CodeSuggestionsList GetSuggestions(string source) { var offset = source.IndexOf('$'); source = source.Replace("$", ""); var document = new ReadOnlyDocument(source); var caretLocation = document.OffsetToLocation(offset); var file = new SourceFile("Program.cs") { CompilationUnit = CSharpLanguage.Instance.Parse(document) }; var assembly = new SourceAssembly("TestAssembly") { SourceFiles = { file } }; var compilation = new Compilation(assembly); compilation.Assemblies.Add(new NetAssembly(CorlibAssembly, typeof(object).Assembly.Location)); var engine = new CSharpCompletionEngine(document, file); return new CodeSuggestionsList(engine.GetSuggestions(caretLocation).ToList()); }
public static void ShowAsSearchResults(string title, List<SearchResultMatch> list) { if (list == null) return; List<SearchResultMatch> results = new List<SearchResultMatch>(list.Count); ReadOnlyDocument document = null; ITextSource buffer = null; FileName fileName = null; IHighlighter highlighter = null; foreach (SearchResultMatch r in list) { if (document == null || fileName != r.FileName) { if (highlighter != null) { highlighter.Dispose(); } fileName = r.FileName; buffer = SD.FileService.GetFileContent(r.FileName); document = new ReadOnlyDocument(buffer, r.FileName); highlighter = SD.EditorControlService.CreateHighlighter(document); highlighter.BeginHighlighting(); } var start = r.StartLocation; var end = r.EndLocation; var startOffset = document.GetOffset(start); var endOffset = document.GetOffset(end); var builder = SearchResultsPad.CreateInlineBuilder(start, end, document, highlighter); var defaultTextColor = highlighter != null ? highlighter.DefaultTextColor : null; SearchResultMatch res = new SearchResultMatch(fileName, start, end, startOffset, endOffset - startOffset, builder, defaultTextColor); results.Add(res); } if (highlighter != null) { highlighter.Dispose(); } SearchResultsPad.Instance.ShowSearchResults(title, results); SearchResultsPad.Instance.BringToFront(); }
/// <summary> /// Gets the project resource from the specified expression. /// </summary> public ProjectResourceInfo GetProjectResource(CodePropertyReferenceExpression propRef) { CodeTypeReferenceExpression typeRef = propRef.TargetObject as CodeTypeReferenceExpression; if (typeRef == null) { LoggingService.Info("Target of possible project resources property reference is not a type reference, but " + propRef.TargetObject.ToString() + "."); return null; } ICompilation compilation = SD.ParserService.GetCompilation(project); // Get the (generated) class where the resource is defined. var resourceClass = compilation.FindType(new FullTypeName(typeRef.Type.BaseType)).GetDefinition(); if (resourceClass == null) { throw new InvalidOperationException("Could not find class for project resources: '" + typeRef.Type.BaseType + "'."); } if (resourceClass.Region.IsEmpty) return null; // Make sure the class we have found is a generated resource class. if (!IsGeneratedResourceClass(resourceClass)) { return null; } // Get the name of the resource file based on the file that contains the generated class. string resourceFileName = Path.GetFileNameWithoutExtension(resourceClass.Region.FileName); if (resourceFileName.EndsWith("Designer", StringComparison.OrdinalIgnoreCase)) { resourceFileName = Path.GetFileNameWithoutExtension(resourceFileName); } resourceFileName = Path.Combine(Path.GetDirectoryName(resourceClass.Region.FileName), resourceFileName); if (File.Exists(resourceFileName + ".resources")) { resourceFileName = resourceFileName + ".resources"; } else if (File.Exists(resourceFileName + ".resx")) { resourceFileName = resourceFileName + ".resx"; } else { throw new FileNotFoundException("Could not find the resource file for type '" + resourceClass.FullName + "'. Tried these file names: '" + resourceFileName + ".(resources|resx)'."); } // Get the property for the resource. IProperty prop = resourceClass.Properties.SingleOrDefault(p => p.Name == propRef.PropertyName); if (prop == null) { throw new InvalidOperationException("Property '" + propRef.PropertyName + "' not found in type '" + resourceClass.FullName + "'."); } if (!prop.CanGet) { throw new InvalidOperationException("Property '" + propRef.PropertyName + "' in type '" + resourceClass.FullName + "' does not have a getter."); } // Get the code of the resource class and // extract the resource key from the property. // This is necessary because the key may differ from the property name // if special characters are used. // It would be better if we could use a real code parser for this, but // that is not possible without getting dependent on the programming language. IDocument doc = new ReadOnlyDocument(SD.FileService.GetFileContent(resourceClass.Region.FileName)); int startOffset = doc.PositionToOffset(prop.Getter.BodyRegion.BeginLine, prop.Getter.BodyRegion.BeginColumn); int endOffset = doc.PositionToOffset(prop.Getter.BodyRegion.EndLine, prop.Getter.BodyRegion.EndColumn); string code = doc.GetText(startOffset, endOffset - startOffset + 1); int index = code.IndexOf("ResourceManager", StringComparison.Ordinal); if (index == -1) { throw new InvalidOperationException("No reference to ResourceManager found in property getter of '" + prop.FullName + "'. Code: '" + code + "'"); } index = code.IndexOf("Get", index, StringComparison.Ordinal); if (index == -1) { throw new InvalidOperationException("No call to Get... found in property getter of '" + prop.FullName + "'. Code: '" + code + "'"); } index = code.IndexOf(this.StringLiteralDelimiter, index + 1, StringComparison.Ordinal); if (index == -1) { throw new InvalidOperationException("No string delimiter ('" + this.StringLiteralDelimiter + "') found in property getter of '" + prop.FullName + "'. Code: '" + code + "'"); } index += this.StringLiteralDelimiter.Length; int endIndex = code.LastIndexOf(this.StringLiteralDelimiter, StringComparison.Ordinal); if (endIndex == -1) { throw new InvalidOperationException("No string terminator ('" + this.StringLiteralDelimiter + "') found in property getter of '" + prop.FullName + "'. Code: '" + code + "'"); } string resourceKey = code.Substring(index, endIndex - index); LoggingService.Debug("-> Decoded resource: In: " + resourceFileName + ". Key: " + resourceKey); return new ProjectResourceInfo(new FileName(resourceFileName), resourceKey); }
void RenameReferencesInFile(SymbolRenameArgs args, IList<IFindReferenceSearchScope> searchScopeList, FileName fileName, Action<PatchedFile> callback, Action<Error> errorCallback, bool isNameValid, CancellationToken cancellationToken) { ITextSource textSource = args.ParseableFileContentFinder.Create(fileName); if (textSource == null) return; if (searchScopeList != null) { if (!searchScopeList.DistinctBy(scope => scope.SearchTerm ?? String.Empty).Any( scope => (scope.SearchTerm == null) || (textSource.IndexOf(scope.SearchTerm, 0, textSource.TextLength, StringComparison.Ordinal) >= 0))) return; } var parseInfo = SD.ParserService.Parse(fileName, textSource) as CSharpFullParseInformation; if (parseInfo == null) return; ReadOnlyDocument document = null; IHighlighter highlighter = null; List<RenameResultMatch> results = new List<RenameResultMatch>(); // Grab the unresolved file matching the compilation version // (this may differ from the version created by re-parsing the project) CSharpUnresolvedFile unresolvedFile = null; IProjectContent pc = compilation.MainAssembly.UnresolvedAssembly as IProjectContent; if (pc != null) { unresolvedFile = pc.GetFile(fileName) as CSharpUnresolvedFile; } CSharpAstResolver resolver = new CSharpAstResolver(compilation, parseInfo.SyntaxTree, unresolvedFile); fr.RenameReferencesInFile( searchScopeList, args.NewName, resolver, delegate (RenameCallbackArguments callbackArgs) { var node = callbackArgs.NodeToReplace; string newCode = callbackArgs.NewNode.ToString(); if (document == null) { document = new ReadOnlyDocument(textSource, fileName); if (args.ProvideHighlightedLine) { highlighter = SD.EditorControlService.CreateHighlighter(document); highlighter.BeginHighlighting(); } } var startLocation = node.StartLocation; var endLocation = node.EndLocation; int offset = document.GetOffset(startLocation); int length = document.GetOffset(endLocation) - offset; if (args.ProvideHighlightedLine) { var builder = SearchResultsPad.CreateInlineBuilder(node.StartLocation, node.EndLocation, document, highlighter); var defaultTextColor = highlighter != null ? highlighter.DefaultTextColor : null; results.Add(new RenameResultMatch(fileName, startLocation, endLocation, offset, length, newCode, builder, defaultTextColor)); } else { results.Add(new RenameResultMatch(fileName, startLocation, endLocation, offset, length, newCode)); } }, errorCallback, cancellationToken); if (highlighter != null) { highlighter.Dispose(); } if (results.Count > 0) { if (!isNameValid) { errorCallback(new Error(ErrorType.Error, string.Format("The name '{0}' is not valid in the current context!", args.NewName), new DomRegion(fileName, results[0].StartLocation))); return; } IDocument changedDocument = new TextDocument(document); var oldVersion = changedDocument.Version; List<SearchResultMatch> fixedResults = new List<SearchResultMatch>(); int lastStartOffset = changedDocument.TextLength + 1; foreach (var result in results.OrderByDescending(m => m.StartOffset)) { if (result.EndOffset <= lastStartOffset) { changedDocument.Replace(result.StartOffset, result.Length, result.NewCode); fixedResults.Add(result); lastStartOffset = result.StartOffset; } } callback(new PatchedFile(fileName, fixedResults, oldVersion, changedDocument.Version)); } }
void FindReferencesInFile(SymbolSearchArgs args, IList<IFindReferenceSearchScope> searchScopeList, FileName fileName, Action<SearchedFile> callback, CancellationToken cancellationToken) { ITextSource textSource = args.ParseableFileContentFinder.Create(fileName); if (textSource == null) return; if (searchScopeList != null) { if (!searchScopeList.DistinctBy(scope => scope.SearchTerm ?? String.Empty).Any( scope => (scope.SearchTerm == null) || (textSource.IndexOf(scope.SearchTerm, 0, textSource.TextLength, StringComparison.Ordinal) >= 0))) return; } var parseInfo = SD.ParserService.Parse(fileName, textSource) as CSharpFullParseInformation; if (parseInfo == null) return; ReadOnlyDocument document = null; IHighlighter highlighter = null; List<SearchResultMatch> results = new List<SearchResultMatch>(); // Grab the unresolved file matching the compilation version // (this may differ from the version created by re-parsing the project) CSharpUnresolvedFile unresolvedFile = null; IProjectContent pc = compilation.MainAssembly.UnresolvedAssembly as IProjectContent; if (pc != null) { unresolvedFile = pc.GetFile(fileName) as CSharpUnresolvedFile; } fr.FindReferencesInFile( searchScopeList, unresolvedFile, parseInfo.SyntaxTree, compilation, delegate (AstNode node, ResolveResult result) { if (document == null) { document = new ReadOnlyDocument(textSource, fileName); highlighter = SD.EditorControlService.CreateHighlighter(document); highlighter.BeginHighlighting(); } Identifier identifier = node.GetChildByRole(Roles.Identifier); if (!identifier.IsNull) node = identifier; var region = new DomRegion(fileName, node.StartLocation, node.EndLocation); int offset = document.GetOffset(node.StartLocation); int length = document.GetOffset(node.EndLocation) - offset; var builder = SearchResultsPad.CreateInlineBuilder(node.StartLocation, node.EndLocation, document, highlighter); var defaultTextColor = highlighter != null ? highlighter.DefaultTextColor : null; results.Add(new SearchResultMatch(fileName, node.StartLocation, node.EndLocation, offset, length, builder, defaultTextColor)); }, cancellationToken); if (highlighter != null) { highlighter.Dispose(); } if (results.Count > 0) { // Remove overlapping results List<SearchResultMatch> fixedResults = new List<SearchResultMatch>(); int lastEndOffset = 0; foreach (var result in results.OrderBy(m => m.StartOffset)) { if (result.StartOffset >= lastEndOffset) { fixedResults.Add(result); lastEndOffset = result.EndOffset; } } callback(new SearchedFile(fileName, fixedResults)); } }
void DisplayTooltip(MouseEventArgs e) { int line = GetLineFromMousePosition(e); if (line == 0) return; int startLine; bool added; string oldText = changeWatcher.GetOldVersionFromLine(line, out startLine, out added); TextEditor editor = this.TextView.GetService<TextEditor>(); markerService = this.TextView.GetService<ITextMarkerService>(); LineChangeInfo zeroLineInfo = changeWatcher.GetChange(0); int offset, length; bool hasNewVersion = changeWatcher.GetNewVersionFromLine(line, out offset, out length); if (line == 1 && zeroLineInfo.Change == ChangeType.Deleted) { int zeroStartLine; bool zeroAdded; startLine = 1; string deletedText = changeWatcher.GetOldVersionFromLine(0, out zeroStartLine, out zeroAdded); var docLine = editor.Document.GetLineByNumber(line); string newLine = DocumentUtilities.GetLineTerminator(changeWatcher.CurrentDocument, 1); deletedText += newLine; deletedText += editor.Document.GetText(docLine.Offset, docLine.Length); if (oldText != null) oldText = deletedText + newLine + oldText; else oldText = deletedText; if (!hasNewVersion) { offset = 0; length = docLine.Length; hasNewVersion = true; } } if (hasNewVersion) { if (marker != null) markerService.Remove(marker); if (length <= 0) { marker = null; length = 0; } else { marker = markerService.Create(offset, length); marker.BackgroundColor = Colors.LightGreen; } } if (oldText != null) { LineChangeInfo currLineInfo = changeWatcher.GetChange(startLine); if (currLineInfo.Change == ChangeType.Deleted && !(line == 1 && zeroLineInfo.Change == ChangeType.Deleted)) { var docLine = editor.Document.GetLineByNumber(startLine); if (docLine.DelimiterLength == 0) oldText = DocumentUtilities.GetLineTerminator(changeWatcher.CurrentDocument, startLine) + oldText; oldText = editor.Document.GetText(docLine.Offset, docLine.TotalLength) + oldText; } DiffControl differ = new DiffControl(); differ.CopyEditorSettingsAndHighlighting(editor); differ.editor.Document.Text = oldText; if (oldText == string.Empty) { differ.editor.Visibility = Visibility.Collapsed; differ.copyButton.Visibility = Visibility.Collapsed; } else { if (differ.editor.SyntaxHighlighting != null) { var baseDocument = new ReadOnlyDocument(changeWatcher.BaseDocument, TextView.Document.FileName); var mainHighlighter = new DocumentHighlighter(baseDocument, differ.editor.SyntaxHighlighting); var popupHighlighter = differ.editor.TextArea.GetService(typeof(IHighlighter)) as DocumentHighlighter; popupHighlighter.InitialSpanStack = mainHighlighter.GetSpanStack(currLineInfo.OldStartLineNumber); } } differ.revertButton.Click += delegate { if (hasNewVersion) { Document.Replace(offset, length, oldText); tooltip.IsOpen = false; } }; const double borderThickness = 1; tooltip.Child = new Border { Child = differ, BorderBrush = editor.TextArea.Foreground, BorderThickness = new Thickness(borderThickness) }; if (tooltip.IsOpen) tooltip.IsOpen = false; tooltip.Closed += delegate { if (marker != null) markerService.Remove(marker); }; tooltip.HorizontalOffset = -borderThickness - TextView.ScrollOffset.X; tooltip.VerticalOffset = TextView.GetVisualTopByDocumentLine(startLine) - TextView.ScrollOffset.Y; tooltip.Placement = PlacementMode.Top; tooltip.PlacementTarget = this.TextView; tooltip.IsOpen = true; } }
void InsertEventHandlerInternal(string methodName, IEvent evt) { CSharpCodeGenerator generator = new CSharpCodeGenerator(); var primary = loader.GetPrimaryTypeDefinition(); var evtHandler = primary.GetMethods(m => m.Name == methodName, GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault(); if (evtHandler == null) { generator.InsertEventHandler(primary, methodName, evt, true); } else { CSharpBinding.Parser.CSharpFullParseInformation parseInfo; var node = evtHandler.GetDeclaration(out parseInfo) as MethodDeclaration; var fileName = new FileName(evtHandler.Region.FileName); var fileContentFinder = new ParseableFileContentFinder(); if (node != null && !node.Body.IsNull) { var location = node.Body.FirstChild.StartLocation; var firstStatement = node.Body.Children.OfType<Statement>().FirstOrDefault(); if (firstStatement == null) { var fileContent = fileContentFinder.Create(fileName); var document = new ReadOnlyDocument(fileContent); var offset = document.GetOffset(new TextLocation(location.Line + 1, 1)); var length = DocumentUtilities.GetWhitespaceAfter(fileContent, offset).Length; location = new TextLocation(location.Line + 1, length + 1); } else { location = firstStatement.StartLocation; } SD.FileService.JumpToFilePosition(fileName, location.Line, location.Column); } } }
public void Replace(int offset, int length, string text) { if (offset < 0 || offset > TextLength) throw new ArgumentOutOfRangeException(nameof(offset)); if (length < 0 || offset + length > TextLength) throw new ArgumentOutOfRangeException(nameof(length)); if (text == null) throw new ArgumentNullException(nameof(text)); var eventArgs = new TextChangeEventArgs(offset, GetText(offset, length), text); OnTextChanging(eventArgs); _cachedSnapshot = null; Builder.Remove(offset, length); Builder.Insert(offset, text); OnTextChanged(eventArgs); }
public IDocument CreateDocumentSnapshot() { return _cachedSnapshot ?? (_cachedSnapshot = new ReadOnlyDocument(this)); }
static SearchResultMatch CreateSearchResultMatch(ReferenceEntry entry) { ITextSource textSource = SD.FileService.GetFileContent(entry.fileName); var document = new ReadOnlyDocument(textSource, entry.fileName); TextLocation start = document.GetLocation(entry.minChar); TextLocation end = document.GetLocation(entry.minChar + entry.length); IHighlighter highlighter = SD.EditorControlService.CreateHighlighter(document); return SearchResultMatch.Create(document, start, end, highlighter); }
public void AddSignatureBlock(string signature, int currentParameterOffset, int currentParameterLength, string currentParameterName) { ParameterName = currentParameterName; var document = new ReadOnlyDocument(signature); var highlightingDefinition = HighlightingManager.Instance.GetDefinition("C#"); var richText = DocumentPrinter.ConvertTextDocumentToRichText(document, highlightingDefinition).ToRichTextModel(); richText.SetFontWeight(currentParameterOffset, currentParameterLength, FontWeights.Bold); var block = new Paragraph(); block.Inlines.AddRange(richText.CreateRuns(document)); block.FontFamily = GetCodeFont(); block.TextAlignment = TextAlignment.Left; AddBlock(block); }
public void AddCodeBlock(string textContent, bool keepLargeMargin = false) { var document = new ReadOnlyDocument(textContent); var highlightingDefinition = HighlightingManager.Instance.GetDefinition("C#"); var block = DocumentPrinter.ConvertTextDocumentToBlock(document, highlightingDefinition); block.FontFamily = GetCodeFont(); if (!keepLargeMargin) block.Margin = new Thickness(0, 6, 0, 6); AddBlock(block); }
SearchedFile SearchForIssues(FileName fileName, ITextSource fileContent, IEnumerable<IssueManager.IssueProvider> providers, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var context = SDRefactoringContext.Create(fileName, fileContent, TextLocation.Empty, cancellationToken); ReadOnlyDocument document = null; IHighlighter highlighter = null; var results = new List<SearchResultMatch>(); foreach (var provider in providers) { cancellationToken.ThrowIfCancellationRequested(); foreach (var issue in provider.GetIssues(context)) { if (document == null) { document = new ReadOnlyDocument(fileContent, fileName); highlighter = SD.EditorControlService.CreateHighlighter(document); highlighter.BeginHighlighting(); } results.Add(SearchResultMatch.Create(document, issue.Start, issue.End, highlighter)); } } if (highlighter != null) { highlighter.Dispose(); } if (results.Count > 0) return new SearchedFile(fileName, results); else return null; }