This question already has answers here:
How can I reverse code around an equal sign in Visual Studio?
(6 answers)
Closed 4 years ago.
I have a bunch of assignment operations in Visual Studio, and I want to reverse them:
i.e
i = j;
would become
j = i;
i.e. replacing everything before the equals with what's after the equals, and vice versa
Is there any easy way to do this, say something in the regular expression engine?
Select the lines you want to swap, Ctrl+H, then replace:
{:i}:b*=:b*{:i};
with:
\2 = \1;
with "Look in:" set to "Selection"
That only handles C/C++ style identifiers, though (via the ":i"). Replace that with:
{.*}:b*=:b*{.*};
to replace anything on either side of the "=".
Also, since you mentioned in a comment you use ReSharper, you can just highlight the "=", Alt+Enter, and "Reverse assignment".
Just a slight improvement on Chris's answer...
Ctrl+H, then replace:
{:b*}{[^:b]*}:b*=:b*{[^:b]*}:b*;
with:
\1\3 = \2;
(better handling of whitespace, esp. at beginning of line)
EDIT:
For Visual Studio 2012 and higher (I tried it on 2015):
Replace
(\s*)([^\s]+)\s*=\s*([^\s]+)\s*;
with:
$1$3 = $2;
In Visual Studio 2015+ after selecting code block press Ctrl + H (Find & Replace window) and check "Use Regular Expression" option, then:
Find: (\w+.\w+) = (\w+);
Replace: $2 = $1;
For example:
entity.CreateDate = CreateDate;
changes to:
CreateDate = entity.CreateDate;
Thank you #Nagesh and Revious, mentioned details added.
The robust way to do this is to use a refactoring tool. They know the syntax of the language, so they understand the concept of "assignment statement" and can correctly select the entire expression on either side of the assignment operator rather than be limited to a single identifier, which is what I think all the regular expressions so far have covered. Refactoring tools treat your code as structured code instead of just text. I found mention two Visual Studio add-ins that can do it:
ReSharper
MZ-Tools
(Inverting assignment isn't technically refactoring since it changes the behavior of the program, but most refactoring tools extend the meaning to include other generic code modifications like that.)
Please see this question: Is there a method to swap the left and right hand sides of a set of expressions in Visual Studio?
My answer to that question has a macro that you can use to swap the assignments for a block of code.
I've improved the expression a little.
Replace
(\t+)(\s*)(\S*) = (\S*);
with
$1$2$4 = $3;
The reason is, it will look for lines starting with tab (\t). It will skip the lines starting with definition. E.g.:
TestClass tc = new TestClass();
int a = 75;
int b = 76;
int c = 77;
a = tc.a;
b = tc.b;
a = tc.c;
Would ignore the int a, int b and int c and swap only the assignments.
what about replace all (CTRL-H)
you can replace for example "i = j;" by "j = i;"
you can use regular expressions in that dialog. I'm not so sure about how you should pop-up help about them however. In that dialog, press F1, then search that page for more information on regular expressions.
I like this dialog because it allows you to go through each replacement. Because the chance of breaking something is high, I think this is a more secure solution
You can do search and replace with regular expressions in Visual Studio, but it would be safer to just do a normal search and replace for each assignment you want to change rather than a bulk change.
Unfortunatly I don't have Visual Studio, so I can't try in the target environment, but if it uses standard regexps, you could probably do it like this:
Search for "(:Al) = (:Al);", and replace with "\2 = \1". (\1 and \2 are references to the first and second capture groups, in this case the parenthesises around the \w:s)
EDIT
Ok, not \w... But according to MSDN, we can instead use :Al. Edited above to use that instead.
Also, from the MSDN page I gather that it should work, as the references seem to work as usual.
Related
I have Visual Studio 2019 (Community at home; Professional in the office). I also have ReSharper. I set up line length to be 120; indentation at 4, and autoformatting on close brace or semicolon. The language is C#
The problem is that indentation of the wrapped line is completely unpredictable (at least to me). Sometimes it is indented 4 characters as I expect; sometimes it is under a parenthesis or to the right of => or same operator (like &&). So, frequently wrapped line starts at character 80 or 90!
How can I make it always indent 4 characters from the previous line?
Needless to say that I tried a dozen of combinations of options under Visual Studio and Resharper Code Editing - Formatting options. Visual studio doesn't seem to have any option that would make it push the new line. Resharper has Parenthesis section under C# - Formatting style. But nothing makes wrapping simple
Example:
lstGroup.Select(s => new Group
{
...
Status = lookup.Where(w => w.LookupType == LookupConstants.CRIMETYPE &&
(int?)w.LookupIndex == (string.IsNullOrEmpty(s.TempCrimeType) ? 0
: Convert.ToInt32(s.TempCrimeType))).Select(w => w.LookupDescription).FirstOrDefault(),
...
});
(it may not be clear, but the lines don't run past char; so I would like it to stay this way!). After hitting semicolon at the end of the statement, it turns into
Status = lookup.Where(w => w.LookupType == LookupConstants.CRIMETYPE &&
(int?) w.LookupIndex == (string.IsNullOrEmpty(s.TempCrimeType)
? 0
: Convert.ToInt32(s.TempCrimeType))).Select(w => w.LookupDescription).FirstOrDefault(),
I'm not sure if you can completely simplify indents for wrapped statements/expressions, but the following options should make it much easier. If something still irritates you, please amend your question with examples.
Tabs, Indents, Alignment
Set all options in "Parenthesis" section to "Parenthesis and inside equally"
Turn off all options in "Align Multiline Constructs"
Brace Layout
Set "Expressions (initializers, switch expressions)" to "At next line indented (Whitesmiths style)"
Consider also to whether you want to also change "Lambda and delegate" to the same style
UPDATE: To prevent ReSharper from re-wrapping your code, go to "Line breaks and wrapping" page and look for options called "Wrap ..." with values "Chop if long or multiline" and "Chop always". Change them to "Simple wrap" as needed. You may also want to ensure that all "Keep existing arrangement..." options are turned on. Your particular example is influenced by a setting called "Wrap ternary expression".
I have a JavaScript line similar to:
var a = (b / 2) + (c / 2);
In Dreamweaver, it highlights this segment as a comment and treats it like this:
var a = (b /* 2 ) + (c */ 2);
It's incorrect syntax highlighting and very annoying. Where do I find syntax highlighting definitions and how do I modify them to correct this?
You can delete/modify the regex definition yourself by finding CodeColoring.xml in your Dreamweaver's configuration path. For CS6 in Windows 7, the default is:
C:\Program Files (x86)\Adobe\Adobe Dreamweaver CS6\configuration\
You will then need to find the JavaScript scheme:
<scheme MMString:name="JavaScript/scheme/name" id="JavaScript" ...>
And within it, you'll find the regexp definition:
<regexp name="RegExp" id="CodeColor_JavascriptRegexp" delimiter="/" escape="\\">
<searchPattern><![CDATA[/\e+\\/]]></searchPattern>
</regexp>
This can probably be refined, but I don't use regular expressions in most scenarios so I just deleted this segment. Restart DW, and voila.
If you want to refine the definition, StackOverflow seems to have its regex highlighting down:
var regex = /a+b/;
var number = (window.innerWidth / window.innerHeight) / 2;
This article explains how to do it:
Modifying Dreamweaver’s syntax highlighting
http://realworldz.wordpress.com/2007/10/04/modifying-dreamweavers-syntax-highlighting/
It gives an example of how to add syntax highlighting to the keyword new for VBScript:
Close Dreamweaver if it’s already open.
Go to C:\Documents and Settings\<YOUR USERNAME>\Application Data\Macromedia\Dreamweaver 8\Configuration\CodeColoring
Open the “ASP VBScript.xml” file in Notepad.
Look for the tags and after the one for “Mod”, add in a new one called for the keyword “New” like this; <keyword>New</keyword>
I have looked everywhere and I agree with the answer from this previous question: Dreamweaver CS5 code hinting
There is just not that much control over syntax highlighting. You can use the method described by Robert's answer here to add more reserved words and such. But editing that file does not apply to changing how Dreamweaver handles highlighting of constants and operators.
Here is a reasonable way to change the way you write you code so that you syntax will still be highlighted in examples like this.
<script>
var a =
(b/2) //Because the forward slashes are not on the same line,
+(c/2); //Dreamweaver will not stop highlighting the numbers
//and operators
document.write(a);
</script>
Note: in this specific example your code can also be simplified to var a = (b+c)/2;
Since the characters /([{;,=!|&~^<>+-*%?:} can't be followed by a division sign, this is what I came up with:
<searchPattern><![CDATA[/\s+/\e+\\/]]></searchPattern>
(this one must have at least one whitespace character to avoid conflicts with end-of-line comments)
<searchPattern><![CDATA[(\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[[\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[{\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[;\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[,\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[=\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[!\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[|\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[&\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[~\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[^\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[<\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[>\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[+\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[-\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[*\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[%\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[?\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[:\s*/\e+\\/]]></searchPattern>
<searchPattern><![CDATA[}\s*/\e+\\/]]></searchPattern>
For scenarios like if (x) /foo/.exec('bar'), just put the RegExp in parenthesis to format it properly. The only other ill effect is that the preceding character will just be formatted as regular text (not bold or colored).
I wrote some code and tried the Ctrl + T to check transpose feature in visual studio.
Just to check if CTRL + Shift + T does the reverse for this Transpose... I tried pressing Ctrl + Shift + T.
and it just messed up everything...
Can anyone tell me what exactly this Ctrl + Shift + T does (especially with a block) ?
For instance:
public string returnDateTimeToMyformat(DateTime dt)
{
dt = dt.AddYears(-1);
return dt.ToString("yyyy MM dd HH mm ss");
}
To:
string returnDateTimeToMyformat publicdtDateTime (dt
{
dt = )1AddYears(-.return;
dt ).ToString("yyyy MM dd HH mm ss");
}
(I started with my cursor right after 'public')
Since CTRL-T swaps the two characters on either side of the cursor, the opposite of it is ...
wait for it ...
CTRL-T
:-)
CTRLSHIFTT transposes the two words after the cursor.
What it's doing to your block seems rather bizarre. It appears to doing it to multiple parts of each line. My only advice would be (as the doctor said to the patient who complained it hurts when banging their head against a wall): Don't do that.
As others have pointed out, the two words following the cursor are transposed, and the cursor is placed after the words that have been transposed. However, Visual Studio 2010 at least appears to ignore commas and other punctuation when considering "words." One utility of this, then, is that you can reorder something like an enum. For instance,
typedef enum myEnum
{
ThingOne,
ThingThree,
ThingTwo
};
Put the cursor somewhere near ThingThree and press CtrlShiftT to get:
typedef enum myEnum
{
ThingOne,
ThingTwo,
ThingThree
};
This could be a good thing if you decide that a different order for your enums is better. You can also use this to help idiot-proof comparisons and/or quickly and easily format them to a better coding standard.
if ( ptr == NULL ) { /* stuff */ }
is considered bad (never mind that having an "if" on its own line is also bad) since you could easily write (or read) "ptr = NULL" by accident. You're better off with
if ( NULL == ptr ) { /* stuff */ }
So, if you did it wrong the first time, just select the offending expression and...CtrlShiftT to the rescue!
...Yeah, okay, so this thing isn't that useful.
Edit: Hmm, I should add that the behavior is a little weirder when your cursor is placed immediately before a punctuation symbol (such as a left-parenthesis), hence the weird result you got when you repeatedly hit CtrlShiftT on your code snippet. It seems to just swap any whitespace-terminated string after the cursor with the next alphanumeric "word," skipping over any punctuation symbols in between. The result is often difficult to read, though, so I'm not going to claim that's the exact pattern.
According to this website:
Transposes the two words that follow
the cursor. (For example, |End Sub
would be changed to read Sub End|.)
The only question that remains is probably: WHY??
Well it might become handy when you have a block of code lines where variables are assigned values. (For example Load/Save) In the opposite function, you want to do the opposite assignment, maybe this shortcut can be used in such a situation...
With this Visual Studio Document Reopen cool extension CTRL+SHIFT+T you can reopen the last closed document(s). It works like in Web browsers.
I have a common issue when working with code in the IDE:
string.Concat("foo", "bar");
and I need to change it to:
string.Concat("bar", "foo");
Often I have several of these that need to be swapped at once. I would like to avoid all the typing. Is there a way to automate this? Either a shortcut or some sort of macro would be great if I knew where to start.
Edit: changed to string.Concat to show that you can't always modify the method signature. I am only looking to change the order of the params in the method call, and nothing else.
<Ctrl> + <Shift> + <t> will transpose two words, so it would work in your case. Unfortunately I don't see this working (without multiple presses) for functions with larger parameter lists...
I had a lot of code with this function:
SetInt(comboBox1.Value + 1, "paramName", ...
SetInt(comboBoxOther.Value, "paramName", ...
And I needed to swap only the first two parameters;
I ended up using some text editor with regular expression management (like Scite), and using this one saved me hours:
Find: SetInt(\([.a-z0-9]+[ + 1]*\), \("[a-z0-9]+"\)
Replace: SetInt(\2, \1
I have a lot of custom keyboard shortcuts set up. To avoid having to set them up every time I install a new visual studio (happens quite a lot currectly, with VS2010 being in beta/RC) I have created a macro, that sets up all my custom commands, like this:
DTE.Commands.Item("ReSharper.ReSharper_UnitTest_RunSolution").Bindings = "Global::Ctrl+T, Ctrl+A"
My main problem is that Ctrl+T is set up to map to the transpose char command by default. So I want to remove that default value in my macro.
I have tried the following two lines, but both throw an exception
DTE.Commands.Item("Edit.CharTranspose").Bindings = ""
DTE.Commands.Item("Edit.CharTranspose").Bindings = Nothing
Although they kind of work, because they actually remove the binding ;) But I would prefer the solution that doesn't throw an exception.
How is that done?
I have coped with the same issue. I use a macro to assign key bindings for a set of align macros.
Dim NewBindings() = {"Global::Alt+="}
DTE.Commands.Item("Macros.Dev.AlignUtils.AlignEquals").Bindings = NewBindings
NewBindings(0) = "Global::Alt+Num -"
DTE.Commands.Item("Macros.Dev.AlignUtils.AlignMinus").Bindings = NewBindings
...
And to remove key bindings i use the following statements :
Dim DelBindings() = {}
DTE.Commands.Item("Macros.Dev.AlignUtils.AlignPlus").Bindings = DelBindings
It works fine under Visual Studio 2005.
I followed a little more pragmatic way (using your example):
DTE.Commands.Item("ReSharper.ReSharper_UnitTest_RunSolution").Bindings = "Global::Ctrl+T"
DTE.Commands.Item("ReSharper.ReSharper_UnitTest_RunSolution").Bindings = "Global::Ctrl+T, Ctrl+A"
With the first assignment Ctrl+T is unassigned from any other function and then becomes unbound with the second assignment.
Works like a charm for me.
You do not need to change it with macro, Just go to
Menu>Tools>Options -- Keyboard and then select what you want to change the shortcut from the dropdown and assignyour desiered short cut