Visual Studio macro to find a string and delete matching lines - visual-studio

In my Visual Studio (2010 C#) solution, I need to delete all lines of code that contain a matching string pattern.
For example, I want to delete all lines that contain ".BackColor = System.Drawing.Color.Yellow;". The Find and Replace feature of Visual Studio isn't good enough, because you cannot tell it to wipe out the matching lines.
So I think I would need a macro for that. Any help is appreciated.

You can use the "Find and Replace" feature of Visual Studio to delete matching lines.
The key is to match the whole line including the end of line character as well. You can do this in wildcard or regular expression mode. In wildcard mode, begin the expression with * and end the expression with *\n. The asterisks will match any number of characters, and the \n will match the end of line character.
In your case, your find query would be "*.BackColor = System.Drawing.Color.Yellow;*\n". The replace field should then be left blank.
To enable wildcard mode, select 'Wildcards' in the 'Use:' field of the 'Find options' section of the 'Find and Replace' dialog.

With Visual Studio 2015, 2017, 2019, 2022 this worked for me. Open Search window, check the "use regular expressions" checkmark. Fill "find what" with
.*myCodeFragmentHere.*\r?\n
fill "replace" with an empty string.
Remove all regexp (brackets, dots) from the code fragment in your search expression.

I tend to create macros in VS by running the macro recorder then editing the resulting code.
So, manually search for the pattern, and press F3. Stop the macro then (or press the line-start key, select to end of line, press delete and then stop the macro).
Edit the macro, the command to delete a line is:
DTE.ActiveDocument.Selection.SelectLine()
DTE.ActiveDocument.Selection.Delete()
You can set the find text with FindText:
DTE.ActiveDocument.Selection.FindText(".BackColor = System.Drawing.Color.Yellow;", vsFindOptions.vsFindOptionsFromStart)

Building upon #HolgerJeromin's answer: instead of guessing the right indentation match (could be tabs could be spaces could be more or less), I prefer matching the beginning of the line using the ^\s* pattern.
For example, to remove all lines having a ProducesResponseType attribute, I use
^\s*\[ProducesResponseType.*\n
(works on Windows too using VS 2019).

For Visual Studio 2015 (in which there are no macros and no wildcards), I did the following:
Open Find and Replace (Ctrl+H)
Set to use Regular Expressions (Alt+E)
Set the Find box to
({line of code string})\r?\n({next line tabbing})
Leave the Replace box empty
Replace
Where-
{line of code string} = the line of code you wish to remove. Note you need to escape characters such as parenthesis and quotes with a backward slash ()
{next line tabbing} = the number of spaces preceding the next line of code (without this your line will be removed but the next line would have double the spaces before it
For example, to remove
DoSomething("hello");
From -
class A
{
void SomeMethod()
{
DoSomething("hello");
DoSomethingElse();
}
}
Replace the following
(DoSomething(\"hello\")\;)\r?\n({ })

I was trying to remove an attribute ([OperationContract] in my case) and none of the other answers worked for me. I finally got it to work by using the following:
\[OperationContract\]\r\n\t\t (Use Regular Expressions)

Related

VS 22 - How to find in the code which lines have these two words

Visual studio 2022
How to find in the code which lines have these two words, example:
find line that has the word 'return' and 'xdto'
Line found: return Json(xdto);
I tried searching with ctrl+f and the text 'return*xdto'
You need to enable regular expressions (reg-ex) to use wildcards in searches.
Try ctrl-shift-f to search in all files.
If you need help with the syntax of regular expressions, do a search first and if the answer isn't there, post a new question with a reg-ex tag.
EDIT: sometimes reg-ex is indicated by a small button containing the symbols '.*'

ReSharper Keep existing line breaks not working

Under Formatting Style | Line Breaks and Wrapping | Preserve Existing Formatting I have "Keep existing line breaks" option checked. However, when I apply ReSharper Reformat Code function to file it removes my existing line breaks and places all the code in a statement on a single line.
Which setting could be annulling the "Keep existing line breaks" option and forcing the code on a single line?
I do have "Wrap long lines" under Line Wrapping unchecked but I don't think that should impact the "Keep existing line breaks" option.
Message = string.IsNullOrWhiteSpace(someString) ?
Properties.Resources.SomeResource : someBool ?
Message = Properties.Resources.SomeResource + Environment.NewLine + customMessage : customMessage;
After applying Reformat Code ReSharper function this statement with two line breaks becomes a single 240 character long line.
Visual Studio 2015
ReSharper 2017.1.3
I ran into a similar issue with the JetBrains CodeCleanup tool, take a look at the ternary operator formatting rules, for me it was the wrap_ternary_expr_style setting. I believe it's trying to fix the formatting of the ternary operator and since you don't have a max line length it condenses it down.

Visual Studio 'Find and Surround With' instead of 'Find and Replace'

So i want to surround all string literals in our C++ source with an _T(...) for our unicode port.
This questions answers how I search for string literals but is there some way of surrounding the matched text with _T() instead of replacing with something else?
I intend to do it one string at a time anyway and not all at once but want to avoid having to type it out or use "Surround With" from Visual Assist myself for each string.
Jochen Kalmbach's answer might work in older versions of Visual Studio, but it didn't work for me in Visual Studio 2013. However, the small RegEx shortcut buttons to the right of the Find/Replace input boxes helped a lot:
In Find, select the ":q Quoted string" option.
In Replace, select the "$1 Substitute the substring matched by captured group number 1", and then surround $1 with _T().
Final Output
Find:
((\".+?\")|('.+?'))
Replace:
_T($1)
Note that the $1 represents the RegEx expression group enclosed in the outermost parentheses.
Here's another example:
Requirement
Find:
Converter.toCustomObject($find("Anything"));
Replace (different Converter method and add parameter after $find() parameter):
Converter.toDifferentObject($find("Anything"), true);
Solution
Find (use RegEx in Find options):
Converter\.toCustomObject\((\$find\(.*)\);
Replace:
Converter.toDifferentObject($1, true);
Notice that the Replace value doesn't need to escape special characters, though you can apply some RegEx, e.g. to add a Line Break after the output, you can use this for Replace:
Converter.toDifferentObject($1, true);\r\n
Goto: Edit|Find and Replace...|Quick Replace..
Then enter:
Find: :q
Replace with : _T(\0)
Use: Regular Expressions

How to replace multiple lines in Visual Studio 2008

I need to do a find and replace, where I need to replace 2 lines at time. Does anyone know how to do this in the VS2008 IDE?
To clarify, i want to replace 2 lines with 1 line.
Many thanks
Thanks to František Žiačik for the answer to this one.
To perform a find/replace, replacing multiple lines, you need to switch on regular expressions and use a line break (\n) between your lines, also using (:b*) at the start of each line to handle any tabs or spaces tabs.
So to find:
line one
line two
you would search for ":bline one\n:bline two" (without the quotes)
Try Multiline Search and Replace macro for Visual Studio.
You can activate the 'Use regular expressions' in the find dialog, and use \n to match a newline.
In your case, type FirstLine\n:Zs*SecondLine.
:Zs* skips leading blanks on line 2.
For example ,\n:Zs*c matches a comma, newline, any number of blanks, a 'c'.

Visual Studio 2008: Find and Replace with new line character?

Sometimes i would like to search for text containing a new line character and there are other times i would like to replace text with a new line character.
How can i do this with visual studio 2008?
Use a RegEx search:
In the Find Dialog - Expand "Find Options"
Check the box for Use: Regular Expressions
Next to the search box there is now an arrow that is active, it will show you available RegEx options/values.
The value you want will be \n. So "SearchValue\n" should do it.
Be aware that that its not a standard RegEx that you use, it's VS specific.
Replace can also use the RegEx values.
Adding on to Brian Schmitt's answer...
Regular expression searches using \n work as expected. However you have to be a little careful when using \n in regex replaces with Visual Studio 2008. For example, if you search for \n and replace with \n (yes, the exact same thing) all of the line breaks in your file(s) will be converted to Unix-style newlines (LF). This may be a bug in Visual Studio. I find it hard to believe this is the intended functionality.
To get around this, you can use tagged expressions, using curly braces: e.g. search for SearchValue{\n} and replace with ReplaceValue\1. This ensures that the same line-break character(s) that were found when searching will also be used when replacing.
You can try my Multiline Search and Replace Macro.

Resources