Is there a keyboard shortcut or fast way to change the code below to a single line in Visual Studio 2013? I also have ReSharper installed.
Multi
new XElement("Option",
new XAttribute("Name", "FileDelete"),
"1"
),
Single
new XElement("Option", new XAttribute("Name", "FileDelete"),"1" ),
Just select all the text
and press (control + j)
and it will become 1 line of code
I setup find/replace for quick use with a regex expression like so:
(note: I use VS 2015, so your hotkeys may be different)
Use Ctrl+H to open quick find replace.
Make sure the "Use Regular Expressions" button is active/toggled-on, and that you are set to search in "Selection" (Not "Document" or "Entire Solution" or whatever)
Type
\s+
and a space ()
in the "find" and "replace with" boxes respectively.
Press Esc key to exit quick find/replace.
Now, as long as you don't change anything, you can select any text you want to make single line, and use the following hotkey sequence to quickly format it:
Ctrl+H (Open quick find/replace)
Alt+A (Replace any occurrence of 1 or more White Spc chars with a single space.)
Enter (Close the popup window that says "X Occurrences Found")
Esc (Exit quick find/replace and return to your code)
I use this all the time after visual studio does things like implementing interfaces to turn stuff like
public SomeType SomeProperty {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
into stuff like
public SomeType SomeProperty { get { return someField; } set { /*Some Simple Set Code*/; } }
For VS2019, default binding is set to Shift + Alt + L + J
Or you could rebind this to something else by going to Tools -> Options -> Keyboard -> search for 'join'
Rebind Edit.JoinLines action to something like (Text Editor) Ctrl + J then press Assign
To make it with ReSharper, you should uncheck the option "Keep existing line breaks" in ReSharper/Options/Code Editing/C#/Formatting style/Line Breaks and Wrapping.
Or just add this line into your .dotSettings
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_USER_LINEBREAKS/#EntryValue">False</s:Boolean>
Then you could format your code using Code Cleanup Tool (default shortcut is Ctrl+Alt+F) or just by typing semicolons or braces.
For me doing Ctrl + J opens the Linux terminal and does not format multiple lines to one line.
This is the fastest way on Linux
Hit Ctrl + Shift + P
Join Lines
You can change your VS settings to automatically format code in whatever way you want, then select and retype any line/block-ending character (';' or '}') after the text you want formatted and VS will format it for you.
You can accomplish this using CodeMaid. The default keybinding is F3, but the command is called CodeMaid.JoinLines if you want to change it
Related
Normally, to create a new bracket block I would type:
"{" then enter
This produces:
{
}
however, (I have seen this on two different machines so far, it might be the default setting) if like me, you like to keep shift held down, or accidentally keep it down and instead press shift + enter, it creates a new line underneath.
{ }
//current cursor position
Leaving the un-formatted brackets behind!
This is really annoying as I nearly always do this, and have to fiddle around for a little second to get the brackets back to where I want them. What can I do to change the behavior of shift + enter?
Go to Options > Environment > Keyboard
Search for Edit.SmartBreakLine and remove the assigned shortcut (Shift + Enter)
Search for Edit.BreakLine, click on "Press shortcut keys:" textbox, press Shift + Enter and click Assign
If it doesn't work try restarting Visual Studio.
Update: This issue is fixed in Visual Studio 2015 Update 1 - SmartBreakLine works as expected.
We stumbled on this thread and it felt like we could make a nice improvement here to Shift+Enter (SmartBreakLine).
So, in cases where a block was opened { } and if shift was held down intentionally or unintentionally, we now do this:
{
|
}
instead of
{ }
|
this way people who are used to using shift+enter to complete the line (in C#, it adds a semicolon to the end of line if needed, formats the line, adds a new line after current line) do not have to lose those functionalities by remapping the shortcut to BreakLine.
See: https://github.com/dotnet/roslyn/pull/5790
this should make it in the next update of Vs2015 and we hope you like it.
It works well in my VS 2015. Try resetting all the settings.
Tools > Import and Export Settings > Reset all settings > Next > Visual C#
You can reset for all other languages similar like this.
Hope this helps!
I know that Ctrl+} will take you to the corresponding brace in Visual Studio, but say I'm in the middle of a gigantic function and I don't know where the top or the bottom is, is there a shortcut to get directly to the function declaration?
void function()
{
//so many lines of code
//can't see the top or the bottom curly brace
//can i get to the top of the function with a shortcut?
}
I have a fresh install of VS2017. As of 15.9.1, the default for me is Alt+Shift+[.
This is the shortcut for EditorContextMenus.Navigate.GoToContainingBlock. So you may have to execute this shortcut multiple times if you are a few block layers deep, but it'll get you where you want to go.
Alt+Ctrl+UP,Tab,Tab,Enter
This sequence will move you through Project selctor > Scope selector > Function selector > Current Function.
Ctrl+M,Ctrl+M
This sequence will toggle between collapse/expand current block.
Place cursor at any line that is immediately enclosed by the function. Collapse. Place cursor at the end of the collapsed function, i.e after { ... }. Expand the function to get to its last brace.
Note:
If you have difficulty in finding a line immediately enclosed by the function(for example, when the function has lots of nested blocks), you can always goto the beginning to collapse the function.
Update
With last updates Visual Studio, now default keyboard shortcut for EditorContextMenus.Navigate.GoToContainingBlock is Shift+Alt+[
Old Answer:
Visual Studio 2017 version 15.8.0 comes with a new shortcut Ctrl + Alt + UpArrow - Go to Enclosing Block.
Go to Enclosing Block (Ctrl + Alt + UpArrow) allows you to quickly
navigate up to the beginning of the enclosing code block.
Source
This command allows also move to function declaration if you are inside function.
If shortcut doesn't work for you
For the VSCode lovers, this key combination will bring you to the top of the function:
Ctrl-Shift-.
followed by ENTER
and for MAC users:
Cmd-Shift-.
followed by ENTER
I usually double press the white line that is located left of the code.
It closes the function but it also takes you to the declaration of the function.
You can do it with Macros for Visual Studio extension.
Here's the code for macros:
// BeginningOfFunction moves the caret to the beginning of the containing definition.
var textSelection = dte.ActiveDocument.Selection;
// Define Visual Studio constants
var vsCMElementFunction = 2;
var codeElement = textSelection.ActivePoint.CodeElement(vsCMElementFunction);
if (codeElement != null)
{
textSelection.MoveToPoint(codeElement.GetStartPoint());
dte.ActiveDocument.Activate();
}
It is one of the sample macros of the extension. Edited it a little, because for some reason sample didn't work for me. You can get to the end of the function by changing codeElement.GetStartPoint() to codeElement.GetEndPoint().
I found one trick in visual studio:
Place the cursor on the empty to get the context (name of the function), copy the name of the function, then click the drop down arrow where all functions will be listed, paste the function name, enter. Then you are at the beginning of that function!
Another alternative would be to use Edit.PreviousMethod. I prefer this option because even if your cursor lies in multiple nested block, you can get to the method definition in single keystroke! I have mapped Edit.PreviousMethod to ctrl + alt + , and Edit.NextMethod to ctrl + alt + . but you can set it to whatever you prefer.
To setup key binding, goto Tools.Options.Environment.Keyboard, then in Show Commands Containing textbox type edit.previousmethod, set focus on Press Shortcut Keys textbox and press the key combination you want, the hit Assign. Repeat for edit.nextmethod, then Ok.
I couldn't find such feature in VS's shortcut list. Is there anyway?
If you want to copy a line, simply place cursor somewhere in that line and hit CTRL+C
To cut an entire line CTRL+X
#Sean found what I was looking for:
To disable this default behavior remove the checkmark (or check to re-enable)
Apply cut or copy commands to blank lines when there is no selection
Accessed from the menu bar: Tools | Options | Text Editor | All languages
You can also enter copy into the options search box for quicker access
[Tested in VS2008, 2010, 2017]
Clicking the line 3 times does the trick
If you have ReSharper you could use
Ctrl + W
- Extend Selection
Sidenote: You may have to use it multiple times depending on the context of your present text cursor position.
If you click once on the row number the entire row will be selected.
If you want to select a line or lines you can use the combination of ctrl + E then U. This combination also works for uncommenting a complete line or lines. This combination looks somewhat strange to work with, but it will get habituated very soon :)
You can also use Ctrl + X to cut an entire line. Similarly, you can use Ctrl + C to copy an entire line.
As long as you don't have anything selected, these commands will work on the entire line.
Clicking anywhere on the line and (CRTL + C) will copy entire line.
Clicking three time in quick succession also selects entire line.
There is a simple way of doing it, simple use Home or End button to reach the start or end of line, and then use home + shift or end + Shift depending on where your cursor is. Hope it helps.
Use the following:
Shift + End If cursor is at beginning of line.
or
Shift + Home If cursor is at the end of the line.
Alternatively, if you use resharper, you can also use the following
Ctrl + w while the cursor is positioned on the line you want to select
This won't solve the problem for Visual Studio, but if you're using Visual Studio Code you can use CTRL+L to select the line your cursor is currently on.
(If you're using Visual Studio, this will cut the line you're currently on—which may also be useful, but wasn't the question.)
Other answers require either using a mouse or hitting more than one combination.
So I've created a macro for those who want a VSCode-like Ctrl+L behaviour. It can select multiple lines, and that's useful for moving blocks of code.
To use it, install Visual Commander extension for macros: https://marketplace.visualstudio.com/items?itemName=SergeyVlasov.VisualCommander
Then create a new command, select C# as a language and paste this code:
using EnvDTE;
using EnvDTE80;
public class C : VisualCommanderExt.ICommand
{
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
var ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
if (!ts.ActivePoint.AtStartOfLine)
ts.StartOfLine();
ts.LineDown(true, 1);
}
}
Now you can assign a desired shortcut in preferences:
Tested in VS 2022.
You can use CTRL + U . This shortcut is use also for uncomment.
You can change the shortcut on this feature. Go to Tools->Options->Environment->Keyboard->Edit.UncommentSelection and assign CTRL+W (same as Resharper) or you can use what shortcut do you want.
If you want to select full row Ctrl E + U
Just click in the left margin.
If you click in the margin just left of the Outline expansions [+][-]
it will select the row.
You can also just click and drag to select multiple lines.
Necvetanov eluded to this in his answer above about clicking on the line number.
This is right...but it just happens that the line number is in the margin.
Here is a whole list of the keyboard shortcuts Default keyboard shortcuts in Visual Studio
a work around for this:
ctrl+d = duplicate line
ctrl+l = copy line
ctrl+v = paste copied text
You can enter, home then shift + end as well. What it will do is take you to the beginning of line then select the whole line till end. Or alternatively first enter end then shift + home
You can set a bind to the Edit.ExpandSelection command:
In the options. Click the shortcut until it selects the whole line.
The screenshot above is from the Edit > Advanced menu in Visual Studio 2022. I set this Alt+E, E shortcut myself and I don't remember if it's originally set to something or not.
Simply by clicking on the line number that's being shown on the left in vs-code. just a single click and a line will get selected.
In Mac, it is ⌘+L.
But if you have some specific conflicting keybindings, this won't work. In my case the VSCode Live Server extension auto registered a couple of bindings for these keys. I removed them and it worked.
I assigned a shortcut key to the following functionality. I press the shortcut until it selects the whole current line:
Edit.SubwordExpandSelection
Just wondering if anyone knows the keyboard shortcut to swap around two sides of a statement. For example:
I want to swap
firstNameTextbox.Text = myData.FirstName;
to
myData.FirstName = firstNameTextbox.Text;
Does anyone know the shortcut, if there is one? Obviously I would type them out, but there is a lot of statements I need to swap, and I think a shortcut like that would be useful!
Feel free to throw in any shortcuts you think are cool!
My contribution would be CTRL + E, D - this will format your code to Visual Studio standards! Pretty well known I'm guessing but I use it all the time! :)
UPDATE
Just to let everyone know, using a bit of snooping of the article that was posted, I managed to construct a regular expression, so here it is:
Find:
{.+\.Text = myData\..+};
And replace with:
\2 = \1;
Hopefully people can apply this to their own expressions they want to swap!
I think the following thread is a good place to begin with
Invert assignment direction in Visual Studio
Here's how I would go about doing that without a specific keyboard shortcut:
First, select the text you want to modify and replace
" = " with " = "
(the key here is to add a lot of spaces).
If you hold down Alt and use the mouse, you can select a "block" of code. Use this to select only the text on the right side of the equation (it's helpful to add extra white space here in your selection)
Use the same Alt + Left-Click combination to select the beginning of the left side (just select a blank area). You should be able to paste text into here.
If you added extra white space to the text you just added, just should be able to easily insert an = using the Alt + Click technique. Use the same trick to remove the equal sign that's dangling on the right side of your code block.
While this might not do exactly what you're looking for, I've found these tricks quite useful.
If you're using ReSharper, you can do this by pressing CtrlAltShift + ← or →
The feature is in Resharper. Select the code segment and click the content wizard, which is a pencil icon in the left corner reading View Actions List, then choose Reverse Assignment.
It is done.
swap-word is a VSCode extension which sounds like it would do what you want.
Quickly swap places two words or selections...
But I'm not sure if it is compatible with VS.
Since I was not happy with the answers where I need to enter complicated strings into the Visual Studio search/replace dialog, I wrote myself a little AutoHotkey script, that performs the swaps with only the need to press a keyboard shortcut. And this, no matter if you are in VS or in another IDE.
This hotkey (start it once simply from a textfile as script or compiled to exe) runs whenever Win+Ctrl-S is pressed
#^s Up::
clipboard := "" ; Empty the clipboard
Sendinput {Ctrl down}c{ctrl up}
Clipwait
Loop, Parse, clipboard, `n, `r ; iterates over seperates lines
{
array := StrSplit(RegExReplace(A_LoopField,";",""),"=") ; remove semicolon and split by '='
SendInput, % Trim(array[2]) . " = " . Trim(array[1]) . ";{Enter}"
}
return
Many more details are possible, e.g. also supporting code where lines end with a comma
...and I can put many more hotkeys and hotstrings into the same script, e.g. for my most mistyped words:
::esle::else ; this 1 line rewrites all my 'else' typos
I recommend using the find-replace option in Visual Studio. IMHO the REGEX string is not that complicated, and moreover, you don't need to understand the expression in order to use it.
The following regex string works for most programming languages:
([\w\.]+)\s*=\s*([\w\.]+)
For Visual Studio's you want to use $ argument in the replace text.
$2 = $1
Make sure to enable regex.
To do this in one shot, you can select a section of the document, and click the replace-all option.
Before:
comboBoxAddOriginalSrcTextToComment.SelectedIndex = Settings.Default.comboBoxAddOriginalSrcTextToComment;
comboBoxDefaultLanguageSet.SelectedIndex = Settings.Default.comboBoxDefaultLanguageSet;
comboBoxItemsPerTransaltionRequest.SelectedIndex = Settings.Default.comboBoxItemsPerTransaltionRequest;
comboBoxLogFileVerbosityLevel.SelectedIndex = Settings.Default.comboBoxLogFileVerbosityLevel;
comboBoxScreenVerbosityLevel.SelectedIndex = Settings.Default.comboBoxScreenVerbosityLevel;
After:
Settings.Default.comboBoxAddOriginalSrcTextToComment = comboBoxAddOriginalSrcTextToComment.SelectedIndex;
Settings.Default.comboBoxDefaultLanguageSet = comboBoxDefaultLanguageSet.SelectedIndex;
Settings.Default.comboBoxItemsPerTransaltionRequest = comboBoxItemsPerTransaltionRequest.SelectedIndex;
Settings.Default.comboBoxLogFileVerbosityLevel = comboBoxLogFileVerbosityLevel.SelectedIndex;
Settings.Default.comboBoxScreenVerbosityLevel = comboBoxScreenVerbosityLevel.SelectedIndex;
IMHO: It's better for a developer to learn to use the IDE (Integrated Development Environment), then to create new tools to do the same thing the IDE can do.
I already know about Ctrl + L to delete an entire line...is there one to just select an entire line (which I can then copy and paste somewhere else...)
You can also use Ctrl + X to cut an entire line. Similarly, you can use Ctrl + C to copy an entire line.
As long as you don't have anything selected, the command will work on the entire line.
Hit
Home
Shift + End
You can do it with Shift + DownArrow.
Yes there is. If you are in the begining of the line press Shift+ End.
If you are in the end of the line press Shift+ Home.
Hope that helps
I believe, if you don't have any selection and press Ctrl + C, it would copy the line.
Shift + End = Select between cursor and the end of the line
It's Home+Home, then Shift+Down for me.
Or you change that setting which makes Ctrl+C with no selection copy the line. But I hate that, so I always turn it off. (Thanks to Bala for providing the link to that setting!)
To cut a line, Ctrl+L works in my keyboard settings.
There's also Alt-Up and Alt-Down to move whole lines. It's two fewer keystrokes than using Ctrl-X, and unlike Ctrl-X, it also moves multiple whole lines at a time if your selection covers multiple lines even partially. It's also nice because the feedback is instantaneous, unlike Ctrl-X where you can never remember whether the pasted line will go above or below your cursor.
I saw this and thought I'd never use the feature. But once I got used to it I use it all the time. There's no easier way to move a block of code than using Shift-Up/Down to select the lines, press Alt-Up/Down a few times to move them, and then use Tab to adjust the indentation.
Of course it only works within the same file though.
Visual Studio macros are another way to do these types of operations if you can't find an existing command. A simple way to create one is:
Use the Record TemporaryMacro option (under Tools/Macros).
Select the line however you prefer (e.g., home, shift, end).
Click Stop Recording (under Tools/Macros).
Choose Save TemporaryMacro (under Tools/Macros).
Then choose Tools/Customize/Keyboard and assign a shortcut to the macro.
It's not specifically a keyboard shortcut, but a triple-click will select a whole line of code.
This works in some other areas of Windows as well. In Chrome, for example, double-click selects a word, but triple-click selects a paragraph.
(This works in Visual Studio 2013 on Windows 7. Not sure about other versions/platforms.)
I use Ctrl + Insert to copy entire line, and Shift + Insert to paste entire line.
Other answers require either using a mouse or hitting more than one combination.
So I've created a macro for those who want a VSCode-like Ctrl+L behaviour. It can select multiple lines.
To use it, install Visual Commander extension for macros: https://marketplace.visualstudio.com/items?itemName=SergeyVlasov.VisualCommander
Then create a new command, select C# as a language and paste this code:
using EnvDTE;
using EnvDTE80;
public class C : VisualCommanderExt.ICommand
{
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
var ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
if (!ts.ActivePoint.AtStartOfLine)
ts.StartOfLine();
ts.LineDown(true, 1);
}
}
Now you can assign a desired shortcut in preferences:
Tested in VS 2022.
Triple-click to select the whole line. Then do what you want.
You can press Home + Shift + End to select the whole line as well.
If you want to copy the whole line then just press Ctrl + C. It will copy the whole line if nothing is selected.