public override bool IsValid (RefactoringOptions options) { MemberResolveResult resolveResult = options.ResolveResult as MemberResolveResult; if (resolveResult == null) return false; IProperty property = resolveResult.ResolvedMember as IProperty; if (property == null || resolveResult.CallingMember == null || resolveResult.CallingMember.FullName != property.FullName || !property.HasGet || property.DeclaringType == null) return false; TextEditorData data = options.GetTextEditorData (); if (property.HasGet && data.Document.GetCharAt (data.Document.LocationToOffset (property.GetRegion.End.Line, property.GetRegion.End.Column - 1)) == ';') return false; if (property.HasSet && data.Document.GetCharAt (data.Document.LocationToOffset (property.SetRegion.End.Line, property.SetRegion.End.Column - 1)) == ';') return false; INRefactoryASTProvider astProvider = options.GetASTProvider (); string backingStoreName = RetrieveBackingStore (options, astProvider, property); if (string.IsNullOrEmpty (backingStoreName)) return false; // look if there is a valid backing store field that doesn't have any attributes. int backinStoreStart; int backinStoreEnd; IField backingStore = GetBackingStoreField (options, backingStoreName, out backinStoreStart, out backinStoreEnd); if (backingStore == null || backingStore.Attributes.Any ()) return false; return true; }
public override void Run (RefactoringOptions options) { base.Run (options); TextEditorData data = options.GetTextEditorData (); Mono.TextEditor.TextEditor editor = data.Parent; List<TextLink> links = new List<TextLink> (); TextLink link = new TextLink ("name"); int referenceCount = 1; MemberResolveResult resolveResult = options.ResolveResult as MemberResolveResult; IProperty property = resolveResult.ResolvedMember as IProperty; if (property.HasGet) referenceCount++; if (property.HasSet) referenceCount++; for (int i = refactoringStartOffset; i < data.Document.Length - backingStoreName.Length; i++) { if (data.Document.GetTextAt (i, backingStoreName.Length) == backingStoreName) { link.AddLink (new Segment (i - refactoringStartOffset, backingStoreName.Length)); if (link.Count == referenceCount) break; } } links.Add (link); TextLinkEditMode tle = new TextLinkEditMode (editor, refactoringStartOffset, links); tle.SetCaretPosition = false; if (tle.ShouldStartTextLinkMode) { tle.OldMode = data.CurrentMode; tle.StartMode (); data.CurrentMode = tle; } }
internal static bool InternalIsValid (RefactoringOptions options, out IType interfaceType) { var unit = options.Document.ParsedDocument.GetAst<CompilationUnit> (); interfaceType = null; if (unit == null) return false; var loc = options.Document.Editor.Caret.Location; var declaration = unit.GetNodeAt<TypeDeclaration> (loc.Line, loc.Column); if (declaration == null) return false; if (!declaration.BaseTypes.Any (bt => bt.Contains (loc.Line, loc.Column))) return false; if (options.ResolveResult == null) return false; interfaceType = options.ResolveResult.Type; var def = interfaceType.GetDefinition (); if (def == null) return false; if (def.Kind != TypeKind.Interface) return false; var declaringType = options.Document.ParsedDocument.GetInnermostTypeDefinition (loc); var type = declaringType.Resolve (options.Document.ParsedDocument.ParsedFile.GetTypeResolveContext (options.Document.Compilation, loc)).GetDefinition (); return interfaceType.GetAllBaseTypes ().Any (bt => CodeGenerator.CollectMembersToImplement (type, bt, false).Any ()); }
public override bool IsValid (RefactoringOptions options) { TextEditorData data = options.GetTextEditorData (); LineSegment line = data.Document.GetLine (data.Caret.Line); if (!data.IsSomethingSelected && line != null) { var stack = line.StartSpan.Clone (); Mono.TextEditor.Highlighting.SyntaxModeService.ScanSpans (data.Document, data.Document.SyntaxMode, data.Document.SyntaxMode, stack, line.Offset, data.Caret.Offset); foreach (Span span in stack) { if (span.Color == "string.single" || span.Color == "string.double") return options.Document.CompilationUnit.GetMemberAt (data.Caret.Line, data.Caret.Column) != null; } } INRefactoryASTProvider provider = options.GetASTProvider (); if (provider == null) return false; string expressionText = null; if (options.ResolveResult != null && options.ResolveResult.ResolvedExpression != null) expressionText = options.ResolveResult.ResolvedExpression.Expression; if (string.IsNullOrEmpty (expressionText)) { int start, end; expressionText = SearchNumber (data, out start, out end); } Expression expression = provider.ParseExpression (expressionText); return expression is PrimitiveExpression; }
public override bool IsValid (RefactoringOptions options) { IResolver resolver = options.GetResolver (); INRefactoryASTProvider provider = options.GetASTProvider (); if (resolver == null || provider == null) return false; TextEditorData data = options.GetTextEditorData (); if (data == null) return false; ResolveResult resolveResult; if (data.IsSomethingSelected) { ExpressionResult expressionResult = new ExpressionResult (data.SelectedText.Trim ()); if (expressionResult.Expression.Contains (" ") || expressionResult.Expression.Contains ("\t")) expressionResult.Expression = "(" + expressionResult.Expression + ")"; resolveResult = resolver.Resolve (expressionResult, new DomLocation (data.Caret.Line, data.Caret.Column)); if (resolveResult == null) return false; return true; } LineSegment lineSegment = data.Document.GetLine (data.Caret.Line); string line = data.Document.GetTextAt (lineSegment); Expression expression = provider.ParseExpression (line); BlockStatement block = provider.ParseText (line) as BlockStatement; if (expression == null || (block != null && block.Children[0] is LocalVariableDeclaration)) return false; resolveResult = resolver.Resolve (new ExpressionResult (line), new DomLocation (options.Document.Editor.Caret.Line, options.Document.Editor.Caret.Column)); return resolveResult.ResolvedType != null && !string.IsNullOrEmpty (resolveResult.ResolvedType.FullName) && resolveResult.ResolvedType.FullName != DomReturnType.Void.FullName; }
public override string GetMenuDescription (RefactoringOptions options) { IType type = options.SelectedItem as IType; if (type.CompilationUnit.Types.Count == 1) return String.Format (GettextCatalog.GetString ("_Rename file to '{0}'"), Path.GetFileName (GetCorrectFileName (type))); return String.Format (GettextCatalog.GetString ("_Move type to file '{0}'"), Path.GetFileName (GetCorrectFileName (type))); }
public override void Run (RefactoringOptions options) { DocumentLocation location = options.GetTextEditorData ().Caret.Location; IType interfaceType = options.Dom.GetType (options.ResolveResult.ResolvedType); IType declaringType = options.Document.CompilationUnit.GetTypeAt (location.Line, location.Column); var editor = options.GetTextEditorData ().Parent; InsertionCursorEditMode mode = new InsertionCursorEditMode (editor, HelperMethods.GetInsertionPoints (editor.Document, declaringType)); ModeHelpWindow helpWindow = new ModeHelpWindow (); helpWindow.TransientFor = IdeApp.Workbench.RootWindow; helpWindow.TitleText = GettextCatalog.GetString ("<b>Implement Interface -- Targeting</b>"); helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Key</b>"), GettextCatalog.GetString ("<b>Behavior</b>"))); helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Up</b>"), GettextCatalog.GetString ("Move to <b>previous</b> target point."))); helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Down</b>"), GettextCatalog.GetString ("Move to <b>next</b> target point."))); helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Enter</b>"), GettextCatalog.GetString ("<b>Declare interface implementation</b> at target point."))); helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Esc</b>"), GettextCatalog.GetString ("<b>Cancel</b> this refactoring."))); mode.HelpWindow = helpWindow; mode.CurIndex = mode.InsertionPoints.Count - 1; mode.StartMode (); mode.Exited += delegate(object s, InsertionCursorEventArgs args) { if (args.Success) { CodeGenerator generator = options.Document.CreateCodeGenerator (); args.InsertionPoint.Insert (editor, generator.CreateInterfaceImplementation (declaringType, interfaceType, false)); } }; }
public static void Rename (IEntity entity, string newName) { if (newName == null) { var options = new RefactoringOptions () { SelectedItem = entity }; new RenameRefactoring ().Run (options); return; } using (var monitor = new NullProgressMonitor ()) { var col = ReferenceFinder.FindReferences (entity, true, monitor); List<Change> result = new List<Change> (); foreach (var memberRef in col) { var change = new TextReplaceChange (); change.FileName = memberRef.FileName; change.Offset = memberRef.Offset; change.RemovedChars = memberRef.Length; change.InsertedText = newName; change.Description = string.Format (GettextCatalog.GetString ("Replace '{0}' with '{1}'"), memberRef.GetName (), newName); result.Add (change); } if (result.Count > 0) { RefactoringService.AcceptChanges (monitor, result); } } }
public void RenameCommand_Update(CommandInfo ci) { var doc = IdeApp.Workbench.ActiveDocument; if (doc == null) return; var editor = doc.GetContent<ITextBuffer>(); if (editor == null) return; var dom = doc.Dom; ResolveResult result; INode item; CurrentRefactoryOperationsHandler.GetItem(dom, doc, editor, out result, out item); var options = new RefactoringOptions() { Document = doc, Dom = dom, ResolveResult = result, SelectedItem = item is InstantiatedType ? ((InstantiatedType)item).UninstantiatedType : item }; // If not a valid operation, allow command to be handled by others if (!new RenameRefactoring().IsValid(options)) ci.Bypass = true; }
public override bool IsValid (RefactoringOptions options) { INRefactoryASTProvider provider = options.GetASTProvider (); IResolver resolver = options.GetResolver (); if (provider == null || resolver == null) return false; if (invoke == null) invoke = GetInvocationExpression (options); if (invoke == null) return false; returnType = DomReturnType.Void; modifiers = ICSharpCode.NRefactory.Ast.Modifiers.None; resolvePosition = new DomLocation (options.Document.Editor.Caret.Line + 1, options.Document.Editor.Caret.Column + 1); ResolveResult resolveResult = resolver.Resolve (new ExpressionResult (provider.OutputNode (options.Dom, invoke)), resolvePosition); if (resolveResult is MethodResolveResult) { MethodResolveResult mrr = (MethodResolveResult)resolveResult ; if (mrr.ExactMethodMatch) return false; returnType = mrr.MostLikelyMethod.ReturnType; modifiers = (ICSharpCode.NRefactory.Ast.Modifiers)mrr.MostLikelyMethod.Modifiers; } if (invoke.TargetObject is MemberReferenceExpression) { string callingObject = provider.OutputNode (options.Dom, ((MemberReferenceExpression)invoke.TargetObject).TargetObject); resolveResult = resolver.Resolve (new ExpressionResult (callingObject), resolvePosition); if (resolveResult == null || resolveResult.ResolvedType == null || resolveResult.CallingType == null) return false; IType type = options.Dom.GetType (resolveResult.ResolvedType); return type != null && type.CompilationUnit != null && File.Exists (type.CompilationUnit.FileName) && RefactoringService.GetASTProvider (DesktopService.GetMimeTypeForUri (type.CompilationUnit.FileName)) != null; } return invoke.TargetObject is IdentifierExpression; }
internal static void InternalRun (RefactoringOptions options, bool implementExplicit) { IType interfaceType; if (!InternalIsValid (options, out interfaceType)) return; var loc = options.Document.Editor.Caret.Location; var declaringType = options.Document.ParsedDocument.GetInnermostTypeDefinition (loc); if (declaringType == null) return; var editor = options.GetTextEditorData ().Parent; var mode = new InsertionCursorEditMode (editor, CodeGenerationService.GetInsertionPoints (options.Document, declaringType)); var helpWindow = new InsertionCursorLayoutModeHelpWindow (); helpWindow.TransientFor = IdeApp.Workbench.RootWindow; helpWindow.TitleText = GettextCatalog.GetString ("Implement Interface"); mode.HelpWindow = helpWindow; mode.CurIndex = mode.InsertionPoints.Count - 1; mode.StartMode (); mode.Exited += delegate(object s, InsertionCursorEventArgs args) { if (args.Success) { var generator = options.CreateCodeGenerator (); if (generator == null) return; var type = declaringType.Resolve (options.Document.ParsedDocument.GetTypeResolveContext (options.Document.Compilation, loc)).GetDefinition (); args.InsertionPoint.Insert (options.GetTextEditorData (), generator.CreateInterfaceImplementation (type, declaringType, interfaceType, implementExplicit)); } }; }
public override bool IsValid (RefactoringOptions options) { IType type = options.SelectedItem as IType; string fileName = GetCorrectFileName (type); if (type == null || string.IsNullOrEmpty (fileName) || File.Exists (fileName) || type.DeclaringType != null) return false; return Path.GetFileNameWithoutExtension (type.CompilationUnit.FileName) != type.Name; }
public override bool IsValid (RefactoringOptions options) { if (options.ResolveResult == null || options.ResolveResult.ResolvedExpression == null) return false; if (options.Dom.GetType (options.ResolveResult.ResolvedType) != null) return false; createExpression = GetCreateExpression (options); return createExpression != null; }
public override bool IsValid (RefactoringOptions options) { if (options.ResolveResult == null) return false; IType type = options.Dom.GetType (options.ResolveResult.ResolvedType); if (type == null || type.ClassType != MonoDevelop.Projects.Dom.ClassType.Class) return false; return CurrentRefactoryOperationsHandler.ContainsAbstractMembers (type); }
public override void Run (RefactoringOptions options) { if (options.SelectedItem is LocalVariable || options.SelectedItem is IParameter) { var col = ReferenceFinder.FindReferences (options.SelectedItem); if (col == null) return; TextEditorData data = options.GetTextEditorData (); Mono.TextEditor.TextEditor editor = data.Parent; if (editor == null) { MessageService.ShowCustomDialog (new RenameItemDialog (options, this)); return; } List<TextLink> links = new List<TextLink> (); TextLink link = new TextLink ("name"); int baseOffset = Int32.MaxValue; foreach (MemberReference r in col) { baseOffset = Math.Min (baseOffset, data.Document.LocationToOffset (r.Line, r.Column)); } foreach (MemberReference r in col) { Segment segment = new Segment (data.Document.LocationToOffset (r.Line, r.Column) - baseOffset, r.Name.Length); if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset) { link.Links.Insert (0, segment); } else { link.AddLink (segment); } } links.Add (link); if (editor.CurrentMode is TextLinkEditMode) ((TextLinkEditMode)editor.CurrentMode).ExitTextLinkMode (); TextLinkEditMode tle = new TextLinkEditMode (editor, baseOffset, links); tle.SetCaretPosition = false; tle.SelectPrimaryLink = true; if (tle.ShouldStartTextLinkMode) { ModeHelpWindow helpWindow = new ModeHelpWindow (); helpWindow.TransientFor = IdeApp.Workbench.RootWindow; helpWindow.TitleText = options.SelectedItem is LocalVariable ? GettextCatalog.GetString ("<b>Local Variable -- Renaming</b>") : GettextCatalog.GetString ("<b>Parameter -- Renaming</b>"); helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Key</b>"), GettextCatalog.GetString ("<b>Behavior</b>"))); helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Return</b>"), GettextCatalog.GetString ("<b>Accept</b> this refactoring."))); helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Esc</b>"), GettextCatalog.GetString ("<b>Cancel</b> this refactoring."))); tle.HelpWindow = helpWindow; tle.Cancel += delegate { if (tle.HasChangedText) editor.Document.Undo (); }; tle.OldMode = data.CurrentMode; tle.StartMode (); data.CurrentMode = tle; } } else { MessageService.ShowCustomDialog (new RenameItemDialog (options, this)); } }
public override void Run (RefactoringOptions options) { DocumentLocation location = options.GetTextEditorData ().Caret.Location; IType interfaceType = options.Dom.GetType (options.ResolveResult.ResolvedType); IType declaringType = options.Document.CompilationUnit.GetTypeAt (location.Line, location.Column); options.Document.Editor.Document.BeginAtomicUndo (); var missingAbstractMembers = interfaceType.Members.Where (member => member.IsAbstract && !declaringType.Members.Any (m => member.Name == m.Name)); CodeGenerationService.AddNewMembers (declaringType, missingAbstractMembers, "implemented abstract members of " + interfaceType.FullName); options.Document.Editor.Document.EndAtomicUndo (); }
public override bool IsValid (RefactoringOptions options) { if (!(options.SelectedItem is LocalVariable)) { // Console.WriteLine ("!!! Item is not LocalVariable"); return false; } ICSharpCode.NRefactory.Ast.INode result = GetMemberBodyNode (options); if (result == null) return false; return true; }
public override void Run (RefactoringOptions options) { ExtractMethodParameters param = CreateParameters (options); if (param == null) return; if (Analyze (options, param, false) == null || param.VariablesToGenerate == null) { MessageService.ShowError (GettextCatalog.GetString ("Invalid selection for method extraction.")); return; } MessageService.ShowCustomDialog (new ExtractMethodDialog (options, this, param)); }
public override bool IsValid (RefactoringOptions options) { if (options.ResolveResult == null) return false; IType type = options.Dom.GetType (options.ResolveResult.ResolvedType); if (type == null || type.ClassType != MonoDevelop.Projects.Dom.ClassType.Interface) return false; DocumentLocation location = options.GetTextEditorData ().Caret.Location; IType declaringType = options.Document.CompilationUnit.GetTypeAt (location.Line + 1, location.Column + 1); return declaringType != null && options.ResolveResult.ResolvedExpression.IsInInheritableTypeContext; }
public override bool IsValid (RefactoringOptions options) { if (options.SelectedItem is IVariable || options.SelectedItem is IParameter) return true; if (options.SelectedItem is ITypeDefinition) return !string.IsNullOrEmpty (((ITypeDefinition)options.SelectedItem).Region.FileName); if (options.SelectedItem is IMember) { var cls = ((IMember)options.SelectedItem).DeclaringTypeDefinition; return cls != null; } return false; }
public override bool IsValid (RefactoringOptions options) { if (options.SelectedItem is LocalVariable || options.SelectedItem is IParameter) return true; if (options.SelectedItem is IType) return ((IType)options.SelectedItem).SourceProject != null; if (options.SelectedItem is IMember) { IType cls = ((IMember)options.SelectedItem).DeclaringType; return cls != null && cls.SourceProject != null; } return false; }
public override bool IsValid (RefactoringOptions options) { // if (options.SelectedItem != null) // return false; var buffer = options.Document.Editor; if (buffer.IsSomethingSelected) { ParsedDocument doc = options.ParseDocument (); if (doc != null && doc.CompilationUnit != null) { if (doc.CompilationUnit.GetMemberAt (buffer.Caret.Line, buffer.Caret.Column) == null) return false; return true; } } return false; }
public override bool IsValid (RefactoringOptions options) { if (options.ResolveResult == null) return false; IType type = options.Dom.GetType (options.ResolveResult.ResolvedType); if (type == null || type.ClassType != MonoDevelop.Projects.Dom.ClassType.Class) return false; if (!CurrentRefactoryOperationsHandler.ContainsAbstractMembers (type)) return false; DocumentLocation location = options.GetTextEditorData ().Caret.Location; IType declaringType = options.Document.CompilationUnit.GetTypeAt (location.Line, location.Column); var missingAbstractMembers = type.Members.Where (member => member.IsAbstract && !member.IsSpecialName && !declaringType.Members.Any (m => member.Name == m.Name)); return missingAbstractMembers.Any (); }
public override void Run (RefactoringOptions options) { DocumentLocation location = options.GetTextEditorData ().Caret.Location; IType interfaceType = options.Dom.GetType (options.ResolveResult.ResolvedType); IType declaringType = options.Document.CompilationUnit.GetTypeAt (location.Line + 1, location.Column + 1); options.Document.TextEditor.BeginAtomicUndo (); CodeRefactorer refactorer = IdeApp.Workspace.GetCodeRefactorer (IdeApp.ProjectOperations.CurrentSelectedSolution); refactorer.ImplementInterface (options.Document.CompilationUnit, declaringType, interfaceType, true, interfaceType, options.ResolveResult.ResolvedType); options.Document.TextEditor.EndAtomicUndo (); }
public override bool IsValid (RefactoringOptions options) { MemberResolveResult resolveResult = options.ResolveResult as MemberResolveResult; if (resolveResult == null) return false; IProperty property = resolveResult.ResolvedMember as IProperty; if (property == null || resolveResult.CallingMember == null || resolveResult.CallingMember.FullName != property.FullName || !property.HasGet || property.DeclaringType == null) return false; TextEditorData data = options.GetTextEditorData (); if (property.HasGet && data.Document.GetCharAt (data.Document.LocationToOffset (property.GetRegion.End.Line - 1, property.GetRegion.End.Column - 2)) != ';') return false; if (property.HasSet && data.Document.GetCharAt (data.Document.LocationToOffset (property.SetRegion.End.Line - 1, property.SetRegion.End.Column - 2)) != ';') return false; return true; }
public override bool IsValid (RefactoringOptions options) { // if (options.SelectedItem != null) // return false; var buffer = options.Document.TextEditor; if (buffer.SelectionStartPosition - buffer.SelectionEndPosition != 0) { ParsedDocument doc = options.ParseDocument (); if (doc != null && doc.CompilationUnit != null) { int line, column; buffer.GetLineColumnFromPosition (buffer.CursorPosition, out line, out column); if (doc.CompilationUnit.GetMemberAt (line, column) == null) return false; return true; } } return false; }
public override List<Change> PerformChanges (RefactoringOptions options, object properties) { List<Change> result = new List<Change> (); ICompilationUnit compilationUnit = options.ParseDocument ().CompilationUnit; Mono.TextEditor.TextEditorData textEditorData = options.GetTextEditorData (); int minOffset = int.MaxValue; foreach (IUsing u in compilationUnit.Usings) { if (u.IsFromNamespace) continue; int offset = textEditorData.Document.LocationToOffset (u.Region.Start.Line, u.Region.Start.Column); TextReplaceChange change = new TextReplaceChange () { FileName = options.Document.FileName, Offset = offset, RemovedChars = textEditorData.Document.LocationToOffset (u.Region.End.Line, u.Region.End.Column) - offset }; Mono.TextEditor.LineSegment line = textEditorData.Document.GetLineByOffset (change.Offset); if (line != null && line.EditableLength == change.RemovedChars) change.RemovedChars += line.DelimiterLength; result.Add (change); minOffset = Math.Min (minOffset, offset); } StringBuilder output = new StringBuilder (); List<IUsing> usings = new List<IUsing> (compilationUnit.Usings); usings.Sort (UsingComparer); INRefactoryASTProvider astProvider = options.GetASTProvider (); foreach (IUsing u in usings) { AstNode declaration; if (u.IsFromNamespace) continue; if (u.Aliases.Any ()) { KeyValuePair<string, IReturnType> alias = u.Aliases.First (); declaration = new UsingAliasDeclaration (alias.Key, alias.Value.ConvertToTypeReference ()); } else { declaration = new UsingDeclaration (u.Namespaces.First ()); } output.Append (astProvider.OutputNode (options.Dom, declaration)); } TextReplaceChange insertSortedUsings = new TextReplaceChange () { FileName = options.Document.FileName, Offset = minOffset, InsertedText = output.ToString () }; result.Add (insertSortedUsings); return result; }
public override void Run (RefactoringOptions options) { DocumentLocation location = options.GetTextEditorData ().Caret.Location; IType interfaceType = options.Dom.GetType (options.ResolveResult.ResolvedType); IType declaringType = options.Document.CompilationUnit.GetTypeAt (location.Line + 1, location.Column + 1); options.Document.TextEditor.BeginAtomicUndo (); CodeRefactorer refactorer = IdeApp.Workspace.GetCodeRefactorer (IdeApp.ProjectOperations.CurrentSelectedSolution); List<KeyValuePair<IMember,IReturnType>> members = new List<KeyValuePair<IMember, IReturnType>> (); foreach (IMember member in interfaceType.Members) { if (member.IsAbstract && !declaringType.Members.Any (m => member.Name == m.Name)) { members.Add (new KeyValuePair<IMember,IReturnType> (member, null)); } } refactorer.ImplementMembers (declaringType, members, "implemented abstract members of " + interfaceType.FullName); options.Document.TextEditor.EndAtomicUndo (); }
public override bool IsValid (RefactoringOptions options) { TextEditorData data = options.GetTextEditorData (); LineSegment line = data.Document.GetLine (data.Caret.Line); if (data.IsSomethingSelected && line != null) { Stack<Span> stack = line.StartSpan != null ? new Stack<Span> (line.StartSpan) : new Stack<Span> (); Mono.TextEditor.Highlighting.SyntaxModeService.ScanSpans (data.Document, data.Document.SyntaxMode, data.Document.SyntaxMode, stack, line.Offset, data.Caret.Offset); foreach (Span span in stack) { if (span.Color == "string.double") { int start, end; string str = MonoDevelop.Refactoring.IntroduceConstant.IntroduceConstantRefactoring.SearchString (data, '"', out start, out end); end = System.Math.Min (end, line.Offset + line.EditableLength); return str.StartsWith ("\"") && str.EndsWith ("\"") && data.SelectionRange.Offset < end; } } } return false; }
public override List<Change> PerformChanges (RefactoringOptions options, object properties) { ICSharpCode.NRefactory.Ast.INode memberNode = GetMemberBodyNode (options); List<Change> changes = new List<Change> (); if (memberNode == null) return null; try { // Console.WriteLine ("AcceptVisitor"); // Console.WriteLine ("Start: " + memberNode.StartLocation.ToString () + " - End: " + memberNode.EndLocation.ToString ()); memberNode.AcceptVisitor (new IntegrateTemporaryVariableVisitor (), new IntegrateTemporaryVariableVisitorOptions (changes, options)); // Console.WriteLine ("AcceptVisitor done"); } catch (IntegrateTemporaryVariableException e) { // Console.WriteLine ("Exception catched"); MessageService.ShowError ("Could not perform integration : ", e.Message); return new List<Change>(); } // Console.WriteLine ("Changes calculated"); return changes; }
public ExtractMethodDialog(RefactoringOptions options, ExtractMethodRefactoring extractMethod, ExtractMethodRefactoring.ExtractMethodParameters properties) { this.Build(); this.options = options; this.properties = properties; this.extractMethod = extractMethod; store = new ListStore(typeof(string), typeof(string)); treeviewParameters.Model = store; treeviewParameters.AppendColumn("Type", new CellRendererText(), "text", 0); treeviewParameters.AppendColumn("Name", new CellRendererText(), "text", 1); FillStore(); buttonPreview.Sensitive = buttonOk.Sensitive = false; entry.Changed += delegate { buttonPreview.Sensitive = buttonOk.Sensitive = ValidateName(); }; ValidateName(); buttonOk.Clicked += OnOKClicked; buttonCancel.Clicked += OnCancelClicked; buttonPreview.Clicked += OnPreviewClicked; buttonUp.Clicked += delegate { List <int> indices = new List <int> (); foreach (TreePath path in treeviewParameters.Selection.GetSelectedRows()) { int index = Int32.Parse(path.ToString()); if (index > 0) { VariableDescriptor tmp = properties.Parameters [index - 1]; properties.Parameters [index - 1] = properties.Parameters [index]; properties.Parameters [index] = tmp; indices.Add(index - 1); } } FillStore(); treeviewParameters.Selection.SelectPath(new TreePath(indices.ToArray())); }; buttonDown.Clicked += delegate { List <int> indices = new List <int> (); foreach (TreePath path in treeviewParameters.Selection.GetSelectedRows()) { int index = Int32.Parse(path.ToString()); if (index + 1 < properties.Parameters.Count) { VariableDescriptor tmp = properties.Parameters [index + 1]; properties.Parameters [index + 1] = properties.Parameters [index]; properties.Parameters [index] = tmp; indices.Add(index + 1); } } FillStore(); treeviewParameters.Selection.SelectPath(new TreePath(indices.ToArray())); }; ListStore modifiers = new ListStore(typeof(string)); modifiers.AppendValues(""); modifiers.AppendValues("public"); modifiers.AppendValues("private"); modifiers.AppendValues("protected"); modifiers.AppendValues("internal"); comboboxModifiers.Model = modifiers; comboboxModifiers.Active = PropertyService.Get <int> ("MonoDevelop.Refactoring.ExtractMethod.ExtractMethodDialog.DefaultModifier"); entry.Activated += delegate { if (buttonOk.Sensitive) { buttonOk.Click(); } }; }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { varCount = 0; selectionStart = selectionEnd = -1; List <Change> result = new List <Change> (); IResolver resolver = options.GetResolver(); INRefactoryASTProvider provider = options.GetASTProvider(); TextEditorData data = options.GetTextEditorData(); if (resolver == null || provider == null || data == null) { return(result); } DocumentLocation endPoint; if (data.IsSomethingSelected) { endPoint = data.MainSelection.Anchor < data.MainSelection.Lead ? data.MainSelection.Lead : data.MainSelection.Anchor; } else { endPoint = data.Caret.Location; } ResolveResult resolveResult; LineSegment lineSegment; var unit = provider.ParseFile(data.Document.Text); if (unit == null) { LoggingService.LogError("Declare local error: parese file == null"); return(result); } var visitor = new VariableLookupVisitor(resolver, new DomLocation(endPoint.Line, endPoint.Column)); if (options.ResolveResult == null) { LoggingService.LogError("Declare local error: resolve result == null"); return(result); } IMember callingMember = options.ResolveResult.CallingMember; if (callingMember != null) { visitor.MemberLocation = new AstLocation(callingMember.Location.Column, callingMember.Location.Line); } unit.AcceptVisitor(visitor, null); ExpressionResult expressionResult = new ExpressionResult(data.SelectedText.Trim()); if (expressionResult.Expression.Contains(" ") || expressionResult.Expression.Contains("\t")) { expressionResult.Expression = "(" + expressionResult.Expression + ")"; } resolveResult = resolver.Resolve(expressionResult, new DomLocation(endPoint.Line, endPoint.Column)); if (resolveResult == null) { return(result); } IReturnType resolvedType = GetResolvedType(options, resolveResult); AstType returnType; if (resolveResult.ResolvedType == null || string.IsNullOrEmpty(resolveResult.ResolvedType.Name)) { returnType = new SimpleType("var"); } else { returnType = options.ShortenTypeName(resolvedType).ConvertToTypeReference(); } varName = CreateVariableName(resolvedType, visitor); options.ParseMember(resolveResult.CallingMember); // insert local variable declaration TextReplaceChange insert = new TextReplaceChange(); insert.FileName = options.Document.FileName; insert.Description = GettextCatalog.GetString("Insert variable declaration"); var varDecl = new VariableDeclarationStatement(returnType, varName, provider.ParseExpression(data.SelectedText)); var node = unit.GetNodeAt(endPoint.Line, endPoint.Column); var containing = node.Parent; while (!(containing.Parent is BlockStatement)) { containing = containing.Parent; } if (containing is BlockStatement) { lineSegment = data.Document.GetLine(data.Caret.Line); } else { lineSegment = data.Document.GetLine(containing.StartLocation.Line); } insert.Offset = lineSegment.Offset; insert.InsertedText = options.GetWhitespaces(lineSegment.Offset) + provider.OutputNode(options.Dom, varDecl); var insertOffset = insert.Offset + options.GetWhitespaces(lineSegment.Offset).Length + provider.OutputNode(options.Dom, varDecl.Type).Length + " ".Length; offsets.Add(insertOffset); result.Add(insert); varCount++; // replace main selection TextReplaceChange replace = new TextReplaceChange(); replace.FileName = options.Document.FileName; replace.Offset = data.SelectionRange.Offset; replace.RemovedChars = data.SelectionRange.Length; replace.InsertedText = varName; result.Add(replace); int delta = insert.InsertedText.Length - insert.RemovedChars; offsets.Add(replace.Offset + delta); Console.WriteLine(replace.Offset); delta += varName.Length - replace.RemovedChars; varCount++; selectionStart = insert.Offset; if (replaceAll) { matches.Sort((x, y) => x.StartLocation.CompareTo(y.StartLocation)); foreach (var match in matches) { replace = new TextReplaceChange(); replace.FileName = options.Document.FileName; int start = data.LocationToOffset(match.StartLocation.Line, match.StartLocation.Column); int end = data.LocationToOffset(match.EndLocation.Line, match.EndLocation.Column); replace.Offset = start; replace.RemovedChars = end - start; replace.InsertedText = varName; result.Add(replace); offsets.Add(start + delta); delta += varName.Length - replace.RemovedChars; } } return(result); }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { RenameProperties properties = (RenameProperties)prop; List <Change> result = new List <Change> (); MemberReferenceCollection col = GetReferences(options); if (col == null) { return(result); } if (properties.RenameFile && options.SelectedItem is IType) { IType cls = (IType)options.SelectedItem; int currentPart = 1; HashSet <string> alreadyRenamed = new HashSet <string> (); foreach (IType part in cls.Parts) { if (part.CompilationUnit.FileName != options.Document.FileName && System.IO.Path.GetFileNameWithoutExtension(part.CompilationUnit.FileName) != System.IO.Path.GetFileNameWithoutExtension(options.Document.FileName)) { continue; } if (alreadyRenamed.Contains(part.CompilationUnit.FileName)) { continue; } alreadyRenamed.Add(part.CompilationUnit.FileName); string oldFileName = System.IO.Path.GetFileNameWithoutExtension(part.CompilationUnit.FileName); string newFileName; int idx = oldFileName.IndexOf(cls.Name); if (idx >= 0) { newFileName = oldFileName.Substring(0, idx) + properties.NewName + oldFileName.Substring(idx + cls.Name.Length); } else { newFileName = currentPart != 1 ? properties.NewName + currentPart : properties.NewName; currentPart++; } int t = 0; while (System.IO.File.Exists(GetFullFileName(newFileName, part.CompilationUnit.FileName, t))) { t++; } result.Add(new RenameFileChange(part.CompilationUnit.FileName, GetFullFileName(newFileName, part.CompilationUnit.FileName, t))); } } foreach (MemberReference memberRef in col) { TextReplaceChange change = new TextReplaceChange(); change.FileName = memberRef.FileName; change.Offset = memberRef.Position; change.RemovedChars = memberRef.Name.Length; change.InsertedText = properties.NewName; change.Description = string.Format(GettextCatalog.GetString("Replace '{0}' with '{1}'"), memberRef.Name, properties.NewName); result.Add(change); } return(result); }
public override void Run(RefactoringOptions options) { if (options.SelectedItem is LocalVariable || options.SelectedItem is IParameter) { MemberReferenceCollection col = GetReferences(options); if (col == null) { return; } TextEditorData data = options.GetTextEditorData(); Mono.TextEditor.TextEditor editor = data.Parent; if (editor == null) { MessageService.ShowCustomDialog(new RenameItemDialog(options, this)); return; } List <TextLink> links = new List <TextLink> (); TextLink link = new TextLink("name"); int baseOffset = Int32.MaxValue; foreach (MemberReference r in col) { baseOffset = Math.Min(baseOffset, data.Document.LocationToOffset(r.Line - 1, r.Column - 1)); } foreach (MemberReference r in col) { Segment segment = new Segment(data.Document.LocationToOffset(r.Line - 1, r.Column - 1) - baseOffset, r.Name.Length); if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset) { link.Links.Insert(0, segment); } else { link.AddLink(segment); } } links.Add(link); TextLinkEditMode tle = new TextLinkEditMode(editor, baseOffset, links); tle.SetCaretPosition = false; tle.SelectPrimaryLink = true; if (tle.ShouldStartTextLinkMode) { ModeHelpWindow helpWindow = new ModeHelpWindow(); helpWindow.TransientFor = IdeApp.Workbench.RootWindow; helpWindow.TitleText = options.SelectedItem is LocalVariable?GettextCatalog.GetString("<b>Local Variable -- Renaming</b>") : GettextCatalog.GetString("<b>Parameter -- Renaming</b>"); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Key</b>"), GettextCatalog.GetString("<b>Behavior</b>"))); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Return</b>"), GettextCatalog.GetString("<b>Accept</b> this refactoring."))); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Esc</b>"), GettextCatalog.GetString("<b>Cancel</b> this refactoring."))); tle.HelpWindow = helpWindow; tle.Cancel += delegate { editor.Document.Undo(); }; tle.OldMode = data.CurrentMode; tle.StartMode(); data.CurrentMode = tle; } } else { MessageService.ShowCustomDialog(new RenameItemDialog(options, this)); } }
public override string GetMenuDescription(RefactoringOptions options) { return(IdeApp.CommandService.GetCommandInfo(MonoDevelop.Ide.Commands.EditCommands.Rename).Text); }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { varCount = 0; selectionStart = selectionEnd = -1; List <Change> result = new List <Change> (); IResolver resolver = options.GetResolver(); INRefactoryASTProvider provider = options.GetASTProvider(); if (resolver == null || provider == null) { return(result); } TextEditorData data = options.GetTextEditorData(); if (data == null) { return(result); } DocumentLocation endPoint; if (data.IsSomethingSelected) { endPoint = data.MainSelection.Anchor < data.MainSelection.Lead ? data.MainSelection.Lead : data.MainSelection.Anchor; } else { endPoint = data.Caret.Location; } ResolveResult resolveResult; LineSegment lineSegment; ICSharpCode.NRefactory.Ast.CompilationUnit unit = provider.ParseFile(data.Document.Text); var visitor = new VariableLookupVisitor(resolver, new DomLocation(endPoint.Line, endPoint.Column)); if (options.ResolveResult == null) { LoggingService.LogError("Declare local error: resolve result == null"); return(result); } IMember callingMember = options.ResolveResult.CallingMember; if (callingMember != null) { visitor.MemberLocation = new Location(callingMember.Location.Column, callingMember.Location.Line); } unit.AcceptVisitor(visitor, null); if (data.IsSomethingSelected) { ExpressionResult expressionResult = new ExpressionResult(data.SelectedText.Trim()); if (expressionResult.Expression.Contains(" ") || expressionResult.Expression.Contains("\t")) { expressionResult.Expression = "(" + expressionResult.Expression + ")"; } resolveResult = resolver.Resolve(expressionResult, new DomLocation(endPoint.Line, endPoint.Column)); if (resolveResult == null) { return(result); } IReturnType resolvedType = resolveResult.ResolvedType; if (resolvedType == null || string.IsNullOrEmpty(resolvedType.Name)) { resolvedType = DomReturnType.Object; } varName = CreateVariableName(resolvedType, visitor); TypeReference returnType; if (resolveResult.ResolvedType == null || string.IsNullOrEmpty(resolveResult.ResolvedType.Name)) { returnType = new TypeReference("var"); returnType.IsKeyword = true; } else { returnType = options.ShortenTypeName(resolveResult.ResolvedType).ConvertToTypeReference(); } options.ParseMember(resolveResult.CallingMember); TextReplaceChange insert = new TextReplaceChange(); insert.FileName = options.Document.FileName; insert.Description = GettextCatalog.GetString("Insert variable declaration"); LocalVariableDeclaration varDecl = new LocalVariableDeclaration(returnType); varDecl.Variables.Add(new VariableDeclaration(varName, provider.ParseExpression(data.SelectedText))); GetContainingEmbeddedStatementVisitor blockVisitor = new GetContainingEmbeddedStatementVisitor(); blockVisitor.LookupLocation = new Location(endPoint.Column, endPoint.Line); unit.AcceptVisitor(blockVisitor, null); StatementWithEmbeddedStatement containing = blockVisitor.ContainingStatement as StatementWithEmbeddedStatement; if (containing != null && !(containing.EmbeddedStatement is BlockStatement)) { insert.Offset = data.Document.LocationToOffset(containing.StartLocation.Line, containing.StartLocation.Column); lineSegment = data.Document.GetLineByOffset(insert.Offset); insert.RemovedChars = data.Document.LocationToOffset(containing.EndLocation.Line, containing.EndLocation.Column) - insert.Offset; BlockStatement insertedBlock = new BlockStatement(); insertedBlock.AddChild(varDecl); insertedBlock.AddChild(containing.EmbeddedStatement); containing.EmbeddedStatement = insertedBlock; insert.InsertedText = provider.OutputNode(options.Dom, containing, options.GetWhitespaces(lineSegment.Offset)).TrimStart(); int offset, length; if (SearchSubExpression(insert.InsertedText, data.SelectedText, 0, out offset, out length)) { if (SearchSubExpression(insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) { insert.InsertedText = insert.InsertedText.Substring(0, offset) + varName + insert.InsertedText.Substring(offset + length); insertOffset = insert.Offset + offset; } } } else if (blockVisitor.ContainingStatement is IfElseStatement) { IfElseStatement ifElse = blockVisitor.ContainingStatement as IfElseStatement; insert.Offset = data.Document.LocationToOffset(blockVisitor.ContainingStatement.StartLocation.Line, blockVisitor.ContainingStatement.StartLocation.Column); lineSegment = data.Document.GetLineByOffset(insert.Offset); insert.RemovedChars = data.Document.LocationToOffset(blockVisitor.ContainingStatement.EndLocation.Line, blockVisitor.ContainingStatement.EndLocation.Column) - insert.Offset; BlockStatement insertedBlock = new BlockStatement(); insertedBlock.AddChild(varDecl); if (blockVisitor.ContainsLocation(ifElse.TrueStatement [0])) { insertedBlock.AddChild(ifElse.TrueStatement [0]); ifElse.TrueStatement [0] = insertedBlock; } else { insertedBlock.AddChild(ifElse.FalseStatement [0]); ifElse.FalseStatement [0] = insertedBlock; } insert.InsertedText = provider.OutputNode(options.Dom, blockVisitor.ContainingStatement, options.GetWhitespaces(lineSegment.Offset)); int offset, length; if (SearchSubExpression(insert.InsertedText, provider.OutputNode(options.Dom, insertedBlock), 0, out offset, out length)) { if (SearchSubExpression(insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) { if (SearchSubExpression(insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) { insert.InsertedText = insert.InsertedText.Substring(0, offset) + varName + insert.InsertedText.Substring(offset + length); insertOffset = insert.Offset + offset; } } } } else { lineSegment = data.Document.GetLine(data.Caret.Line); insert.Offset = lineSegment.Offset; insert.InsertedText = options.GetWhitespaces(lineSegment.Offset) + provider.OutputNode(options.Dom, varDecl) + data.EolMarker; insertOffset = insert.Offset + options.GetWhitespaces(lineSegment.Offset).Length + provider.OutputNode(options.Dom, varDecl.TypeReference).Length + " ".Length; TextReplaceChange replace = new TextReplaceChange(); replace.FileName = options.Document.FileName; replace.Offset = data.SelectionRange.Offset; replace.RemovedChars = data.SelectionRange.Length; replace.InsertedText = varName; result.Add(replace); replaceOffset = replace.Offset; if (insert.Offset < replaceOffset) { replaceOffset += insert.InsertedText.Length - insert.RemovedChars; } varCount++; } result.Add(insert); varCount++; selectionStart = insert.Offset; return(result); } lineSegment = data.Document.GetLine(data.Caret.Line); string line = data.Document.GetTextAt(lineSegment); Expression expression = provider.ParseExpression(line); if (expression == null) { return(result); } resolveResult = resolver.Resolve(new ExpressionResult(line), new DomLocation(options.Document.Editor.Caret.Line, options.Document.Editor.Caret.Column)); if (resolveResult.ResolvedType != null && !string.IsNullOrEmpty(resolveResult.ResolvedType.FullName)) { TextReplaceChange insert = new TextReplaceChange(); insert.FileName = options.Document.FileName; insert.Description = GettextCatalog.GetString("Insert variable declaration"); insert.Offset = lineSegment.Offset + options.GetWhitespaces(lineSegment.Offset).Length; varName = CreateVariableName(resolveResult.ResolvedType, visitor); LocalVariableDeclaration varDecl = new LocalVariableDeclaration(options.ShortenTypeName(resolveResult.ResolvedType).ConvertToTypeReference()); varDecl.Variables.Add(new VariableDeclaration(varName, expression)); insert.RemovedChars = expression.EndLocation.Column - 1; insert.InsertedText = provider.OutputNode(options.Dom, varDecl); insertOffset = insert.Offset + provider.OutputNode(options.Dom, varDecl.TypeReference).Length + " ".Length; result.Add(insert); varCount++; int idx = 0; while (idx < insert.InsertedText.Length - varName.Length) { if (insert.InsertedText.Substring(idx, varName.Length) == varName && (idx == 0 || insert.InsertedText [idx - 1] == ' ') && (idx == insert.InsertedText.Length - varName.Length - 1 || insert.InsertedText [idx + varName.Length] == ' ')) { selectionStart = insert.Offset + idx; selectionEnd = selectionStart + varName.Length; break; } idx++; } } return(result); }
public override void Run(RefactoringOptions options) { MessageService.ShowCustomDialog(new IntroduceConstantDialog(this, options, new Parameters())); }
public override string GetMenuDescription(RefactoringOptions options) { return(GettextCatalog.GetString("_Implement abstract members")); }
public override void Run(RefactoringOptions options) { if (options.SelectedItem is IVariable) { var field = options.SelectedItem as IField; if (field != null && field.Accessibility != Accessibility.Private) { MessageService.ShowCustomDialog(new RenameItemDialog(options, this)); return; } var col = ReferenceFinder.FindReferences(options.SelectedItem, true); if (col == null) { return; } var data = options.Document != null?options.GetTextEditorData() : IdeApp.Workbench.ActiveDocument.Editor; var editor = data.Parent; if (editor == null) { MessageService.ShowCustomDialog(new RenameItemDialog(options, this)); return; } var links = new List <TextLink> (); var link = new TextLink("name"); int baseOffset = Int32.MaxValue; foreach (var r in col) { baseOffset = Math.Min(baseOffset, r.Offset); } foreach (MemberReference r in col) { var segment = new TextSegment(r.Offset - baseOffset, r.Length); if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset) { link.Links.Insert(0, segment); } else { link.AddLink(segment); } } links.Add(link); if (editor.CurrentMode is TextLinkEditMode) { ((TextLinkEditMode)editor.CurrentMode).ExitTextLinkMode(); } TextLinkEditMode tle = new TextLinkEditMode(editor, baseOffset, links); tle.SetCaretPosition = false; tle.SelectPrimaryLink = true; if (tle.ShouldStartTextLinkMode) { var helpWindow = new TableLayoutModeHelpWindow(); helpWindow.TransientFor = IdeApp.Workbench.RootWindow; helpWindow.TitleText = options.SelectedItem is IVariable?GettextCatalog.GetString("<b>Local Variable -- Renaming</b>") : GettextCatalog.GetString("<b>Parameter -- Renaming</b>"); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Key</b>"), GettextCatalog.GetString("<b>Behavior</b>"))); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Return</b>"), GettextCatalog.GetString("<b>Accept</b> this refactoring."))); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Esc</b>"), GettextCatalog.GetString("<b>Cancel</b> this refactoring."))); tle.HelpWindow = helpWindow; tle.Cancel += delegate { if (tle.HasChangedText) { editor.Document.Undo(); } }; tle.OldMode = data.CurrentMode; tle.StartMode(); data.CurrentMode = tle; } } else { MessageService.ShowCustomDialog(new RenameItemDialog(options, this)); } }
public override bool IsValid(RefactoringOptions options) { return(true); }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { #region Init var renameProperties = prop as RenameProperties; if (renameProperties == null) { return(null); } var changes = new List <Change>(); var doc = options.Document; if (doc == null) { return(null); } var ast = doc.GetDAst(); if (ast == null) { return(null); } var n = options.SelectedItem as INode; if (n == null) { return(null); } var project = doc.HasProject ? doc.Project as AbstractDProject : null; var parseCache = DResolverWrapper.CreateParseCacheView(project); var modules = new List <DModule>(); if (project == null) { modules.Add(ast); } else { foreach (var p in project.GetSourcePaths()) { modules.AddRange(GlobalParseCache.EnumModulesRecursively(p)); } } var ctxt = ResolutionContext.Create(parseCache, null, null); #endregion // Enumerate references foreach (var mod in modules) { if (mod == null) { continue; } var references = D_Parser.Refactoring.ReferencesFinder.SearchModuleForASTNodeReferences(mod, n, ctxt).ToList(); if (((DModule)n.NodeRoot).FileName == mod.FileName) { references.Insert(0, new IdentifierDeclaration(n.NameHash) { Location = n.NameLocation }); } if (references.Count < 1) { continue; } var txt = TextFileProvider.Instance.GetEditableTextFile(new FilePath(mod.FileName)); var prevReplacement = CodeLocation.Empty; foreach (ISyntaxRegion reference in references) { if (prevReplacement == reference.Location) { continue; } prevReplacement = reference.Location; changes.Add(new TextReplaceChange { FileName = mod.FileName, InsertedText = renameProperties.NewName, RemovedChars = n.Name.Length, Description = string.Format(GettextCatalog.GetString("Replace '{0}' with '{1}'"), n.Name, renameProperties.NewName), Offset = txt.GetPositionFromLineColumn(reference.Location.Line, reference.Location.Column) }); } } return(changes); }
public override void Run(RefactoringOptions options) { if (options.SelectedItem is IVariable) { var field = options.SelectedItem as IField; if (field != null && (field.Accessibility != Accessibility.Private || field.DeclaringTypeDefinition != null && field.DeclaringTypeDefinition.Parts.Count > 1)) { using (var dlg = new RenameItemDialog(options, this)) MessageService.ShowCustomDialog(dlg); return; } var par = options.SelectedItem as IParameter; if (par != null && par.Owner != null && (par.Owner.Accessibility != Accessibility.Private || par.Owner.DeclaringTypeDefinition != null && par.Owner.DeclaringTypeDefinition.Parts.Count > 1)) { using (var dlg = new RenameItemDialog(options, this)) MessageService.ShowCustomDialog(dlg); return; } var col = ReferenceFinder.FindReferences(options.SelectedItem, true); if (col == null) { return; } var data = options.Document != null?options.GetTextEditorData() : IdeApp.Workbench.ActiveDocument.Editor; var editor = data.Parent; if (editor == null) { using (var dlg = new RenameItemDialog(options, this)) MessageService.ShowCustomDialog(dlg); return; } var links = new List <TextLink> (); var link = new TextLink("name"); int baseOffset = Int32.MaxValue; foreach (var r in col) { baseOffset = Math.Min(baseOffset, r.Offset); } foreach (MemberReference r in col) { var segment = new TextSegment(r.Offset - baseOffset, r.Length); if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset) { link.Links.Insert(0, segment); } else { link.AddLink(segment); } } links.Add(link); if (editor.CurrentMode is TextLinkEditMode) { ((TextLinkEditMode)editor.CurrentMode).ExitTextLinkMode(); } TextLinkEditMode tle = new TextLinkEditMode(editor, baseOffset, links); tle.SetCaretPosition = false; tle.SelectPrimaryLink = true; if (tle.ShouldStartTextLinkMode) { tle.Cancel += delegate { if (tle.HasChangedText) { editor.Document.Undo(); } }; tle.OldMode = data.CurrentMode; tle.StartMode(); data.CurrentMode = tle; } } else { using (var dlg = new RenameItemDialog(options, this)) MessageService.ShowCustomDialog(dlg); } }
public FileProvider(RefactoringOptions options) { this.options = options; }
public RenameItemDialog(RefactoringOptions options, RenameRefactoring rename) { this.options = options; this.rename = rename; if (options.SelectedItem is IMethod && ((IMethod)options.SelectedItem).IsConstructor) { options.SelectedItem = ((IMethod)options.SelectedItem).DeclaringType; } this.Build(); if (options.SelectedItem is IType) { var t = (IType)options.SelectedItem; if (t.Kind == TypeKind.TypeParameter) { this.Title = GettextCatalog.GetString("Rename Type Parameter"); entry.Text = t.Name; } else { var typeDefinition = (t).GetDefinition(); if (typeDefinition.DeclaringType == null) { // not supported for inner types this.renameFileFlag.Visible = true; this.renameFileFlag.Active = true; // if more than one type is in the file, only rename the file as defilt if the file name contains the type name // see Bug 603938 - Renaming a Class in a file with multiple classes renames the file if (options.Document != null && options.Document.ParsedDocument.TopLevelTypeDefinitions.Count > 1) { this.renameFileFlag.Active = options.Document.FileName.FileNameWithoutExtension.Contains(typeDefinition.Name); } } else { this.renameFileFlag.Active = false; } if (typeDefinition.Kind == TypeKind.Interface) { this.Title = GettextCatalog.GetString("Rename Interface"); } else { this.Title = GettextCatalog.GetString("Rename Class"); } } // this.fileName = type.GetDefinition ().Region.FileName; } else if (options.SelectedItem is IField) { this.Title = GettextCatalog.GetString("Rename Field"); } else if (options.SelectedItem is IProperty) { if (((IProperty)options.SelectedItem).IsIndexer) { this.Title = GettextCatalog.GetString("Rename Indexer"); } else { this.Title = GettextCatalog.GetString("Rename Property"); } } else if (options.SelectedItem is IEvent) { this.Title = GettextCatalog.GetString("Rename Event"); } else if (options.SelectedItem is IMethod) { var m = (IMethod)options.SelectedItem; if (m.IsConstructor || m.IsDestructor) { this.Title = GettextCatalog.GetString("Rename Class"); } else { this.Title = GettextCatalog.GetString("Rename Method"); } } else if (options.SelectedItem is IParameter) { this.Title = GettextCatalog.GetString("Rename Parameter"); } else if (options.SelectedItem is IVariable) { this.Title = GettextCatalog.GetString("Rename Variable"); } else if (options.SelectedItem is ITypeParameter) { this.Title = GettextCatalog.GetString("Rename Type Parameter"); } else { this.Title = GettextCatalog.GetString("Rename Item"); } if (options.SelectedItem is IEntity) { var member = (IEntity)options.SelectedItem; if (member.EntityType == EntityType.Constructor || member.EntityType == EntityType.Destructor) { entry.Text = member.DeclaringType.Name; } else { entry.Text = member.Name; } // fileName = member.Region.FileName; } else if (options.SelectedItem is ITypeParameter) { var lvar = (ITypeParameter)options.SelectedItem; entry.Text = lvar.Name; // this.fileName = lvar.Region.FileName; } else if (options.SelectedItem is IVariable) { var lvar = (IVariable)options.SelectedItem; entry.Text = lvar.Name; // this.fileName = lvar.Region.FileName; } entry.SelectRegion(0, -1); buttonPreview.Sensitive = buttonOk.Sensitive = false; entry.Changed += OnEntryChanged; entry.Activated += OnEntryActivated; buttonOk.Clicked += OnOKClicked; buttonPreview.Clicked += OnPreviewClicked; entry.Changed += delegate { buttonPreview.Sensitive = buttonOk.Sensitive = ValidateName(); }; ValidateName(); }
public override List <Change> PerformChanges(RefactoringOptions options, object properties) { List <Change> result = new List <Change> (); ICompilationUnit compilationUnit = options.ParseDocument().CompilationUnit; Mono.TextEditor.TextEditorData textEditorData = options.GetTextEditorData(); int minOffset = int.MaxValue; foreach (IUsing u in compilationUnit.Usings) { if (u.IsFromNamespace) { continue; } int offset = textEditorData.Document.LocationToOffset(u.Region.Start.Line - 1, u.Region.Start.Column - 1); TextReplaceChange change = new TextReplaceChange() { FileName = options.Document.FileName, Offset = offset, RemovedChars = textEditorData.Document.LocationToOffset(u.Region.End.Line - 1, u.Region.End.Column - 1) - offset }; Mono.TextEditor.LineSegment line = textEditorData.Document.GetLineByOffset(change.Offset); if (line != null && line.EditableLength == change.RemovedChars) { change.RemovedChars += line.DelimiterLength; } result.Add(change); minOffset = Math.Min(minOffset, offset); } StringBuilder output = new StringBuilder(); List <IUsing> usings = new List <IUsing> (compilationUnit.Usings); usings.Sort(UsingComparer); INRefactoryASTProvider astProvider = options.GetASTProvider(); foreach (IUsing u in usings) { UsingDeclaration declaration; if (u.IsFromNamespace) { continue; } if (u.Aliases.Any()) { KeyValuePair <string, IReturnType> alias = u.Aliases.First(); declaration = new UsingDeclaration(alias.Key, alias.Value.ConvertToTypeReference()); } else { declaration = new UsingDeclaration(u.Namespaces.First()); } output.Append(astProvider.OutputNode(options.Dom, declaration)); } TextReplaceChange insertSortedUsings = new TextReplaceChange() { FileName = options.Document.FileName, Offset = minOffset, InsertedText = output.ToString() }; result.Add(insertSortedUsings); return(result); }
//so anonymous delegate can access base.Run verifiably void BaseRun(RefactoringOptions options) { base.Run(options); }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { List <Change> result = new List <Change> (); TextEditorData data = options.GetTextEditorData(); MemberResolveResult resolveResult = options.ResolveResult as MemberResolveResult; IProperty property = resolveResult.ResolvedMember as IProperty; INRefactoryASTProvider astProvider = options.GetASTProvider(); string backingStoreName = RetrieveBackingStore(options, astProvider, property); int backinStoreStart; int backinStoreEnd; IField backingStore = GetBackingStoreField(options, backingStoreName, out backinStoreStart, out backinStoreEnd); if (backingStore != null) { using (var monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, true)) { foreach (MemberReference memberRef in ReferenceFinder.FindReferences(backingStore, monitor)) { result.Add(new TextReplaceChange() { FileName = memberRef.FileName, Offset = memberRef.Position, RemovedChars = memberRef.Name.Length, InsertedText = property.Name }); } } result.RemoveAll(c => backinStoreStart <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset <= backinStoreEnd); result.Add(new TextReplaceChange() { FileName = options.Document.FileName, Offset = backinStoreStart, RemovedChars = backinStoreEnd - backinStoreStart }); } if (property.HasGet) { int startOffset = data.Document.LocationToOffset(property.GetRegion.Start.ToDocumentLocation(data.Document)); int endOffset = data.Document.LocationToOffset(property.GetRegion.End.ToDocumentLocation(data.Document)); string text = astProvider.OutputNode(options.Dom, new PropertyGetRegion(null, null), options.GetIndent(property) + "\t").Trim(); result.RemoveAll(c => startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset <= endOffset); result.Add(new TextReplaceChange() { FileName = options.Document.FileName, Offset = startOffset, RemovedChars = endOffset - startOffset, InsertedText = text }); } int setStartOffset; int setEndOffset; PropertySetRegion setRegion = new PropertySetRegion(null, null); string setText; if (property.HasSet) { setStartOffset = data.Document.LocationToOffset(property.SetRegion.Start.ToDocumentLocation(data.Document)); setEndOffset = data.Document.LocationToOffset(property.SetRegion.End.ToDocumentLocation(data.Document)); setText = astProvider.OutputNode(options.Dom, setRegion, options.GetIndent(property) + "\t").Trim(); } else { setEndOffset = setStartOffset = data.Document.LocationToOffset(property.GetRegion.End.ToDocumentLocation(data.Document)); setRegion.Modifier = ICSharpCode.NRefactory.Ast.Modifiers.Private; setText = Environment.NewLine + astProvider.OutputNode(options.Dom, setRegion, options.GetIndent(property) + "\t").TrimEnd(); } result.RemoveAll(c => setStartOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset <= setEndOffset); result.Add(new TextReplaceChange() { FileName = options.Document.FileName, Offset = setStartOffset, RemovedChars = setEndOffset - setStartOffset, InsertedText = setText }); return(result); }
public override void Run(RefactoringOptions options) { fileName = declaringType.CompilationUnit.FileName; var openDocument = IdeApp.Workbench.OpenDocument(fileName); if (openDocument == null) { MessageService.ShowError(string.Format(GettextCatalog.GetString("Can't open file {0}."), fileName)); return; } data = openDocument.Editor; if (data == null) { return; } openDocument.RunWhenLoaded(delegate { try { indent = data.Document.GetLine(declaringType.Location.Line).GetIndentation(data.Document) ?? ""; } catch (Exception) { indent = ""; } indent += "\t"; InsertionCursorEditMode mode = new InsertionCursorEditMode(data.Parent, CodeGenerationService.GetInsertionPoints(openDocument, declaringType)); if (fileName == options.Document.FileName) { for (int i = 0; i < mode.InsertionPoints.Count; i++) { var point = mode.InsertionPoints [i]; if (point.Location < data.Caret.Location) { mode.CurIndex = i; } else { break; } } } ModeHelpWindow helpWindow = new ModeHelpWindow(); helpWindow.TransientFor = IdeApp.Workbench.RootWindow; helpWindow.TitleText = GettextCatalog.GetString("<b>Create Method -- Targeting</b>"); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Key</b>"), GettextCatalog.GetString("<b>Behavior</b>"))); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Up</b>"), GettextCatalog.GetString("Move to <b>previous</b> target point."))); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Down</b>"), GettextCatalog.GetString("Move to <b>next</b> target point."))); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Enter</b>"), GettextCatalog.GetString("<b>Declare new method</b> at target point."))); helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Esc</b>"), GettextCatalog.GetString("<b>Cancel</b> this refactoring."))); mode.HelpWindow = helpWindow; mode.StartMode(); mode.Exited += delegate(object s, InsertionCursorEventArgs args) { if (args.Success) { SetInsertionPoint(args.InsertionPoint); BaseRun(options); if (string.IsNullOrEmpty(fileName)) { return; } data.ClearSelection(); data.Caret.Offset = selectionEnd; data.SetSelection(selectionStart, selectionEnd); } }; }); }
public override string GetMenuDescription(RefactoringOptions options) { return(GettextCatalog.GetString("_Declare Local")); }
public override string GetMenuDescription(RefactoringOptions options) { return(GettextCatalog.GetString("_Introduce Constant...")); }
public override string GetMenuDescription(RefactoringOptions options) { return(GettextCatalog.GetString("_Remove backing store")); }
public override string GetMenuDescription(RefactoringOptions options) { return(GettextCatalog.GetString("_Create Method")); }
public override void Run(RefactoringOptions options) { ImplementExplicit.InternalRun(options, false); }
internal static RefactoringOptions CreateRefactoringOptions(string text) { int cursorPosition = -1; int endPos = text.IndexOf('$'); if (endPos >= 0) { cursorPosition = endPos; text = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1); } int selectionStart = -1; int selectionEnd = -1; int idx = text.IndexOf("<-"); if (idx >= 0) { selectionStart = idx; text = text.Substring(0, idx) + text.Substring(idx + 2); selectionEnd = idx = text.IndexOf("->"); text = text.Substring(0, idx) + text.Substring(idx + 2); if (cursorPosition < 0) { cursorPosition = selectionEnd - 1; } } TestWorkbenchWindow tww = new TestWorkbenchWindow(); TestViewContent sev = new TestViewContent(); // return new RefactoringOptions (); DotNetProject project = new DotNetAssemblyProject("C#"); Solution solution = new Solution(); solution.RootFolder.Items.Add(project); project.FileName = GetTempFile(".csproj"); string file = GetTempFile(".cs"); project.AddFile(file); string parsedText = text; string editorText = text; ProjectDomService.Load(project); ProjectDom dom = ProjectDomService.GetProjectDom(project); dom.ForceUpdate(true); ProjectDomService.Parse(project, file, null, delegate { return(parsedText); }); ProjectDomService.Parse(project, file, null, delegate { return(parsedText); }); sev.Project = project; sev.ContentName = file; sev.Text = editorText; sev.CursorPosition = cursorPosition; tww.ViewContent = sev; var doc = new MonoDevelop.Ide.Gui.Document(tww); doc.ParsedDocument = new NRefactoryParser().Parse(null, sev.ContentName, parsedText); foreach (var e in doc.ParsedDocument.Errors) { Console.WriteLine(e); } if (cursorPosition >= 0) { doc.TextEditor.CursorPosition = cursorPosition; } if (selectionStart >= 0) { doc.TextEditor.Select(selectionStart, selectionEnd); } NRefactoryResolver resolver = new NRefactoryResolver(dom, doc.ParsedDocument.CompilationUnit, MonoDevelop.Ide.Gui.TextEditor.GetTextEditor(sev), file); ExpressionResult expressionResult; if (selectionStart >= 0) { expressionResult = new ExpressionResult(editorText.Substring(selectionStart, selectionEnd - selectionStart).Trim()); endPos = selectionEnd; } else { expressionResult = new NewCSharpExpressionFinder(dom).FindFullExpression(editorText, cursorPosition + 1); } ResolveResult resolveResult = endPos >= 0 ? resolver.Resolve(expressionResult, new DomLocation(doc.TextEditor.CursorLine, doc.TextEditor.CursorColumn)) : null; RefactoringOptions result = new RefactoringOptions { Document = doc, Dom = dom, ResolveResult = resolveResult, SelectedItem = null }; if (resolveResult is MemberResolveResult) { result.SelectedItem = ((MemberResolveResult)resolveResult).ResolvedMember; } if (resolveResult is LocalVariableResolveResult) { result.SelectedItem = ((LocalVariableResolveResult)resolveResult).LocalVariable; } if (resolveResult is ParameterResolveResult) { result.SelectedItem = ((ParameterResolveResult)resolveResult).Parameter; } result.TestFileProvider = new FileProvider(result); return(result); }
public override bool IsValid(RefactoringOptions options) { IType interfaceType; return(ImplementExplicit.InternalIsValid(options, out interfaceType)); }
internal static string GetOutput(RefactoringOptions options, List <Change> changes) { RefactoringService.AcceptChanges(null, options.Dom, changes, new FileProvider(options)); return(options.Document.TextEditor.Text); }
public override List <Change> PerformChanges(RefactoringOptions options, object properties) { List <Change> result = new List <Change> (); Parameters param = properties as Parameters; if (param == null) { return(result); } TextEditorData data = options.GetTextEditorData(); IResolver resolver = options.GetResolver(); IMember curMember = options.Document.CompilationUnit.GetMemberAt(data.Caret.Line, data.Caret.Column); ResolveResult resolveResult = options.ResolveResult; int start = 0; int end = 0; if (resolveResult == null) { LineSegment line = data.Document.GetLine(data.Caret.Line); if (line != null) { var stack = line.StartSpan.Clone(); Mono.TextEditor.Highlighting.SyntaxModeService.ScanSpans(data.Document, data.Document.SyntaxMode, data.Document.SyntaxMode, stack, line.Offset, data.Caret.Offset); foreach (Span span in stack) { if (span.Color == "string.single" || span.Color == "string.double") { resolveResult = resolver.Resolve(new ExpressionResult(SearchString(data, span.Color == "string.single" ? '\'' : '"', out start, out end)), DomLocation.Empty); end++; } } } if (end == 0) { resolveResult = resolver.Resolve(new ExpressionResult(SearchNumber(data, out start, out end)), DomLocation.Empty); } } else { start = data.Document.LocationToOffset(resolveResult.ResolvedExpression.Region.Start.Line, resolveResult.ResolvedExpression.Region.Start.Column); end = data.Document.LocationToOffset(resolveResult.ResolvedExpression.Region.End.Line, resolveResult.ResolvedExpression.Region.End.Column); } if (start == 0 && end == 0) { return(result); } INRefactoryASTProvider provider = options.GetASTProvider(); FieldDeclaration fieldDeclaration = new FieldDeclaration(null); VariableDeclaration varDecl = new VariableDeclaration(param.Name); varDecl.Initializer = provider.ParseExpression(resolveResult.ResolvedExpression.Expression); fieldDeclaration.Fields.Add(varDecl); fieldDeclaration.Modifier = param.Modifiers; fieldDeclaration.Modifier |= ICSharpCode.NRefactory.Ast.Modifiers.Const; fieldDeclaration.TypeReference = resolveResult.ResolvedType.ConvertToTypeReference(); fieldDeclaration.TypeReference.IsKeyword = true; TextReplaceChange insertConstant = new TextReplaceChange(); insertConstant.FileName = options.Document.FileName; insertConstant.Description = string.Format(GettextCatalog.GetString("Generate constant '{0}'"), param.Name); insertConstant.Offset = data.Document.LocationToOffset(curMember.Location.Line, 1); insertConstant.InsertedText = provider.OutputNode(options.Dom, fieldDeclaration, options.GetIndent(curMember)) + Environment.NewLine; result.Add(insertConstant); TextReplaceChange replaceConstant = new TextReplaceChange(); replaceConstant.FileName = options.Document.FileName; replaceConstant.Description = string.Format(GettextCatalog.GetString("Replace expression with constant '{0}'"), param.Name); replaceConstant.Offset = start; replaceConstant.RemovedChars = end - start; replaceConstant.InsertedText = param.Name; result.Add(replaceConstant); return(result); }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { RenameProperties properties = (RenameProperties)prop; List <Change> result = new List <Change> (); IEnumerable <MemberReference> col = null; using (var monitor = new MessageDialogProgressMonitor(true, false, false, true)) { col = ReferenceFinder.FindReferences(options.SelectedItem, true, monitor); if (col == null) { return(result); } if (properties.RenameFile && options.SelectedItem is IType) { var cls = ((IType)options.SelectedItem).GetDefinition(); int currentPart = 1; HashSet <string> alreadyRenamed = new HashSet <string> (); foreach (var part in cls.Parts) { if (alreadyRenamed.Contains(part.Region.FileName)) { continue; } alreadyRenamed.Add(part.Region.FileName); string oldFileName = System.IO.Path.GetFileNameWithoutExtension(part.Region.FileName); string newFileName; if (oldFileName.ToUpper() == properties.NewName.ToUpper() || oldFileName.ToUpper().EndsWith("." + properties.NewName.ToUpper())) { continue; } int idx = oldFileName.IndexOf(cls.Name); if (idx >= 0) { newFileName = oldFileName.Substring(0, idx) + properties.NewName + oldFileName.Substring(idx + cls.Name.Length); } else { newFileName = currentPart != 1 ? properties.NewName + currentPart : properties.NewName; currentPart++; } int t = 0; while (System.IO.File.Exists(GetFullFileName(newFileName, part.Region.FileName, t))) { t++; } result.Add(new RenameFileChange(part.Region.FileName, GetFullFileName(newFileName, part.Region.FileName, t))); } } foreach (var memberRef in col) { TextReplaceChange change = new TextReplaceChange(); change.FileName = memberRef.FileName; change.Offset = memberRef.Offset; change.RemovedChars = memberRef.Length; change.InsertedText = properties.NewName; change.Description = string.Format(GettextCatalog.GetString("Replace '{0}' with '{1}'"), memberRef.GetName(), properties.NewName); result.Add(change); } } return(result); }
public override void Run(RefactoringOptions options) { MessageService.ShowCustomDialog(new DRenameNameDialog(options, this)); }
public override string GetMenuDescription(RefactoringOptions options) { return(GettextCatalog.GetString("I_mplement explicit")); }