Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's The Best Way To Write Multi-Line Code Snippets In VS-Code?

In Sublime Text, multi-line code snippets can be defined with white-spaces in a snippet file.

But as far as I know, VS-Code needs a JSON entry. These require either:

  1. Hard-breaks into a list of double-quoted strings, or
  2. Soft-break a long string using line-breaks \n

This is inconvenient compared to the WYSIWYG approaches other IDEs provide out of the box.

Are there better ways for defining long-blocks of code?

like image 897
kakyo Avatar asked Jan 25 '17 16:01

kakyo


People also ask

How do you write multiple lines of code in VS code?

Select the lines you want and then press: Windows: Shift + Alt + i. Mac: shift + option + i.

How do you write Vscode snippets?

To create or edit your own snippets, select User Snippets under File > Preferences (Code > Preferences on macOS), and then select the language (by language identifier) for which the snippets should appear, or the New Global Snippets file option if they should appear for all languages.


2 Answers

You can define the body of your snippet as an array of strings, each beginning on a new line.

Like this:

  "Create for loop":{     "prefix": "mkfor",     "body":[       "for(int i = 0; i < 3; i++)",       "{",       "   //code goes here",       "}"     ],    "description": "Creates a for loop"   } 

or if you install Easy Snippet Maker extension, you can create your snippets by highlighting texts.

like image 145
Armin Avatar answered Oct 28 '22 22:10

Armin


You can check out this video for a quick short tutorial

https://youtu.be/g1ouTcFxQSU

Go to File --> Preferences --> User Snippets. Select your preferred language.
Now type the following code to make a for loop snippet:

  "Create for loop":{     "prefix": "for",     "body":[       "for(int i = 0; i < 10; i++)",       "{",       "   //code goes here",       "}"     ],    "description": "Creates a for loop"   } 

You are done.
Type "for" in the editor and use the first prediction.

SHORTCUT--

  1. install Snippet-creator extension.
  2. Highlight the code that you need to make snippet.
  3. press ctrl+shift+P and type "Create snippet" on the command palette and press ENTER.
  4. select language for which you want to create snippet(eg:-CPP), then type
    snippet name, type snippet shortcut and then type snippet description.
    You are now good to go.
    Type the snippet shortcut in the editor that you entered in step 4, and select the
    prediction (if no prediction comes press ctrl+space) that comes first.

Hope this helps :)

Note: goto File->Preferences->User Snippets. Then select the language in which you
created the snippet. You will find the snippet there.

like image 28
vinod Avatar answered Oct 28 '22 20:10

vinod