static void CreateNewFile(MDRefactoringContext context, TypeDeclaration type, string correctFileName) { var content = context.Document.Editor.Text; var types = new List <EntityDeclaration> (context.Unit.GetTypes().Where(t => t.StartLocation != type.StartLocation)); types.Sort((x, y) => y.StartLocation.CompareTo(x.StartLocation)); foreach (var removeType in types) { var start = context.GetOffset(removeType.StartLocation); var end = context.GetOffset(removeType.EndLocation); content = content.Remove(start, end - start); } if (context.Document.Project is MonoDevelop.Projects.DotNetProject) { string header = StandardHeaderService.GetHeader(context.Document.Project, correctFileName, true); if (!string.IsNullOrEmpty(header)) { content = header + context.Document.Editor.EolMarker + StripHeader(content); } } content = StripDoubleBlankLines(content); File.WriteAllText(correctFileName, content); context.Document.Project.AddFile(correctFileName); MonoDevelop.Ide.IdeApp.ProjectOperations.Save(context.Document.Project); }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { IResolver resolver = options.GetResolver(); List <Change> result = new List <Change> (); INRefactoryASTProvider provider = options.GetASTProvider(); if (resolver == null || provider == null) { return(result); } TypeDeclaration newType = new TypeDeclaration(ICSharpCode.NRefactory.Ast.Modifiers.None, null); newType.Name = createExpression.CreateType.Type; newType.Type = GetNewTypeType(); ConstructorDeclaration constructor = new ConstructorDeclaration(newType.Name, ICSharpCode.NRefactory.Ast.Modifiers.Public, null, null); constructor.Body = new BlockStatement(); int i = 0; foreach (Expression expression in createExpression.Parameters) { i++; string output = provider.OutputNode(options.Dom, expression); string parameterName; if (Char.IsLetter(output[0]) || output[0] == '_') { parameterName = output; } else { parameterName = "par" + i; } ResolveResult resolveResult2 = resolver.Resolve(new ExpressionResult(output), options.ResolveResult.ResolvedExpression.Region.Start); TypeReference typeReference = new TypeReference(resolveResult2.ResolvedType.ToInvariantString()); typeReference.IsKeyword = true; ParameterDeclarationExpression pde = new ParameterDeclarationExpression(typeReference, parameterName); constructor.Parameters.Add(pde); } ICSharpCode.NRefactory.Ast.INode node = newType; IType curType = options.Document.CompilationUnit.GetTypeAt(options.Document.Editor.Caret.Line, options.Document.Editor.Caret.Column); if (curType != null && !string.IsNullOrEmpty(curType.Namespace)) { NamespaceDeclaration namespaceDeclaration = new NamespaceDeclaration(curType.Namespace); namespaceDeclaration.Children.Add(newType); node = namespaceDeclaration; } newType.Children.Add(constructor); string fileName = GetName(Path.Combine(Path.GetDirectoryName(options.Document.FileName), newType.Name + Path.GetExtension(options.Document.FileName))); string header = options.Dom.Project is DotNetProject?StandardHeaderService.GetHeader(options.Dom.Project, fileName, true) + Environment.NewLine : ""; CreateFileChange createFile = new CreateFileChange(fileName, header + provider.OutputNode(options.Dom, node)); result.Add(createFile); result.Add(new OpenFileChange(fileName)); return(result); }
// Returns a stream with the content of the file. // project and language parameters are optional public virtual Stream CreateFileContent(SolutionItem policyParent, Project project, string language, string fileName, string identifier) { Dictionary <string, string> tags = new Dictionary <string, string> (); ModifyTags(policyParent, project, language, identifier, fileName, ref tags); string content = CreateContent(project, tags, language); content = StringParserService.Parse(content, tags); string mime = DesktopService.GetMimeTypeForUri(fileName); CodeFormatter formatter = !string.IsNullOrEmpty(mime) ? CodeFormatterService.GetFormatter(mime) : null; if (formatter != null) { var formatted = formatter.FormatText(policyParent != null ? policyParent.Policies : null, content); if (formatted != null) { content = formatted; } } MemoryStream ms = new MemoryStream(); byte[] data; if (AddStandardHeader) { string header = StandardHeaderService.GetHeader(policyParent, fileName, true); data = System.Text.Encoding.UTF8.GetBytes(header); ms.Write(data, 0, data.Length); } Mono.TextEditor.Document doc = new Mono.TextEditor.Document(); doc.Text = content; TextStylePolicy textPolicy = policyParent != null?policyParent.Policies.Get <TextStylePolicy> ("text/plain") : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> ("text/plain"); string eolMarker = TextStylePolicy.GetEolMarker(textPolicy.EolMarker); byte[] eolMarkerBytes = System.Text.Encoding.UTF8.GetBytes(eolMarker); var tabToSpaces = textPolicy.TabsToSpaces? new string (' ', textPolicy.TabWidth) : null; foreach (Mono.TextEditor.LineSegment line in doc.Lines) { var lineText = doc.GetTextAt(line.Offset, line.EditableLength); if (tabToSpaces != null) { lineText = lineText.Replace("\t", tabToSpaces); } data = System.Text.Encoding.UTF8.GetBytes(lineText); ms.Write(data, 0, data.Length); ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length); } ms.Position = 0; return(ms); }
public override Stream CreateFileContent(SolutionFolderItem policyParent, Project project, string language, string fileName, string identifier) { if (Outer.FormatCode) { return(base.CreateFileContent(policyParent, project, language, fileName, identifier)); } var model = GetTagModel(policyParent, project, language, identifier, fileName); string text = CreateContent(project, model.OverrideTags, language); text = ProcessContent(text, model); var memoryStream = new MemoryStream(); byte[] preamble = Encoding.UTF8.GetPreamble(); memoryStream.Write(preamble, 0, preamble.Length); if (AddStandardHeader) { string header = StandardHeaderService.GetHeader(policyParent, fileName, true); byte[] bytes = Encoding.UTF8.GetBytes(header); memoryStream.Write(bytes, 0, bytes.Length); } var textDocument = TextEditorFactory.CreateNewDocument(); //var textDocument = new TextDocument (); textDocument.Text = text; var textStylePolicy = (policyParent == null) ? PolicyService.GetDefaultPolicy <TextStylePolicy> ("text/plain") : policyParent.Policies.Get <TextStylePolicy> ("text/plain"); string eolMarker = TextStylePolicy.GetEolMarker(textStylePolicy.EolMarker); byte[] eol = Encoding.UTF8.GetBytes(eolMarker); string indent = (!textStylePolicy.TabsToSpaces) ? null : new string (' ', textStylePolicy.TabWidth); foreach (var current in textDocument.GetLines()) { string line = textDocument.GetTextAt(current.Offset, current.Length); if (indent != null) { line = line.Replace(" ", indent); } byte[] bytes = Encoding.UTF8.GetBytes(line); memoryStream.Write(bytes, 0, bytes.Length); memoryStream.Write(eol, 0, eol.Length); } memoryStream.Position = 0; return(memoryStream); }
Document CreateNewFile(BaseTypeDeclarationSyntax type, string correctFileName) { var doc = IdeApp.Workbench.ActiveDocument; var content = doc.Editor.Text; var types = new List <BaseTypeDeclarationSyntax> ( root .DescendantNodesAndSelf(n => !(n is BaseTypeDeclarationSyntax)) .OfType <BaseTypeDeclarationSyntax> () .Where(t => t.SpanStart != type.SpanStart) ); types.Sort((x, y) => y.SpanStart.CompareTo(x.SpanStart)); foreach (var removeType in types) { var bounds = CalcTypeBounds(removeType); content = content.Remove(bounds.Offset, bounds.Length); } if (doc.HasProject) { string header = StandardHeaderService.GetHeader(doc.Project, correctFileName, true); if (!string.IsNullOrEmpty(header)) { content = header + doc.Editor.GetEolMarker() + StripHeader(content); } } content = StripDoubleBlankLines(content); File.WriteAllText(correctFileName, content); if (doc.HasProject) { var prj = DetermineRealProject(doc); prj.AddFile(correctFileName); IdeApp.ProjectOperations.SaveAsync(prj); } doc.Editor.RemoveText(CalcTypeBounds(type)); return(document); }
// Returns a stream with the content of the file. // project and language parameters are optional public virtual Stream CreateFileContent(SolutionFolderItem policyParent, Project project, string language, string fileName, string identifier) { var model = CombinedTagModel.GetTagModel(ProjectTagModel, policyParent, project, language, identifier, fileName); //HACK: for API compat, CreateContent just gets the override, not the base model // but ProcessContent gets the entire model string content = CreateContent(project, model.OverrideTags, language); content = ProcessContent(content, model); string mime = DesktopService.GetMimeTypeForUri(fileName); var formatter = !string.IsNullOrEmpty(mime) ? CodeFormatterService.GetFormatter(mime) : null; if (formatter != null) { var formatted = formatter.FormatText(policyParent != null ? policyParent.Policies : null, content); if (formatted != null) { content = formatted; } } var ms = new MemoryStream(); var bom = Encoding.UTF8.GetPreamble(); ms.Write(bom, 0, bom.Length); byte[] data; if (AddStandardHeader) { string header = StandardHeaderService.GetHeader(policyParent, fileName, true); data = System.Text.Encoding.UTF8.GetBytes(header); ms.Write(data, 0, data.Length); } var doc = TextEditorFactory.CreateNewDocument(); doc.Text = content; TextStylePolicy textPolicy = policyParent != null?policyParent.Policies.Get <TextStylePolicy> ("text/plain") : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> ("text/plain"); string eolMarker = TextStylePolicy.GetEolMarker(textPolicy.EolMarker); byte[] eolMarkerBytes = System.Text.Encoding.UTF8.GetBytes(eolMarker); var tabToSpaces = textPolicy.TabsToSpaces? new string (' ', textPolicy.TabWidth) : null; foreach (var line in doc.GetLines()) { var lineText = doc.GetTextAt(line.Offset, line.Length); if (tabToSpaces != null) { lineText = lineText.Replace("\t", tabToSpaces); } data = System.Text.Encoding.UTF8.GetBytes(lineText); ms.Write(data, 0, data.Length); ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length); } ms.Position = 0; return(ms); }
public override List <Change> PerformChanges(RefactoringOptions options, object properties) { List <Change> result = new List <Change> (); IType type = options.SelectedItem as IType; if (type == null) { return(result); } string newName = GetCorrectFileName(type); if (type.CompilationUnit.Types.Count == 1) { result.Add(new RenameFileChange(type.CompilationUnit.FileName, newName)); } else { StringBuilder content = new StringBuilder(); if (options.Dom.Project is DotNetProject) { content.Append(StandardHeaderService.GetHeader(options.Dom.Project, newName, true) + Environment.NewLine); } INRefactoryASTProvider provider = options.GetASTProvider(); Mono.TextEditor.TextEditorData data = options.GetTextEditorData(); ICSharpCode.NRefactory.Ast.CompilationUnit unit = provider.ParseFile(options.Document.Editor.Text); TypeFilterTransformer typeFilterTransformer = new TypeFilterTransformer((type is InstantiatedType) ? ((InstantiatedType)type).UninstantiatedType.DecoratedFullName : type.DecoratedFullName); unit.AcceptVisitor(typeFilterTransformer, null); if (typeFilterTransformer.TypeDeclaration == null) { return(result); } Mono.TextEditor.Document generatedDocument = new Mono.TextEditor.Document(); generatedDocument.Text = provider.OutputNode(options.Dom, unit); int startLine = 0; int minLine = typeFilterTransformer.TypeDeclaration.StartLocation.Line; foreach (var attr in typeFilterTransformer.TypeDeclaration.Attributes) { minLine = Math.Min(minLine, attr.StartLocation.Line); } for (int i = minLine - 1; i >= 1; i--) { string lineText = data.Document.GetTextAt(data.Document.GetLine(i)).Trim(); if (string.IsNullOrEmpty(lineText)) { continue; } if (lineText.StartsWith("///")) { startLine = i; } else { break; } } int start; if (startLine >= 1) { start = data.Document.GetLine(startLine).Offset; } else { var startLocation = typeFilterTransformer.TypeDeclaration.StartLocation; startLocation.Column = 1; foreach (var attr in typeFilterTransformer.TypeDeclaration.Attributes) { if (attr.StartLocation < startLocation) { startLocation = attr.StartLocation; } } start = data.Document.LocationToOffset(startLocation.Line, 1); } int length = data.Document.LocationToOffset(typeFilterTransformer.TypeDeclaration.EndLocation.Line, typeFilterTransformer.TypeDeclaration.EndLocation.Column) - start; ICSharpCode.NRefactory.Ast.CompilationUnit generatedCompilationUnit = provider.ParseFile(generatedDocument.Text); TypeSearchVisitor typeSearchVisitor = new TypeSearchVisitor(); generatedCompilationUnit.AcceptVisitor(typeSearchVisitor, null); int genStart = generatedDocument.LocationToOffset(typeSearchVisitor.Types[0].StartLocation.Line, 0); foreach (var attr in typeSearchVisitor.Types[0].Attributes) { genStart = Math.Min(genStart, generatedDocument.LocationToOffset(attr.StartLocation.Line, 0)); } int genEnd = generatedDocument.LocationToOffset(typeSearchVisitor.Types[0].EndLocation.Line, typeSearchVisitor.Types[0].EndLocation.Column); ((Mono.TextEditor.IBuffer)generatedDocument).Replace(genStart, genEnd - genStart, data.Document.GetTextAt(start, length)); content.Append(generatedDocument.Text); result.Add(new CreateFileChange(newName, content.ToString())); TextReplaceChange removeDeclaration = new TextReplaceChange(); removeDeclaration.Description = "Remove type declaration"; removeDeclaration.FileName = type.CompilationUnit.FileName; removeDeclaration.Offset = start; removeDeclaration.RemovedChars = length; result.Add(removeDeclaration); } result.Add(new SaveProjectChange(options.Document.Project)); return(result); }
// Returns a stream with the content of the file. // project and language parameters are optional public virtual async Task <Stream> CreateFileContentAsync(SolutionFolderItem policyParent, Project project, string language, string fileName, string identifier) { var model = CombinedTagModel.GetTagModel(ProjectTagModel, policyParent, project, language, identifier, fileName); //HACK: for API compat, CreateContent just gets the override, not the base model // but ProcessContent gets the entire model string content = CreateContent(project, model.OverrideTags, language); content = ProcessContent(content, model); string mime = DesktopService.GetMimeTypeForUri(fileName); var formatter = !string.IsNullOrEmpty(mime) ? CodeFormatterService.GetFormatter(mime) : null; if (formatter != null) { var formatted = formatter.FormatText(policyParent != null ? policyParent.Policies : null, content); if (formatted != null) { content = formatted; } } var ms = new MemoryStream(); Encoding encoding = null; TextStylePolicy textPolicy = policyParent != null?policyParent.Policies.Get <TextStylePolicy> (mime ?? "text/plain") : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> (mime ?? "text/plain"); string eolMarker = TextStylePolicy.GetEolMarker(textPolicy.EolMarker); var ctx = await EditorConfigService.GetEditorConfigContext(fileName); if (ctx != null) { ctx.CurrentConventions.UniversalConventions.TryGetEncoding(out encoding); if (ctx.CurrentConventions.UniversalConventions.TryGetLineEnding(out string lineEnding)) { eolMarker = lineEnding; } } if (encoding == null) { encoding = System.Text.Encoding.UTF8; } var bom = encoding.GetPreamble(); if (bom != null && bom.Length > 0) { ms.Write(bom, 0, bom.Length); } byte[] data; if (AddStandardHeader) { string header = StandardHeaderService.GetHeader(policyParent, fileName, true); data = encoding.GetBytes(header); ms.Write(data, 0, data.Length); } var doc = TextEditorFactory.CreateNewDocument(); doc.Text = content; byte[] eolMarkerBytes = encoding.GetBytes(eolMarker); var tabToSpaces = textPolicy.TabsToSpaces? new string (' ', textPolicy.TabWidth) : null; IDocumentLine lastLine = null; foreach (var line in doc.GetLines()) { var lineText = doc.GetTextAt(line.Offset, line.Length); if (tabToSpaces != null) { lineText = lineText.Replace("\t", tabToSpaces); } if (line.LengthIncludingDelimiter > 0) { data = encoding.GetBytes(lineText); ms.Write(data, 0, data.Length); ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length); } lastLine = line; } if (ctx != null && lastLine != null && lastLine.Length > 0) { if (ctx.CurrentConventions.UniversalConventions.TryGetRequireFinalNewline(out bool requireNewLine)) { if (requireNewLine) { ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length); } } } ms.Position = 0; return(ms); }