void FindReferences(object sender, EventArgs e) { MenuCommand item = (MenuCommand)sender; IMember member = (IMember)item.Tag; string memberName; if (member is IProperty && ((IProperty)member).IsIndexer) { // The name of the default indexer is always "Indexer" in C#. // Add the type name to clarify which indexer is referred to. memberName = member.Name + " of " + member.DeclaringType.Name; } else { memberName = member.Name; } using (AsynchronousWaitDialog monitor = AsynchronousWaitDialog.ShowWaitDialog("${res:SharpDevelop.Refactoring.FindReferences}")) { FindReferencesAndRenameHelper.ShowAsSearchResults(StringParser.Parse("${res:SharpDevelop.Refactoring.ReferencesTo}", new string[, ] { { "Name", memberName } }), RefactoringService.FindReferences(member, monitor)); } }
void nameCell_Edited(object o, EditedArgs args) { TreeIter iter; TreeStore.GetIter(out iter, new Gtk.TreePath(args.Path)); var n = TreeStore.GetValue(iter, 0) as INode; if (n != null && args.NewText != n.Name && DRenameRefactoring.CanRenameNode(n) && DRenameRefactoring.IsValidIdentifier(args.NewText)) { RefactoringService.AcceptChanges( IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor("Rename item", null), new DRenameRefactoring().PerformChanges( new RefactoringOptions(IdeApp.Workbench.ActiveDocument) { SelectedItem = n }, new MonoDevelop.Refactoring.Rename.RenameRefactoring.RenameProperties { NewName = args.NewText })); TreeView.Selection.SelectIter(iter); TreeView.GrabFocus(); } }
public static bool Rename(ISymbol symbol, string newName) { if (symbol == null) { throw new ArgumentNullException("symbol"); } if (newName == null) { throw new ArgumentNullException("newName"); } try { var result = new RenameRefactoring().PerformChanges(symbol, new RenameProperties() { NewName = newName }); using (var monitor = new ProgressMonitor()) { if (result.Count > 0) { RefactoringService.AcceptChanges(monitor, result); } } return(true); } catch (AggregateException ae) { foreach (var inner in ae.Flatten().InnerExceptions) { LoggingService.LogError("Exception while rename.", inner); } return(false); } catch (Exception e) { LoggingService.LogError("Exception while rename.", e); return(false); } }
public void FillInspectors(string filter) { categories.Clear(); treeStore.Clear(); foreach (var node in RefactoringService.GetInspectors(mimeType)) { if (!string.IsNullOrEmpty(filter) && node.Title.IndexOf(filter, StringComparison.OrdinalIgnoreCase) < 0) { continue; } Gtk.TreeIter iter; if (!categories.TryGetValue(node.Category, out iter)) { iter = treeStore.AppendValues("<b>" + node.Category + "</b>"); categories [node.Category] = iter; } var title = node.Title; if (!string.IsNullOrEmpty(filter)) { var idx = title.IndexOf(filter, StringComparison.OrdinalIgnoreCase); title = title.Substring(0, idx) + "<span bgcolor=\"yellow\">" + title.Substring(idx, filter.Length) + "</span>" + title.Substring(idx + filter.Length); } treeStore.AppendValues(iter, title, node.GetSeverity(), node); } treeviewInspections.ExpandAll(); }
void FindOverrides(object sender, EventArgs e) { MenuCommand item = (MenuCommand)sender; IMember member = (IMember)item.Tag; List <IClass> derivedClasses = RefactoringService.FindDerivedClasses(member.DeclaringType, ParserService.AllProjectContents, false); List <SearchResult> results = new List <SearchResult>(); foreach (IClass derivedClass in derivedClasses) { if (derivedClass.CompilationUnit == null) { continue; } if (derivedClass.CompilationUnit.FileName == null) { continue; } IMember m = RefactoringService.FindSimilarMember(derivedClass, member); if (m != null && !m.Region.IsEmpty) { SearchResult res = new SimpleSearchResult(m.FullyQualifiedName, new Point(m.Region.BeginColumn - 1, m.Region.BeginLine - 1)); res.ProvidedDocumentInformation = FindReferencesAndRenameHelper.GetDocumentInformation(derivedClass.CompilationUnit.FileName); results.Add(res); } } SearchInFilesManager.ShowSearchResults(StringParser.Parse("${res:SharpDevelop.Refactoring.OverridesOf}", new string[, ] { { "Name", member.Name } }), results); }
void FindDerivedClasses(object sender, EventArgs e) { MenuCommand item = (MenuCommand)sender; IClass c = (IClass)item.Tag; List <IClass> derivedClasses = RefactoringService.FindDerivedClasses(c, ParserService.AllProjectContents, false); List <SearchResult> results = new List <SearchResult>(); foreach (IClass derivedClass in derivedClasses) { if (derivedClass.CompilationUnit == null) { continue; } if (derivedClass.CompilationUnit.FileName == null) { continue; } SearchResult res = new SimpleSearchResult(derivedClass.FullyQualifiedName, new Point(derivedClass.Region.BeginColumn - 1, derivedClass.Region.BeginLine - 1)); res.ProvidedDocumentInformation = FindReferencesAndRenameHelper.GetDocumentInformation(derivedClass.CompilationUnit.FileName); results.Add(res); } SearchInFilesManager.ShowSearchResults(StringParser.Parse("${res:SharpDevelop.Refactoring.ClassesDerivingFrom}", new string[, ] { { "Name", c.Name } }), results); }
void FindOverrides(object sender, EventArgs e) { MenuCommand item = (MenuCommand)sender; IMember member = (IMember)item.Tag; IEnumerable <IClass> derivedClasses = RefactoringService.FindDerivedClasses(member.DeclaringType, ParserService.AllProjectContents, false); List <SearchResultMatch> results = new List <SearchResultMatch>(); IAmbience ambience = AmbienceService.GetCurrentAmbience(); ambience.ConversionFlags = ConversionFlags.UseFullyQualifiedMemberNames | ConversionFlags.ShowTypeParameterList; foreach (IClass derivedClass in derivedClasses) { if (derivedClass.CompilationUnit == null) { continue; } if (derivedClass.CompilationUnit.FileName == null) { continue; } IMember m = MemberLookupHelper.FindSimilarMember(derivedClass, member); if (m != null && !m.Region.IsEmpty) { string matchText = ambience.Convert(m); SearchResultMatch res = new SimpleSearchResultMatch(matchText, new TextLocation(m.Region.BeginColumn - 1, m.Region.BeginLine - 1)); res.ProvidedDocumentInformation = FindReferencesAndRenameHelper.GetDocumentInformation(m.DeclaringType.CompilationUnit.FileName); results.Add(res); } } SearchResultPanel.Instance.ShowSearchResults(new SearchResult( StringParser.Parse("${res:SharpDevelop.Refactoring.OverridesOf}", new string[, ] { { "Name", member.Name } }), results )); }
protected override void Initialize() { base.Initialize(); Nodes.Clear(); List <IProjectContent> contentList = new List <IProjectContent>(); if (ProjectService.OpenSolution != null) { foreach (IProject project in ProjectService.OpenSolution.Projects) { IProjectContent projectContent = ParserService.GetProjectContent(project); if (projectContent != null) { contentList.Add(projectContent); } } } foreach (IClass derivedClass in RefactoringService.FindDerivedClasses(c, contentList, true)) { new ClassNode(project, derivedClass).AddTo(this); } if (Nodes.Count == 0) { SetIcon(ClosedIcon); OpenedIcon = ClosedIcon = null; } }
public override void OnTheFlyFormat(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, TextEditorData data, int startOffset, int endOffset) { var parser = new MonoDevelop.CSharp.Parser.CSharpParser(); var compilationUnit = parser.Parse(data); bool hadErrors = parser.ErrorReportPrinter.ErrorsCount + parser.ErrorReportPrinter.FatalCounter > 0; var policy = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain); var domSpacingVisitor = new AstSpacingVisitor(policy, data) { AutoAcceptChanges = false, }; compilationUnit.AcceptVisitor(domSpacingVisitor, null); var domIndentationVisitor = new AstIndentationVisitor(policy, data) { AutoAcceptChanges = false, HadErrors = hadErrors }; compilationUnit.AcceptVisitor(domIndentationVisitor, null); var changes = new List <Change> (); changes.AddRange(domSpacingVisitor.Changes. Concat(domIndentationVisitor.Changes). Where(c => c is TextReplaceChange && (startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset < endOffset))); RefactoringService.AcceptChanges(null, null, changes); }
void GetAllSeverities() { foreach (var node in RefactoringService.GetInspectors(mimeType)) { severities [node] = node.GetSeverity(); } }
/// <summary> /// Our Run override is used to perform an action. /// /// Here we take the previously selected translation menu item and generate a translation for the string literal /// that is under the users cursor. /// /// We then create a TextReplaceChange and apply it using the RefactoringService. This will write new text (source code) /// at the location that we specify and add an undo operation into the undo buffer for us. /// </summary> /// <param name="dataItem">Data item.</param> protected override void Run(object dataItem) { var doc = IdeApp.Workbench.ActiveDocument; var editor = doc.Editor; if (doc != null && editor != null) { var loc = editor.CaretLocation; var setting = dataItem as TranslationSetting; var language = setting.TargetLanguage; var token = setting.Token; var text = token.Text.Substring(1, token.Text.Length - 2); // Grab the text without the "" characters. var translation = TranslationHelper.Translate(text, language); if (!string.IsNullOrEmpty(translation)) { TextReplaceChange translateChange = new TextReplaceChange(); translateChange.RemovedChars = token.Text.Length; translateChange.InsertedText = "\"" + translation + "\""; translateChange.Description = "Translate the existin string content to " + language; translateChange.Offset = token.SpanStart; translateChange.FileName = doc.FileName; var monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor("Apply translation", null); RefactoringService.AcceptChanges(monitor, new List <Change> () { translateChange }); } } }
public override void Run() { var selectedItem = GetSelectedItems().FirstOrDefault(); if (selectedItem == null) { return; } IClass c = GetClassFromName(selectedItem.FullyQualifiedClassName); if (c == null) { return; } IMember member = GetMemberFromName(c, selectedItem.MethodName, selectedItem.Parameters); if (member == null) { return; } string memberName = member.DeclaringType.Name + "." + member.Name; using (AsynchronousWaitDialog monitor = AsynchronousWaitDialog.ShowWaitDialog("${res:SharpDevelop.Refactoring.FindReferences}")) { FindReferencesAndRenameHelper.ShowAsSearchResults(StringParser.Parse("${res:SharpDevelop.Refactoring.ReferencesTo}", new string[, ] { { "Name", memberName } }), RefactoringService.FindReferences(member, monitor)); } }
void FindDerivedClasses(object sender, EventArgs e) { MenuCommand item = (MenuCommand)sender; IClass c = (IClass)item.Tag; IEnumerable <IClass> derivedClasses = RefactoringService.FindDerivedClasses(c, ParserService.AllProjectContents, false); List <SearchResultMatch> results = new List <SearchResultMatch>(); foreach (IClass derivedClass in derivedClasses) { if (derivedClass.CompilationUnit == null) { continue; } if (derivedClass.CompilationUnit.FileName == null) { continue; } SearchResultMatch res = new SimpleSearchResultMatch(ClassNode.GetText(derivedClass), new TextLocation(derivedClass.Region.BeginColumn - 1, derivedClass.Region.BeginLine - 1)); res.ProvidedDocumentInformation = FindReferencesAndRenameHelper.GetDocumentInformation(derivedClass.CompilationUnit.FileName); results.Add(res); } SearchResultPanel.Instance.ShowSearchResults(new SearchResult( StringParser.Parse("${res:SharpDevelop.Refactoring.ClassesDerivingFrom}", new string[, ] { { "Name", c.Name } }), results )); }
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); } } }
void AnalyzeFile(ProjectFile file, IProjectContent content) { var me = new object(); var owner = processedFiles.AddOrUpdate(file.Name, me, (key, old) => old); if (me != owner) { return; } if (file.BuildAction != BuildAction.Compile || tokenSource.IsCancellationRequested) { return; } TextEditorData editor; try { editor = TextFileProvider.Instance.GetReadOnlyTextEditorData(file.FilePath); } catch (FileNotFoundException) { // Swallow exception and ignore this file return; } var document = TypeSystemService.ParseFile(file.Project, editor); if (document == null) { return; } var compilation = content.AddOrUpdateFiles(document.ParsedFile).CreateCompilation(); CSharpAstResolver resolver; using (var timer = ExtensionMethods.ResolveCounter.BeginTiming()) { resolver = new CSharpAstResolver(compilation, document.GetAst <SyntaxTree> (), document.ParsedFile as ICSharpCode.NRefactory.CSharp.TypeSystem.CSharpUnresolvedFile); resolver.ApplyNavigator(new ExtensionMethods.ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Resolve, null)); } var context = document.CreateRefactoringContextWithEditor(editor, resolver, tokenSource.Token); CodeIssueProvider[] codeIssueProvider = RefactoringService.GetInspectors(editor.MimeType).ToArray(); foreach (var provider in codeIssueProvider) { var severity = provider.GetSeverity(); if (severity == Severity.None || tokenSource.IsCancellationRequested) { return; } try { foreach (var issue in provider.GetIssues(context, tokenSource.Token)) { AddIssue(file, provider, issue); } } catch (OperationCanceledException) { // The operation was cancelled, no-op as the user-visible parts are // handled elsewhere } } }
public DocGenerator(TextEditorData data) { this.data = data; if (data != null) { provider = RefactoringService.GetASTProvider(data.Document.MimeType); } }
static IList <CodeIssueProvider> GetInspectors(IReadonlyTextDocument editor, ICollection <string> inspectorIds) { var inspectors = RefactoringService.GetInspectors(editor.MimeType).ToList(); return(inspectors .Where(inspector => inspectorIds.Contains(inspector.IdString)) .ToList()); }
internal List <CodeAction> GetCurrentFixes() { if (currentSmartTag == null) { return(RefactoringService.GetValidActions(document, document.Editor.Caret.Location).Result.ToList()); } return(currentSmartTag.fixes); }
void OnOKClicked(object sender, EventArgs e) { List <Change> changes = rename.PerformChanges(options, Properties); IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor(this.Title, null); RefactoringService.AcceptChanges(monitor, options.Dom, changes); ((Widget)this).Destroy(); }
public override void Run(RefactoringOptions options) { List <Change> changes = PerformChanges(options, null); IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor(this.Name, null); RefactoringService.AcceptChanges(monitor, options.Dom, changes); // Console.WriteLine ("Changes accepted"); }
internal List <CodeAction> GetCurrentFixes() { if (QuickTaskStrip.EnableFancyFeatures && currentSmartTag == null) { return(RefactoringService.GetValidActions(document, document.Editor.Caret.Location).Result.ToList()); } return(currentSmartTag == null ? emptyList : currentSmartTag.fixes); }
public override string FormatText(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, string input, int startOffset, int endOffset) { var data = new TextEditorData(); data.Document.SuppressHighlightUpdate = true; data.Document.MimeType = mimeTypeChain.First(); data.Document.FileName = "toformat.cs"; var textPolicy = policyParent.Get <TextStylePolicy> (mimeTypeChain); data.Options.TabsToSpaces = textPolicy.TabsToSpaces; data.Options.TabSize = textPolicy.TabWidth; data.Options.OverrideDocumentEolMarker = true; data.Options.DefaultEolMarker = textPolicy.GetEolMarker(); data.Text = input; //System.Console.WriteLine ("-----"); //System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->")); //System.Console.WriteLine ("-----"); MonoDevelop.CSharp.Parser.CSharpParser parser = new MonoDevelop.CSharp.Parser.CSharpParser(); var compilationUnit = parser.Parse(data); bool hadErrors = parser.ErrorReportPrinter.ErrorsCount + parser.ErrorReportPrinter.FatalCounter > 0; var policy = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain); var formattingVisitor = new AstFormattingVisitor(policy, data) { AutoAcceptChanges = false }; compilationUnit.AcceptVisitor(formattingVisitor, null); var changes = new List <Change> (); changes.AddRange(formattingVisitor.Changes. Where(c => c is TextReplaceChange && (startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset < endOffset))); RefactoringService.AcceptChanges(null, null, changes); int end = endOffset; foreach (TextReplaceChange c in changes) { end -= c.RemovedChars; if (c.InsertedText != null) { end += c.InsertedText.Length; } } /* System.Console.WriteLine ("-----"); * System.Console.WriteLine (data.Text.Replace (" ", "^").Replace ("\t", "->")); * System.Console.WriteLine ("-----");*/ string result = data.GetTextBetween(startOffset, Math.Min(data.Length, end)); data.Dispose(); return(result); }
public override object VisitCompilationUnit(MonoDevelop.CSharp.Dom.CompilationUnit unit, object data) { base.VisitCompilationUnit(unit, data); if (AutoAcceptChanges) { RefactoringService.AcceptChanges(null, null, changes); } return(null); }
public static IEnumerable <Result> Check(Document input, CancellationToken cancellationToken) { if (!QuickTaskStrip.EnableFancyFeatures) { return(Enumerable.Empty <Result> ()); } // var now = DateTime.Now; var editor = input.Editor; if (editor == null) { return(Enumerable.Empty <Result> ()); } var loc = editor.Caret.Location; var result = new BlockingCollection <Result> (); var codeIssueProvider = RefactoringService.GetInspectors(editor.Document.MimeType).ToArray(); var context = input.ParsedDocument.CreateRefactoringContext != null? input.ParsedDocument.CreateRefactoringContext(input, cancellationToken) : null; // Console.WriteLine ("start check:"+ (DateTime.Now - now).TotalMilliseconds); Parallel.ForEach(codeIssueProvider, (provider) => { try { var severity = provider.GetSeverity(); if (severity == Severity.None) { return; } // var now2 = DateTime.Now; foreach (var r in provider.GetIssues(input, context, cancellationToken)) { var fixes = new List <GenericFix> (r.Actions.Where(a => a != null).Select(a => new GenericFix(a.Title, new System.Action(() => a.Run(input, loc))))); result.Add(new InspectorResults( provider, r.Region, r.Description, severity, provider.IssueMarker, fixes.ToArray() )); } /* var ms = (DateTime.Now - now2).TotalMilliseconds; * if (ms > 1000) * Console.WriteLine (ms +"\t\t"+ provider.Title);*/ } catch (OperationCanceledException) { //ignore } catch (Exception e) { LoggingService.LogError("CodeAnalysis: Got exception in inspector '" + provider + "'", e); } }); // Console.WriteLine ("END check:"+ (DateTime.Now - now).TotalMilliseconds); return(result); }
public override IEnumerable <IContextAction> GetAvailableActions(EditorContext editorContext) { foreach (var targetClass in editorContext.GetClassDeclarationsOnCurrentLine().Where(c => c.ClassType == ClassType.Class).Select(c2 => c2.GetCurrentClassPart(editorContext.Editor.FileName))) { foreach (var implementAction in RefactoringService.GetImplementAbstractClassActions(targetClass)) { yield return(implementAction); } } }
void OnOKClicked(object sender, EventArgs e) { var properties = Properties; ((Widget)this).Destroy(); var changes = this.rename(properties); ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor(Title, null); RefactoringService.AcceptChanges(monitor, changes); }
async void OnOKClicked(object sender, EventArgs e) { var properties = Properties; ((Widget)this).Destroy(); try { var changes = await this.rename(properties); ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor(Title, null); if (ChangedDocuments != null) { AlertButton result = null; var msg = new QuestionMessage(); msg.Buttons.Add(AlertButton.MakeWriteable); msg.Buttons.Add(AlertButton.Cancel); msg.AllowApplyToAll = true; foreach (var path in ChangedDocuments) { try { var attr = File.GetAttributes(path); if (attr.HasFlag(FileAttributes.ReadOnly)) { msg.Text = GettextCatalog.GetString("File {0} is read-only", path); msg.SecondaryText = GettextCatalog.GetString("Would you like to make the file writable?"); result = MessageService.AskQuestion(msg); if (result == AlertButton.Cancel) { return; } else if (result == AlertButton.MakeWriteable) { try { File.SetAttributes(path, attr & ~FileAttributes.ReadOnly); } catch (Exception ex) { MessageService.ShowError(ex.Message); return; } } } } catch (Exception ex) { MessageService.ShowError(ex.Message); return; } } } RefactoringService.AcceptChanges(monitor, changes); } catch (Exception ex) { MessageService.ShowError(GettextCatalog.GetString("Error while renaming symbol {0}", this.symbol.Name), ex); LoggingService.LogError("Error while renaming symbol " + this.symbol.Name, ex); } }
public static void JumpToDeclaration(MonoDevelop.Ide.Gui.Document doc, RefactoringSymbolInfo info) { if (info.Symbol != null) { RefactoringService.RoslynJumpToDeclaration(info.Symbol, doc.Project); } if (info.CandidateSymbols.Length > 0) { RefactoringService.RoslynJumpToDeclaration(info.CandidateSymbols[0], doc.Project); } }
void GoToBase(object sender, EventArgs e) { MenuCommand item = (MenuCommand)sender; IMember member = (IMember)item.Tag; IMember baseMember = RefactoringService.FindBaseMember(member); if (baseMember != null) { FindReferencesAndRenameHelper.JumpToDefinition(baseMember); } }
internal void SetLocation(TextLocation loc) { if (document != null) { location = RefactoringService.GetCorrectResolveLocation(document, loc); } else { location = loc; } }