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 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();
            }
        }
        /// <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
                    });
                }
            }
        }
Exemple #4
0
        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 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 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");
        }
        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();
        }
Exemple #8
0
 public override object VisitCompilationUnit(MonoDevelop.CSharp.Dom.CompilationUnit unit, object data)
 {
     base.VisitCompilationUnit(unit, data);
     if (AutoAcceptChanges)
     {
         RefactoringService.AcceptChanges(null, null, changes);
     }
     return(null);
 }
Exemple #9
0
        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);
        }
        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);
        }
Exemple #11
0
        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);
            }
        }
Exemple #12
0
        void OnOKClicked(object sender, EventArgs e)
        {
            TextEditorData data = options.GetTextEditorData();

            Mono.TextEditor.TextEditor editor = data.Parent;
// Insertion cursor mode test:
            if (editor != null)
            {
                IType type = properties.DeclaringMember.DeclaringType;

                InsertionCursorEditMode mode = new InsertionCursorEditMode(editor, CodeGenerationService.GetInsertionPoints(options.Document, type));
                for (int i = 0; i < mode.InsertionPoints.Count; i++)
                {
                    var point = mode.InsertionPoints[i];
                    if (point.Location < editor.Caret.Location)
                    {
                        mode.CurIndex = i;
                    }
                    else
                    {
                        break;
                    }
                }
                ModeHelpWindow helpWindow = new ModeHelpWindow();
                helpWindow.TransientFor = IdeApp.Workbench.RootWindow;
                helpWindow.TitleText    = GettextCatalog.GetString("<b>Extract 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();
                methodName       = entry.Text;
                activeModifier   = comboboxModifiers.Active;
                generateComments = checkbuttonGenerateComment.Active;

                mode.Exited += delegate(object s, InsertionCursorEventArgs args) {
                    if (args.Success)
                    {
                        SetProperties();
                        properties.InsertionPoint = args.InsertionPoint;
                        List <Change>    changes = extractMethod.PerformChanges(options, properties);
                        IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor(this.Title, null);
                        RefactoringService.AcceptChanges(monitor, options.Dom, changes);
                    }
                };
            }

            ((Widget)this).Destroy();
        }
Exemple #13
0
            public void Fix()
            {
                //FIXME: performchanges should probably use a monitor too, as it can be slow
                var changes = Refactoring.PerformChanges(Options, Properties);

                if (Preview)
                {
                    MessageService.ShowCustomDialog(new RefactoringPreviewDialog(Options.Dom, changes));
                }
                else
                {
                    var monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor("Rename", null);
                    RefactoringService.AcceptChanges(monitor, Options.Dom, changes);
                }
            }
        static void TestStatementFormatting(CSharpFormattingPolicy policy, string input, string expectedOutput)
        {
            TextEditorData data = new TextEditorData();

            data.Document.FileName = "a.cs";
            data.Document.Text     =
                @"class Test
{
	MyType TestMethod ()
	{
		"         + input + @"
	}
}";
            var compilationUnit = new CSharpParser().Parse(data);
            AstSpacingVisitor domSpacingVisitor = new AstSpacingVisitor(policy, data);

            domSpacingVisitor.AutoAcceptChanges = false;
            compilationUnit.AcceptVisitor(domSpacingVisitor, null);

            AstIndentationVisitor domIndentationVisitor = new AstIndentationVisitor(policy, data);

            domIndentationVisitor.AutoAcceptChanges = false;
            compilationUnit.AcceptVisitor(domIndentationVisitor, null);

            List <Change> changes = new List <Change> ();

            changes.AddRange(domSpacingVisitor.Changes);
            changes.AddRange(domIndentationVisitor.Changes);
            RefactoringService.AcceptChanges(null, null, changes);

            for (int i = 1; i <= data.Document.LineCount; i++)
            {
                LineSegment line = data.Document.GetLine(i);
                if (line.EditableLength < 2)
                {
                    continue;
                }
                data.Remove(line.Offset, 2);
            }
            string text = data.Document.GetTextBetween(data.Document.GetLine(5).Offset,
                                                       data.Document.GetLine(data.Document.LineCount - 1).Offset).Trim();

            Console.WriteLine(text);
            Assert.AreEqual(expectedOutput, text);
        }
        public static void RenameNamespace(INamespace ns, string newName)
        {
            using (var monitor = new NullProgressMonitor()) {
                var col = ReferenceFinder.FindReferences(ns, 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 Fix()
            {
                if (string.IsNullOrEmpty(Properties.NewName))
                {
                    Refactoring.Run(Options);
                    return;
                }

                //FIXME: performchanges should probably use a monitor too, as it can be slow
                var changes = Refactoring.PerformChanges(Options, Properties);

                if (Preview)
                {
                    using (var dlg = new RefactoringPreviewDialog(changes))
                        MessageService.ShowCustomDialog(dlg);
                }
                else
                {
                    var monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor("Rename", null);
                    RefactoringService.AcceptChanges(monitor, changes);
                }
            }
        public async Task PerformChangesAsync(ISymbol symbol, RenameProperties properties)
        {
            var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
            var ws       = TypeSystemService.GetWorkspace(solution);

            var newSolution = await Renamer.RenameSymbolAsync(ws.CurrentSolution, symbol, properties.NewName, ws.Options);

            ws.TryApplyChanges(newSolution);


            var changes = new List <Change> ();

            if (properties.RenameFile && symbol is INamedTypeSymbol)
            {
                var type           = (INamedTypeSymbol)symbol;
                int currentPart    = 1;
                var alreadyRenamed = new HashSet <string> ();
                foreach (var part in type.Locations)
                {
                    if (!part.IsInSource)
                    {
                        continue;
                    }
                    var fileName = part?.SourceTree?.FilePath;
                    if (fileName == null || alreadyRenamed.Contains(fileName))
                    {
                        continue;
                    }
                    alreadyRenamed.Add(fileName);

                    string oldFileName = System.IO.Path.GetFileNameWithoutExtension(fileName);
                    string newFileName;
                    var    newName = properties.NewName;
                    if (string.IsNullOrEmpty(oldFileName) || string.IsNullOrEmpty(newName))
                    {
                        continue;
                    }
                    if (oldFileName.ToUpper() == newName.ToUpper() || oldFileName.ToUpper().EndsWith("." + newName.ToUpper(), StringComparison.Ordinal))
                    {
                        continue;
                    }
                    int idx = oldFileName.IndexOf(type.Name, StringComparison.Ordinal);
                    if (idx >= 0)
                    {
                        newFileName = oldFileName.Substring(0, idx) + newName + oldFileName.Substring(idx + type.Name.Length);
                    }
                    else
                    {
                        newFileName = currentPart != 1 ? newName + currentPart : newName;
                        currentPart++;
                    }

                    int t = 0;
                    while (System.IO.File.Exists(GetFullFileName(newFileName, fileName, t)))
                    {
                        t++;
                    }
                    changes.Add(new RenameFileChange(fileName, GetFullFileName(newFileName, fileName, t)));
                }
            }
            RefactoringService.AcceptChanges(new ProgressMonitor(), changes);
        }
        public static void Format(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, MonoDevelop.Ide.Gui.Document data, ProjectDom dom, DomLocation location, bool correctBlankLines, bool runAferCR /* = false*/)
        {
            if (data.ParsedDocument == null || data.ParsedDocument.CompilationUnit == null)
            {
                return;
            }
            var member = data.ParsedDocument.CompilationUnit.GetMemberAt(location.Line + (runAferCR ? -1 : 0), location.Column);

            if (member == null || member.Location.IsEmpty || member.BodyRegion.End.IsEmpty)
            {
                return;
            }

            StringBuilder sb = new StringBuilder();
            int           closingBrackets = 0;
            DomRegion     validRegion     = DomRegion.Empty;

            foreach (var u in data.ParsedDocument.CompilationUnit.Usings.Where(us => us.IsFromNamespace))
            {
                // the dom parser breaks A.B.C into 3 namespaces with the same region, this is filtered here
                if (u.ValidRegion == validRegion)
                {
                    continue;
                }
                validRegion = u.ValidRegion;
                sb.Append("namespace Stub {");
                closingBrackets++;
            }

            var parent = member.DeclaringType;

            while (parent != null)
            {
                sb.Append("class Stub {");
                closingBrackets++;
                parent = parent.DeclaringType;
            }
            sb.AppendLine();
            int startOffset = sb.Length;
            int memberStart = data.Editor.LocationToOffset(member.Location.Line, 1);
            int memberEnd   = data.Editor.LocationToOffset(member.BodyRegion.End.Line + (runAferCR ? 1 : 0), member.BodyRegion.End.Column);

            if (memberEnd < 0)
            {
                memberEnd = data.Editor.Length;
            }
            sb.Append(data.Editor.GetTextBetween(memberStart, memberEnd));
            int endOffset = sb.Length;

            sb.AppendLine();
            sb.Append(new string ('}', closingBrackets));
            TextEditorData stubData = new TextEditorData()
            {
                Text = sb.ToString()
            };

            stubData.Document.FileName = data.FileName;
            var  parser          = new MonoDevelop.CSharp.Parser.CSharpParser();
            bool hadErrors       = parser.ErrorReportPrinter.ErrorsCount + parser.ErrorReportPrinter.FatalCounter > 0;
            var  compilationUnit = parser.Parse(stubData);

            var policy            = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);
            var domSpacingVisitor = new AstFormattingVisitor(policy, stubData)
            {
                AutoAcceptChanges = false,
            };

            compilationUnit.AcceptVisitor(domSpacingVisitor, null);


            var changes = new List <Change> ();

            changes.AddRange(domSpacingVisitor.Changes.Cast <TextReplaceChange> ().Where(c => startOffset < c.Offset && c.Offset < endOffset));
            int           delta = data.Editor.LocationToOffset(member.Location.Line, 1) - startOffset;
            HashSet <int> lines = new HashSet <int> ();

            foreach (TextReplaceChange change in changes)
            {
                if (change is AstFormattingVisitor.MyTextReplaceChange)
                {
                    ((AstFormattingVisitor.MyTextReplaceChange)change).SetTextEditorData(data.Editor);
                }
                change.Offset += delta;
                lines.Add(data.Editor.OffsetToLineNumber(change.Offset));
            }
            // be sensible in documents with parser errors - only correct up to the caret position.
            if (parser.ErrorReportPrinter.Errors.Any(e => e.ErrorType == ErrorType.Error) || data.ParsedDocument.Errors.Any(e => e.ErrorType == ErrorType.Error))
            {
                var lastOffset = data.Editor.Caret.Offset;
                changes.RemoveAll(c => ((TextReplaceChange)c).Offset > lastOffset);
            }
            RefactoringService.AcceptChanges(null, null, changes);
            foreach (int line in lines)
            {
                data.Editor.Document.CommitLineUpdate(line);
            }
            stubData.Dispose();
        }
 internal static string GetOutput(RefactoringOptions options, List <Change> changes)
 {
     RefactoringService.AcceptChanges(null, options.Dom, changes, new FileProvider(options));
     return(options.Document.Editor.Text);
 }