54

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?

kakyo
  • 10,460
  • 14
  • 76
  • 140

7 Answers7

53

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.

Félix Paradis
  • 5,165
  • 6
  • 40
  • 49
Armin
  • 2,397
  • 2
  • 21
  • 31
  • 10
    Thanks. The snippet you gave here is the exact problem in my question: I don't want multiple double-quoted strings with commas. I'll give that extension a try. – kakyo Apr 02 '17 at 02:33
  • Have you found a better solution to creating multiple lines without using a string for each line with comma? – Paulliano Jun 16 '23 at 09:54
21

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.

vinod
  • 766
  • 6
  • 11
9

I cannot find a good way to create multi-line snippets either. It's probably one of the features I'd like to see improved the most. As another answer suggested, there are a couple extensions out there to help with Snippet creation (like this and this). However, they don't escape literal dollar signs and indentation isn't great.

When browsing for answers to this, I stumbled across a Pen by Denis Malinochkin (linked from this issue). However, it also did not escape dollar signs properly, so I forked it and added this line to handle literal dollar signs. Here it is: https://codepen.io/cbejensen/pen/WXLxaE

Hope that helps!

P.S. - This is the line I added:

line = line.replace(new RegExp(/\$/, 'g'), '\\$');
Christian Jensen
  • 900
  • 1
  • 10
  • 25
  • Thanks! That's crazy that one must hack to make this work. – kakyo Dec 03 '17 at 12:59
  • 1
    Note that the reason why the [original pen](https://codepen.io/mrmlnc/pen/GqrqPg) didn't escape dollar signs, because VS Code uses `$1`, `$2`, etc to position the cursor after you've activated the snippet – antoine Sep 19 '18 at 18:48
  • Good point, can't believe I overlooked that! I've updated the pen to account for numbers following dollar signs, though of course many snippets may want literal dollar signs before numbers. I guess there's no great way to account for literal dollar signs and I probably should have left the original pen as it was. – Christian Jensen Oct 02 '18 at 19:39
5

I've created an extension to store snippets in a markdown file:

demo_image

https://marketplace.visualstudio.com/items?itemName=usernamehw.snippets-in-markdown

Alex
  • 59,571
  • 22
  • 137
  • 126
2

Hit cmd+shift+p on mac machine, and search for "Configure User Snippets" then create a file and paste below json code. provide prefix, Body, and description. Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets

{
    "forLoop": {
        "prefix": "forLoop",
        "body": [
            "for (const ${2:element} of ${1:array}) {",
            "\t$0",
            "}"
        ],
        "description": "For Loop"
    },

    "reactClass": {
        "prefix": "reactClass",
        "body": [
            "import React from 'react';",
            "class ${1:ComponentName} extends React.Component {",
            "\t$0constructor(props) {",
            "\t$0\t$0super(props)",
            "",
            "render() {",
            "return (<div> ${2:Component} </div>)",
            "}",
            "export default ${3:ComponentName}"
        ],
        "description": "For React Component class"
    },
    "function": {
    "scope": "javascript,typescript",
    "prefix": "function",
    "body": [
        "import React from 'react';",
        "import withStyles from '@material-ui/core/styles/withStyles';",
        "import { makeStyles } from '@material-ui/core/styles';",
        "",
        "import Styles from  './style.js';",
        "",
        "const useStyles = makeStyles(Styles);",
        "",
        "function $1(props){",
        "const classes = useStyles();",
        "\treturn (",
        "\t\t<React.Fragment>",
        "\t\t\t<div className={classes.root}>",
        "\t\t\t\t$1",
        "\t\t\t</div>",
        "\t\t</React.Fragment>",
        "\t)",
        "}",
        "export default withStyles(useStyles)($1);"
    ],
    "description": "react class"
  }
}
Hank
  • 231
  • 5
  • 13
2

I use this JSON Escape formatter(?) to process a large amount of HTML into a snippet:

https://www.freeformatter.com/json-escape.html

(The result of this process should be added in quotes "..." into the "body" part of the JSON object.

JCRC
  • 21
  • 2
0

I've written a script which you can create your own complex snippets. just using the file you'd like. so you dont' need to write the source code in a string or string array. https://github.com/banxi1988/vscode-snippets-ext-template

banxi1988
  • 1,322
  • 13
  • 10