/// <summary>
        /// Filters the initial result set by determining which entries actually resolve back to our declaration target.
        /// </summary>
        private IDictionary <String, List <SearchMatch> > ResolveActualMatches(FRResults results, ASResult target)
        {
            // this will hold actual references back to the source member (some result hits could point to different members with the same name)
            IDictionary <String, List <SearchMatch> > actualMatches = new Dictionary <String, List <SearchMatch> >();
            IDictionary <String, List <SearchMatch> > initialResultsList = RefactoringHelper.GetInitialResultsList(results);
            int matchesChecked = 0; int totalMatches = 0;

            foreach (KeyValuePair <String, List <SearchMatch> > entry in initialResultsList)
            {
                totalMatches += entry.Value.Count;
            }
            Boolean foundDeclarationSource = false;
            bool    optionsEnabled = IncludeComments || IncludeStrings;

            foreach (KeyValuePair <String, List <SearchMatch> > entry in initialResultsList)
            {
                String currentFileName = entry.Key;
                UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.ResolvingReferencesIn") + " \"" + currentFileName + "\"");
                foreach (SearchMatch match in entry.Value)
                {
                    // we have to open/reopen the entry's file
                    // there are issues with evaluating the declaration targets with non-open, non-current files
                    // we have to do it each time as the process of checking the declaration source can change the currently open file!
                    ScintillaControl sci = this.AssociatedDocumentHelper.LoadDocument(currentFileName).SciControl;
                    // if the search result does point to the member source, store it
                    bool add = false;
                    if (RefactoringHelper.DoesMatchPointToTarget(sci, match, target, this.AssociatedDocumentHelper))
                    {
                        if (ignoreDeclarationSource && !foundDeclarationSource && RefactoringHelper.IsMatchTheTarget(sci, match, target))
                        {
                            //ignore the declaration source
                            foundDeclarationSource = true;
                        }
                        else
                        {
                            add = true;
                        }
                    }
                    else if (optionsEnabled)
                    {
                        add = RefactoringHelper.IsInsideCommentOrString(match, sci, IncludeComments, IncludeStrings);
                    }

                    if (add)
                    {
                        if (!actualMatches.ContainsKey(currentFileName))
                        {
                            actualMatches.Add(currentFileName, new List <SearchMatch>());
                        }

                        actualMatches[currentFileName].Add(match);
                    }

                    matchesChecked++;
                    UserInterfaceManager.ProgressDialog.UpdateProgress((100 * matchesChecked) / totalMatches);
                }
            }
            this.AssociatedDocumentHelper.CloseTemporarilyOpenedDocuments();
            return(actualMatches);
        }
 /// <summary>
 /// Entry point to execute finding.
 /// </summary>
 protected override void ExecutionImplementation()
 {
     UserInterfaceManager.ProgressDialog.Show();
     UserInterfaceManager.ProgressDialog.SetTitle(TextHelper.GetString("Info.FindingReferences"));
     UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.SearchingFiles"));
     RefactoringHelper.FindTargetInFiles(currentTarget, new FRProgressReportHandler(this.RunnerProgress), new FRFinishedHandler(this.FindFinished), true);
 }
Exemple #3
0
 /// <summary>
 /// Entry point to execute finding.
 /// </summary>
 protected override void ExecutionImplementation()
 {
     UserInterfaceManager.ProgressDialog.Show();
     UserInterfaceManager.ProgressDialog.SetTitle(TextHelper.GetString("Info.FindingReferences"));
     UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.SearchingFiles"));
     RefactoringHelper.FindTargetInFiles(CurrentTarget, RunnerProgress, FindFinished, true, OnlySourceFiles, true, IncludeComments, IncludeStrings);
 }
Exemple #4
0
        private bool ValidateTargets()
        {
            var  target  = findAllReferencesCommand.CurrentTarget;
            bool isEnum  = target.Type.IsEnum();
            bool isClass = false;

            if (!isEnum)
            {
                bool isVoid = target.Type.IsVoid();
                isClass = !isVoid && target.IsStatic && (target.Member == null || RefactoringHelper.CheckFlag(target.Member.Flags, FlagType.Constructor));
            }

            bool isGlobalFunction  = false;
            bool isGlobalNamespace = false;

            if (!isEnum && !isClass && (target.InClass == null || target.InClass.IsVoid()))
            {
                isGlobalFunction  = RefactoringHelper.CheckFlag(target.Member.Flags, FlagType.Function);
                isGlobalNamespace = RefactoringHelper.CheckFlag(target.Member.Flags, FlagType.Namespace);
            }

            // Types with not their own file
            if (!isEnum && !isClass && !isGlobalFunction && !isGlobalNamespace)
            {
                return(true);
            }

            var member = isEnum || isClass ? target.Type : target.Member;
            var inFile = member.InFile;

            // Is this possible? should return false? I'm inclined to think so
            if (inFile == null)
            {
                return(true);
            }

            oldFileName = inFile.FileName;
            string oldName = Path.GetFileNameWithoutExtension(oldFileName);

            // Private classes and similars
            if (string.IsNullOrEmpty(oldName) || !oldName.Equals(member.Name))
            {
                return(true);
            }

            string fullPath = Path.GetFullPath(inFile.FileName);

            fullPath = Path.GetDirectoryName(fullPath);

            newFileName = Path.Combine(fullPath, NewName + Path.GetExtension(oldFileName));

            // No point in refactoring if the old and new name is the same
            if (string.IsNullOrEmpty(oldFileName) || oldFileName.Equals(newFileName))
            {
                return(false);
            }

            // Check if the new file name already exists
            return(FileHelper.ConfirmOverwrite(newFileName));
        }
Exemple #5
0
        /// <summary>
        /// Renames the given the set of matched references
        /// </summary>
        private void OnFindAllReferencesCompleted(Object sender, RefactorCompleteEventArgs <IDictionary <string, List <SearchMatch> > > eventArgs)
        {
            UserInterfaceManager.ProgressDialog.Show();
            UserInterfaceManager.ProgressDialog.SetTitle(TextHelper.GetString("Info.RenamingReferences"));
            PluginCore.Controls.MessageBar.Locked = true;
            foreach (KeyValuePair <String, List <SearchMatch> > entry in eventArgs.Results)
            {
                UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.Updating") + " \"" + entry.Key + "\"");
                // re-open the document and replace all the text
                PluginBase.MainForm.OpenEditableDocument(entry.Key);
                ScintillaControl sci = ASContext.CurSciControl;
                // replace matches in the current file with the new name
                RefactoringHelper.ReplaceMatches(entry.Value, sci, this.newName, sci.Text);
                if (sci.IsModify)
                {
                    this.AssociatedDocumentHelper.MarkDocumentToKeep(sci.FileName);
                }
            }
            this.Results = eventArgs.Results;
            if (this.outputResults)
            {
                this.ReportResults();
            }
            UserInterfaceManager.ProgressDialog.Hide();
            PluginCore.Controls.MessageBar.Locked = false;
            this.FireOnRefactorComplete();

            RenameFile();
        }
        private void AddGetterSetterPreview(List <ReferenceInfo> refInfos, ASResult target, string prefix, string name, bool supportInsideComment, bool supportInsideString)
        {
            target = RenamingHelper.FindGetterSetter(target, prefix + name);
            if (target == null)
            {
                return;
            }

            var results = new FRRunner().SearchSync(GetConfig(prefix + name))[currentDoc.FileName];
            int offset  = prefix.Length;

            foreach (var match in results)
            {
                int    index         = match.Index + offset;
                int    length        = match.Length - offset;
                string value         = match.Value.Substring(offset);
                int    style         = sci.BaseStyleAt(index);
                bool   insideComment = supportInsideComment && RefactoringHelper.IsCommentStyle(style);
                bool   insideString  = supportInsideString && RefactoringHelper.IsStringStyle(style);

                if (RefactoringHelper.DoesMatchPointToTarget(sci, match, target, null) || insideComment || insideString)
                {
                    var @ref = new ReferenceInfo()
                    {
                        Index = index, Length = length, Value = value
                    };
                    refInfos.Add(@ref);

                    if (previewChanges && (!insideComment || includeComments) && (!insideString || includeStrings))
                    {
                        Highlight(index, value.Length);
                    }
                }
            }
        }
Exemple #7
0
 /// <summary>
 /// Renames the given the set of matched references
 /// </summary>
 private void OnFindAllReferencesCompleted(object sender, RefactorCompleteEventArgs <IDictionary <string, List <SearchMatch> > > eventArgs)
 {
     UserInterfaceManager.ProgressDialog.Show();
     UserInterfaceManager.ProgressDialog.SetTitle(TextHelper.GetString("Info.UpdatingReferences"));
     MessageBar.Locked = true;
     foreach (var entry in eventArgs.Results)
     {
         UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.Updating") + " \"" + entry.Key + "\"");
         // re-open the document and replace all the text
         var doc = AssociatedDocumentHelper.LoadDocument(entry.Key);
         var sci = doc.SciControl;
         // replace matches in the current file with the new name
         RefactoringHelper.ReplaceMatches(entry.Value, sci, NewName);
         //Uncomment if we want to keep modified files
         //if (sci.IsModify) AssociatedDocumentHelper.MarkDocumentToKeep(entry.Key);
         doc.Save();
     }
     if (newFileName != null)
     {
         RenameFile(eventArgs.Results);
     }
     Results = eventArgs.Results;
     AssociatedDocumentHelper.CloseTemporarilyOpenedDocuments();
     if (OutputResults)
     {
         ReportResults();
     }
     UserInterfaceManager.ProgressDialog.Hide();
     MessageBar.Locked = false;
     FireOnRefactorComplete();
 }
Exemple #8
0
        /// <summary>
        /// Generate surround main menu and context menu items
        /// </summary>
        private void GenerateSurroundMenuItems()
        {
            ITabbedDocument document = PluginBase.MainForm.CurrentDocument;

            if (document != null && document.IsEditable && RefactoringHelper.GetLanguageIsValid())
            {
                this.surroundContextMenu.GenerateSnippets(document.SciControl);
                foreach (ToolStripMenuItem item in this.surroundContextMenu.DropDownItems)
                {
                    item.Click += this.SurroundWithClicked;
                }
                foreach (ToolStripMenuItem item in this.refactorMainMenu.SurroundMenu.DropDownItems)
                {
                    item.Click -= this.SurroundWithClicked;
                }
                this.refactorMainMenu.SurroundMenu.GenerateSnippets(document.SciControl);
                foreach (ToolStripMenuItem item in this.refactorMainMenu.SurroundMenu.DropDownItems)
                {
                    item.Click += this.SurroundWithClicked;
                }
            }
            else
            {
                this.surroundContextMenu.DropDownItems.Clear();
                this.refactorMainMenu.SurroundMenu.DropDownItems.Clear();
                this.refactorMainMenu.SurroundMenu.DropDownItems.Add("");
                this.surroundContextMenu.DropDownItems.Add("");
            }
        }
 /// <summary>
 /// Invoked when the FRSearch completes its search
 /// </summary>
 private void FindFinished(FRResults results)
 {
     UserInterfaceManager.ProgressDialog.Reset();
     UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.ResolvingReferences"));
     // First filter out any results that don't actually point to our source declaration
     this.Results = ResolveActualMatches(results, currentTarget);
     if (this.outputResults)
     {
         this.ReportResults();
     }
     UserInterfaceManager.ProgressDialog.Hide();
     // Select first match
     if (this.Results.Count > 0)
     {
         foreach (var fileEntries in this.Results)
         {
             if (fileEntries.Value.Count > 0 && System.IO.File.Exists(fileEntries.Key))
             {
                 SearchMatch entry = fileEntries.Value[0];
                 PluginBase.MainForm.OpenEditableDocument(fileEntries.Key, false);
                 RefactoringHelper.SelectMatch(PluginBase.MainForm.CurrentDocument.SciControl, entry);
                 break;
             }
         }
     }
     this.FireOnRefactorComplete();
 }
Exemple #10
0
 private void CopyTargets()
 {
     MessageBar.Locked = true;
     foreach (var target in targets)
     {
         string oldPath = target.OldFilePath;
         string newPath = target.NewFilePath;
         if (File.Exists(oldPath))
         {
             if (oldPath.Equals(newPath, StringComparison.OrdinalIgnoreCase))
             {
                 // name casing changed
                 // we cannot append to the extension, as it will break finding possibly needed references
                 // we don't use folders to avoid several possible problems and ease some logic
                 newPath = target.TmpFilePath = Path.Combine(Path.GetDirectoryName(oldPath),
                                                             Path.GetFileNameWithoutExtension(oldPath) +
                                                             "$renaming$" +
                                                             Path.GetExtension(oldPath));
             }
             if (!Path.IsPathRooted(newPath))
             {
                 newPath = Path.Combine(Path.GetDirectoryName(oldPath), newPath);
             }
             string newDirectory = Path.GetDirectoryName(newPath);
             if (!Directory.Exists(newDirectory))
             {
                 Directory.CreateDirectory(newDirectory);
             }
             RefactoringHelper.Copy(oldPath, newPath, true, true);
         }
     }
     MessageBar.Locked = false;
 }
Exemple #11
0
        private void FindFinished(FRResults results)
        {
            UserInterfaceManager.ProgressDialog.Show();
            UserInterfaceManager.ProgressDialog.SetTitle(TextHelper.GetString("Info.UpdatingReferences"));
            MessageBar.Locked = true;
            bool   isNotHaxe         = !PluginBase.CurrentProject.Language.StartsWith("haxe");
            bool   packageIsNotEmpty = !string.IsNullOrEmpty(currentTarget.OldFileModel.Package);
            string targetName        = Path.GetFileNameWithoutExtension(currentTarget.OldFilePath);
            string oldType           = (currentTarget.OldFileModel.Package + "." + targetName).Trim('.');
            string newType           = (currentTarget.NewPackage + "." + targetName).Trim('.');

            foreach (KeyValuePair <string, List <SearchMatch> > entry in results)
            {
                List <SearchMatch> matches = entry.Value;
                if (matches.Count == 0)
                {
                    continue;
                }
                string path = entry.Key;
                UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.Updating") + " \"" + path + "\"");
                ScintillaControl sci = AssociatedDocumentHelper.LoadDocument(path);
                if (isNotHaxe && path != currentTarget.NewFilePath && ASContext.Context.CurrentModel.Imports.Search(targetName, FlagType.Class & FlagType.Function & FlagType.Namespace, 0) == null)
                {
                    ASGenerator.InsertImport(new MemberModel(targetName, newType, FlagType.Import, 0), false);
                }
                if (packageIsNotEmpty)
                {
                    RefactoringHelper.ReplaceMatches(matches, sci, newType, null);
                }
                else
                {
                    foreach (SearchMatch sm in matches)
                    {
                        if (sm.LineText.TrimStart().StartsWith("import"))
                        {
                            RefactoringHelper.SelectMatch(sci, sm);
                            sci.ReplaceSel(newType);
                        }
                    }
                }
                foreach (SearchMatch match in matches)
                {
                    match.LineText = sci.GetLine(match.Line - 1);
                    match.Value    = newType;
                }
                if (!Results.ContainsKey(path))
                {
                    Results[path] = new List <SearchMatch>();
                }
                Results[path].AddRange(matches.ToArray());
                PluginBase.MainForm.CurrentDocument.Save();
                if (sci.IsModify)
                {
                    AssociatedDocumentHelper.MarkDocumentToKeep(path);
                }
            }
            UserInterfaceManager.ProgressDialog.Hide();
            MessageBar.Locked = false;
            UpdateReferencesNextTarget();
        }
Exemple #12
0
        public static void AnalyzeLogicalAndExpression(SyntaxNodeAnalysisContext context, INamedTypeSymbol expressionType)
        {
            var logicalAndExpression = (BinaryExpressionSyntax)context.Node;

            if (!logicalAndExpression.ContainsDiagnostics)
            {
                ExpressionSyntax expression = SyntaxInfo.NullCheckExpressionInfo(logicalAndExpression.Left, allowedKinds: NullCheckKind.NotEqualsToNull).Expression;

                if (expression != null &&
                    context.SemanticModel
                    .GetTypeSymbol(expression, context.CancellationToken)?
                    .IsReferenceType == true)
                {
                    ExpressionSyntax right = logicalAndExpression.Right?.WalkDownParentheses();

                    if (right != null &&
                        ValidateRightExpression(right, context.SemanticModel, context.CancellationToken) &&
                        !RefactoringHelper.ContainsOutArgumentWithLocal(right, context.SemanticModel, context.CancellationToken))
                    {
                        ExpressionSyntax expression2 = FindExpressionThatCanBeConditionallyAccessed(expression, right);

                        if (expression2?.SpanContainsDirectives() == false &&
                            !logicalAndExpression.IsInExpressionTree(expressionType, context.SemanticModel, context.CancellationToken))
                        {
                            context.ReportDiagnostic(DiagnosticDescriptors.UseConditionalAccess, logicalAndExpression);
                        }
                    }
                }
            }
        }
Exemple #13
0
        private static InvocationExpressionSyntax GetNewInvocation(InvocationExpressionSyntax invocation)
        {
            ArgumentListSyntax argumentList = invocation.ArgumentList;
            SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

            return(RefactoringHelper.ChangeInvokedMethodName(invocation, "Fail")
                   .WithArgumentList(argumentList.WithArguments(arguments.RemoveAt(0))));
        }
Exemple #14
0
        /// <summary>
        /// Checks if the file or directory is ok for refactoring
        /// </summary>
        private static bool IsValidFile(string file)
        {
            IProject project = PluginBase.CurrentProject;

            return(project != null &&
                   RefactoringHelper.IsProjectRelatedFile(project, file) &&
                   Regex.Match(Path.GetFileNameWithoutExtension(file), REG_IDENTIFIER, RegexOptions.Singleline).Success &&
                   (Directory.Exists(file) || FileHelper.FileMatchesSearchFilter(file, project.DefaultSearchFilter)));
        }
        public static Task <Document> RefactorAsync(
            Document document,
            InvocationExpressionSyntax invocationExpression,
            string newName,
            CancellationToken cancellationToken)
        {
            InvocationExpressionSyntax newInvocationExpression = RefactoringHelper.ChangeInvokedMethodName(invocationExpression, newName);

            return(document.ReplaceNodeAsync(invocationExpression, newInvocationExpression, cancellationToken));
        }
Exemple #16
0
        void GenerateExtractVariable(List <SearchMatch> matches)
        {
            if (string.IsNullOrEmpty(newName))
            {
                newName = GetNewName();
            }
            if (string.IsNullOrEmpty(newName))
            {
                return;
            }
            var sci = PluginBase.MainForm.CurrentDocument.SciControl;

            sci.BeginUndoAction();
            try
            {
                var expression = sci.SelText.Trim(new char[] { '=', ' ', '\t', '\n', '\r', ';', '.' });
                expression = expression.TrimEnd(new char[] { '(', '[', '{', '<' });
                expression = expression.TrimStart(new char[] { ')', ']', '}', '>' });
                var insertPosition = sci.PositionFromLine(ASContext.Context.CurrentMember.LineTo);
                foreach (var match in matches)
                {
                    var position = sci.MBSafePosition(match.Index);
                    insertPosition = Math.Min(insertPosition, position);
                    match.LineText = sci.GetLine(match.Line - 1);
                }
                insertPosition = sci.LineFromPosition(insertPosition);
                insertPosition = sci.LineIndentPosition(insertPosition);
                RefactoringHelper.ReplaceMatches(matches, sci, newName);
                sci.SetSel(insertPosition, insertPosition);
                var member = new MemberModel(newName, string.Empty, FlagType.LocalVar, 0)
                {
                    Value = expression
                };
                var snippet = TemplateUtils.GetTemplate("Variable");
                snippet  = TemplateUtils.ReplaceTemplateVariable(snippet, "Modifiers", null);
                snippet  = TemplateUtils.ToDeclarationString(member, snippet);
                snippet += "$(Boundary)\n$(Boundary)";
                SnippetHelper.InsertSnippetText(sci, sci.CurrentPos, snippet);
                foreach (var match in matches)
                {
                    match.Line += 1;
                }
                Results = new Dictionary <string, List <SearchMatch> > {
                    { sci.FileName, matches }
                };
                if (outputResults)
                {
                    ReportResults();
                }
            }
            finally
            {
                sci.EndUndoAction();
            }
        }
        protected BinaryExpressionSyntax CreateCoalesceExpression(SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            int position = IfStatement.SpanStart;

            return(RefactoringHelper.CreateCoalesceExpression(
                       GetTargetType(position, semanticModel, cancellationToken),
                       Left.WithoutTrivia(),
                       Right.WithoutTrivia(),
                       position,
                       semanticModel));
        }
Exemple #18
0
 /// <summary>
 /// Invoked when the user selects the "Rename" command
 /// </summary>
 private void RenameClicked(Object sender, EventArgs e)
 {
     try
     {
         RenamingHelper.AddToQueue(RefactoringHelper.GetDefaultRefactorTarget());
     }
     catch (Exception ex)
     {
         ErrorManager.ShowError(ex);
     }
 }
Exemple #19
0
        private static ExpressionSyntax GetNewNode(PrefixUnaryExpressionSyntax logicalNot)
        {
            ExpressionSyntax operand    = logicalNot.Operand;
            ExpressionSyntax expression = operand.WalkDownParentheses();

            switch (expression.Kind())
            {
            case SyntaxKind.TrueLiteralExpression:
            case SyntaxKind.FalseLiteralExpression:
            {
                LiteralExpressionSyntax newNode = BooleanLiteralExpression(expression.Kind() == SyntaxKind.FalseLiteralExpression);

                newNode = newNode.WithTriviaFrom(expression);

                return(operand.ReplaceNode(expression, newNode));
            }

            case SyntaxKind.LogicalNotExpression:
            {
                return(((PrefixUnaryExpressionSyntax)expression).Operand);
            }

            case SyntaxKind.EqualsExpression:
            {
                var equalsExpression = (BinaryExpressionSyntax)expression;

                BinaryExpressionSyntax notEqualsExpression = NotEqualsExpression(
                    equalsExpression.Left,
                    ExclamationEqualsToken().WithTriviaFrom(equalsExpression.OperatorToken),
                    equalsExpression.Right);

                return(operand.ReplaceNode(equalsExpression, notEqualsExpression));
            }

            case SyntaxKind.InvocationExpression:
            {
                var invocationExpression = (InvocationExpressionSyntax)expression;

                var memberAccessExpression = (MemberAccessExpressionSyntax)invocationExpression.Expression;

                ExpressionSyntax lambdaExpression = invocationExpression.ArgumentList.Arguments.First().Expression.WalkDownParentheses();

                SingleParameterLambdaExpressionInfo lambdaInfo = SyntaxInfo.SingleParameterLambdaExpressionInfo(lambdaExpression);

                var logicalNot2 = (PrefixUnaryExpressionSyntax)GetReturnExpression(lambdaInfo.Body).WalkDownParentheses();

                InvocationExpressionSyntax newNode = invocationExpression.ReplaceNode(logicalNot2, logicalNot2.Operand.WithTriviaFrom(logicalNot2));

                return(RefactoringHelper.ChangeInvokedMethodName(newNode, (memberAccessExpression.Name.Identifier.ValueText == "All") ? "Any" : "All"));
            }
            }

            return(null);
        }
Exemple #20
0
        /// <summary>
        /// Set up required variables for live preview features.
        /// </summary>
        /// <param name="supportInsideComment">Whether searching inside comments are enabled.</param>
        /// <param name="supportInsideString">Whether searching inside strings are enabled.</param>
        /// <param name="supportPreviewChanges">Whether live preview is enabled.</param>
        /// <param name="target">Current target to rename.</param>
        private void SetupLivePreview(bool supportInsideComment, bool supportInsideString, bool supportPreviewChanges, ASResult target)
        {
            if (!supportPreviewChanges)
            {
                return;
            }

            var results  = new FRRunner().SearchSync(GetConfig(oldName))[currentDoc.FileName];
            var tempRefs = new List <ReferenceInfo>();

            foreach (var match in results)
            {
                int    index         = match.Index;
                int    length        = match.Length;
                string value         = match.Value;
                int    style         = sci.BaseStyleAt(index);
                bool   insideComment = supportInsideComment && RefactoringHelper.IsCommentStyle(style);
                bool   insideString  = supportInsideString && RefactoringHelper.IsStringStyle(style);

                if (RefactoringHelper.DoesMatchPointToTarget(sci, match, target, null) || insideComment || insideString)
                {
                    var @ref = new ReferenceInfo()
                    {
                        Index = index, Length = length, Value = value
                    };
                    tempRefs.Add(@ref);

                    if (currentRef == null && match.Index == start)
                    {
                        currentRef = @ref;
                    }
                    else if (previewChanges && (!insideComment || includeComments) && (!insideString || includeStrings))
                    {
                        Highlight(index, length);
                    }
                }
            }

            if (RenamingHelper.HasGetterSetter(target))
            {
                var list = target.Member.Parameters;
                if (list[0].Name == RenamingHelper.ParamGetter)
                {
                    AddGetterSetterPreview(tempRefs, target, RenamingHelper.PrefixGetter, oldName, supportInsideComment, supportInsideString);
                }
                if (list[1].Name == RenamingHelper.ParamSetter)
                {
                    AddGetterSetterPreview(tempRefs, target, RenamingHelper.PrefixSetter, oldName, supportInsideComment, supportInsideString);
                }
                tempRefs.Sort();
            }

            refs = tempRefs.ToArray();
        }
Exemple #21
0
        /// <summary>
        ///
        /// </summary>
        private void MoveTargets()
        {
            Dictionary <string, ITabbedDocument> fileNameToOpenedDoc = new Dictionary <string, ITabbedDocument>();

            foreach (ITabbedDocument doc in PluginBase.MainForm.Documents)
            {
                fileNameToOpenedDoc.Add(doc.FileName, doc);
            }
            MessageBar.Locked = true;
            foreach (KeyValuePair <string, string> item in oldPathToNewPath)
            {
                string oldPath = item.Key;
                string newPath = item.Value;
                if (Path.HasExtension(oldPath))
                {
                    if (fileNameToOpenedDoc.ContainsKey(oldPath))
                    {
                        fileNameToOpenedDoc[oldPath].Save();
                        fileNameToOpenedDoc[oldPath].Close();
                    }
                    newPath = Path.Combine(item.Value, Path.GetFileName(oldPath));
                    // refactor failed or was refused
                    if (Path.GetFileName(oldPath).Equals(newPath, StringComparison.OrdinalIgnoreCase))
                    {
                        // name casing changed
                        string tmpPath = oldPath + "$renaming$";
                        File.Move(oldPath, tmpPath);
                        oldPath = tmpPath;
                    }
                    if (!Path.IsPathRooted(newPath))
                    {
                        newPath = Path.Combine(Path.GetDirectoryName(oldPath), newPath);
                    }
                    RefactoringHelper.Move(oldPath, newPath);
                }
                else
                {
                    foreach (string file in Directory.GetFiles(oldPath, "*.*", SearchOption.AllDirectories))
                    {
                        if (fileNameToOpenedDoc.ContainsKey(file))
                        {
                            fileNameToOpenedDoc[file].Save();
                            fileNameToOpenedDoc[file].Close();
                        }
                    }
                    RefactoringHelper.Move(oldPath, newPath, renaming);
                }
            }
            MessageBar.Locked = false;
        }
Exemple #22
0
        /// <summary>
        /// A new Rename refactoring command.
        /// </summary>
        /// <param name="target">The target declaration to find references to.</param>
        /// <param name="outputResults">If true, will send the found results to the trace log and results panel</param>
        /// <param name="newName">If provided, will not query the user for a new name.</param>
        /// <param name="ignoreDeclarationSource">If true, will not rename the original declaration source.  Useful for Encapsulation refactoring.</param>
        public Rename(ASResult target, Boolean outputResults, String newName, Boolean ignoreDeclarationSource)
        {
            if (target == null)
            {
                TraceManager.Add("refactor target is null");
                return;
            }
            this.outputResults = outputResults;
            if (target.IsPackage)
            {
                string package = target.Path.Replace('.', Path.DirectorySeparatorChar);
                foreach (PathModel aPath in ASContext.Context.Classpath)
                {
                    if (aPath.IsValid && !aPath.Updating)
                    {
                        string path = Path.Combine(aPath.Path, package);
                        if (aPath.IsValid && Directory.Exists(path))
                        {
                            this.newName = string.IsNullOrEmpty(newName) ? GetNewName(Path.GetFileName(path)) : newName;
                            if (string.IsNullOrEmpty(this.newName))
                            {
                                return;
                            }
                            renamePackage = new Move(new Dictionary <string, string> {
                                { path, this.newName }
                            }, true, true);
                            return;
                        }
                    }
                }
                return;
            }

            this.newName = !string.IsNullOrEmpty(newName) ? newName : GetNewName(RefactoringHelper.GetRefactorTargetName(target));

            if (string.IsNullOrEmpty(this.newName))
            {
                return;
            }

            // create a FindAllReferences refactor to get all the changes we need to make
            // we'll also let it output the results, at least until we implement a way of outputting the renamed results later
            this.findAllReferencesCommand = new FindAllReferences(target, false, ignoreDeclarationSource)
            {
                OnlySourceFiles = true
            };
            // register a completion listener to the FindAllReferences so we can rename the entries
            this.findAllReferencesCommand.OnRefactorComplete += OnFindAllReferencesCompleted;
        }
Exemple #23
0
        /// <summary>
        /// Generate surround main menu and context menu items
        /// </summary>
        private void GenerateSurroundMenuItems()
        {
            ITabbedDocument document = PluginBase.MainForm.CurrentDocument;

            if (document != null && document.IsEditable && RefactoringHelper.GetLanguageIsValid())
            {
                this.surroundContextMenu.GenerateSnippets(document.SciControl);
                this.refactorMainMenu.SurroundMenu.GenerateSnippets(document.SciControl);
            }
            else
            {
                this.surroundContextMenu.Clear();
                this.refactorMainMenu.SurroundMenu.Clear();
            }
        }
Exemple #24
0
        /// <summary>
        /// Checks if the file or directory is ok for refactoring
        /// </summary>
        private bool IsValidFile(string file)
        {
            IProject project = PluginBase.CurrentProject;

            if (project == null ||
                !RefactoringHelper.IsProjectRelatedFile(project, file) ||
                !Regex.Match(Path.GetFileNameWithoutExtension(file), REG_IDENTIFIER, RegexOptions.Singleline).Success)
            {
                return(false);
            }
            if (Directory.Exists(file))
            {
                return(true);
            }
            return(FileHelper.FileMatchesSearchFilter(file, project.DefaultSearchFilter));
        }
Exemple #25
0
        public override async Task <Document> RefactorAsync(Document document, CancellationToken cancellationToken = default(CancellationToken))
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            BinaryExpressionSyntax coalesceExpression = RefactoringHelper.CreateCoalesceExpression(
                semanticModel.GetTypeSymbol(Left, cancellationToken),
                Right1.WithoutTrivia(),
                Right2.WithoutTrivia(),
                IfStatement.SpanStart,
                semanticModel);

            ExpressionStatementSyntax newNode = SimpleAssignmentStatement(Left.WithoutTrivia(), coalesceExpression)
                                                .WithTriviaFrom(IfStatement)
                                                .WithFormatterAnnotation();

            return(await document.ReplaceNodeAsync(IfStatement, newNode, cancellationToken).ConfigureAwait(false));
        }
Exemple #26
0
        private void RenameFile(IDictionary <string, List <SearchMatch> > results)
        {
            // We close previous files to avoid unwanted "file modified" dialogs
            ITabbedDocument doc;
            bool            reopen = false;

            if (AssociatedDocumentHelper.InitiallyOpenedFiles.TryGetValue(oldFileName, out doc))
            {
                doc.Close();
                reopen = true;
            }
            if (AssociatedDocumentHelper.InitiallyOpenedFiles.TryGetValue(newFileName, out doc))
            {
                doc.Close();
                reopen = true;
            }

            // name casing changed
            if (oldFileName.Equals(newFileName, StringComparison.OrdinalIgnoreCase))
            {
                string tmpPath = oldFileName + "$renaming$";
                RefactoringHelper.Move(oldFileName, tmpPath);
                RefactoringHelper.Move(tmpPath, newFileName);
            }
            else
            {
                var project = (Project)PluginBase.CurrentProject;
                FileHelper.ForceMove(oldFileName, newFileName);
                DocumentManager.MoveDocuments(oldFileName, newFileName);
                if (project.IsDocumentClass(oldFileName))
                {
                    project.SetDocumentClass(newFileName, true);
                    project.Save();
                }
            }

            if (results.ContainsKey(oldFileName))
            {
                results[newFileName] = results[oldFileName];
                results.Remove(oldFileName);
            }
            if (reopen)
            {
                PluginBase.MainForm.OpenEditableDocument(newFileName);
            }
        }
        public override async Task <Document> RefactorAsync(Document document, CancellationToken cancellationToken = default(CancellationToken))
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            int position = IfStatement.SpanStart;

            ITypeSymbol targetType = GetTargetType(position, semanticModel, cancellationToken);

            BinaryExpressionSyntax coalesceExpression = RefactoringHelper.CreateCoalesceExpression(
                targetType,
                Left.WithoutTrivia(),
                Right.WithoutTrivia(),
                position,
                semanticModel);

            StatementSyntax statement = CreateStatement(coalesceExpression);

            if (IfStatement.IsSimpleIf())
            {
                StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(IfStatement);

                SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

                int index = statements.IndexOf(IfStatement);

                StatementSyntax newNode = statement
                                          .WithLeadingTrivia(IfStatement.GetLeadingTrivia())
                                          .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia())
                                          .WithFormatterAnnotation();

                SyntaxList <StatementSyntax> newStatements = statements
                                                             .RemoveAt(index)
                                                             .ReplaceAt(index, newNode);

                return(await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                StatementSyntax newNode = statement
                                          .WithTriviaFrom(IfStatement)
                                          .WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(IfStatement, newNode, cancellationToken).ConfigureAwait(false));
            }
        }
Exemple #28
0
        /// <summary>
        /// Initializes a new instance of <see cref="Rename"/> class.
        /// </summary>
        /// <param name="target">The target declaration to find references to.</param>
        /// <param name="outputResults">If true, will send the found results to the trace log and results panel</param>
        /// <param name="newName">If provided, will not query the user for a new name.</param>
        /// <param name="ignoreDeclarationSource">If true, will not rename the original declaration source.  Useful for Encapsulation refactoring.</param>
        /// <param name="inline">Whether to use inline renaming.</param>
        public Rename(ASResult target, bool outputResults, string newName, bool ignoreDeclarationSource, bool inline = false)
        {
            if (target == null)
            {
                TraceManager.Add("Refactor target is null.");
                return;
            }
            Target        = target;
            OutputResults = outputResults;
            if (target.IsPackage)
            {
                isRenamePackage = true;

                string package = target.Path.Replace('.', Path.DirectorySeparatorChar);
                foreach (var aPath in ASContext.Context.Classpath)
                {
                    if (aPath.IsValid && !aPath.Updating)
                    {
                        string path = Path.Combine(aPath.Path, package);
                        if (aPath.IsValid && Directory.Exists(path))
                        {
                            TargetName        = Path.GetFileName(path);
                            renamePackagePath = path;
                            StartRename(inline, TargetName, newName);
                            return;
                        }
                    }
                }
                return;
            }

            isRenamePackage = false;
            TargetName      = RefactoringHelper.GetRefactorTargetName(target);

            // create a FindAllReferences refactor to get all the changes we need to make
            // we'll also let it output the results, at least until we implement a way of outputting the renamed results later
            findAllReferencesCommand = new FindAllReferences(target, false, ignoreDeclarationSource)
            {
                OnlySourceFiles = true
            };
            // register a completion listener to the FindAllReferences so we can rename the entries
            findAllReferencesCommand.OnRefactorComplete += OnFindAllReferencesCompleted;

            StartRename(inline, TargetName, newName);
        }
        private static InvocationExpressionSyntax GetNewInvocation(InvocationExpressionSyntax invocation)
        {
            ArgumentListSyntax argumentList = invocation.ArgumentList;
            SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

            if (arguments.Count == 1)
            {
                ArgumentSyntax argument = arguments[0];
                arguments = arguments.ReplaceAt(0, argument.WithExpression(StringLiteralExpression("").WithTriviaFrom(argument.Expression)));
            }
            else
            {
                arguments = arguments.RemoveAt(0);
            }

            return(RefactoringHelper.ChangeInvokedMethodName(invocation, "Fail")
                   .WithArgumentList(argumentList.WithArguments(arguments)));
        }
            static string Common(ScintillaControl sci, string sourceText, string newName)
            {
                SetSrc(sci, sourceText);
                var waitHandle = new AutoResetEvent(false);

                CommandFactoryProvider.GetFactory(sci)
                .CreateRenameCommandAndExecute(RefactoringHelper.GetDefaultRefactorTarget(), false, newName)
                .OnRefactorComplete += (sender, args) => waitHandle.Set();
                var end    = DateTime.Now.AddSeconds(2);
                var result = false;

                while ((!result) && (DateTime.Now < end))
                {
                    context.Send(state => {}, new {});
                    result = waitHandle.WaitOne(0);
                }
                return(sci.Text);
            }