Marko Grdinić
Marko Grdinić

Reputation: 4062

Visual Studio - Is there a shortcut to insert parentheses around a selection?

I am playing with Atom and I really like how I can select an expression and press Shift+9 to insert ( and ) outside it. This is convenient for Haskell and I would like the same for F#. Is there a shortcut for this?

Upvotes: 30

Views: 26622

Answers (4)

MHebes
MHebes

Reputation: 3207

Released February 13th, 2024, Visual Studio 2022 17.9 supports this feature.

Auto Surround with Quotes or Brackets You can now easily surround a selection with bracket delimiters including: “double quotes”, ‘single quotes’, and (parentheses). Just select an area of code and press the relevant key.

To enable or disable this feature, go to Tools > Options > Text Editor and check the “Automatically surround selections when typing quotes or brackets” option.

Upvotes: 4

NutCr4cker
NutCr4cker

Reputation: 91

Stumbled upon this when searching parenthesis surrounding for C# in VS2022. Another free method (non-hacky) to add in Dan Cundy's list: Auto Surround extension available for Visual studio 2022

Upvotes: 9

Dan Cundy
Dan Cundy

Reputation: 2849

Paid Method

You should check out a third party add-in like Resharper. They bundle a such abilities.

Resharper

Free Method

There is another method noted by @Igor Zevaka.

Here: Any way to surround code block with Curly Braces {} in VS2008?

This allows you to create a snippet, and use a shortcut to use it.

Here is a quick and dirty snippet to do just that.

To Install:

Save the code as SurroundWithBraces.snippet into "\Visual Studio Version\Code Snippets\Visual C#\My Code Snippets"

To use:

Select block of text. Press Ctrl+K, Ctrl+S Chose My Code Snippets, braces

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>braces</Title>
      <Shortcut>braces</Shortcut>
      <Description>Code snippet to surround a block of code with braces</Description>
      <Author>Igor Zevaka</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Code Language="csharp">
        <![CDATA[{
        $selected$ $end$
     }]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Upvotes: 6

Lorien Brune
Lorien Brune

Reputation: 881

This is an in-built option in Visual Studio 2017. Go to Tools -> Options -> C / C++ -> Advanced, then navigate within the options dialog as shown on the screenshot below.

Set the Enable Surround with Parentheses option to True.

This works for C++, but the process ought to be similar for other languages.

Once you click OK, you should be able to automatically insert parentheses around any selected text by typing only the first (

Visual Studio 2017 Text Editor Options

Upvotes: 28

Related Questions