How to add custom code snippets in VSCode? - code-snippets

Is it possible to add custom code snippets in Visual Studio Code? And if so, how? VSCode is based on Atom, so it should be possible.

Hit > shift + command + p and type snippets
Select Preferences: Configure User Snippets
Choose the language type for which you want to add the custom snippet in the vscode inputbox
vscode has comments to explain on how to add a snippet, as described on :> vsdoc or you can follow the next link with a short guide:
Lets say, we want to open custom snippets for the language GO. Then we can do:
Hit > command + p
Type: go.json + enter And you land on the custom snippet page
Snippets are defined in a JSON format and stored in a per-user (languageId).json file. For example, Markdown snippets go in a markdown.json file.
Using tools:
Snippet Generator extension (recommended)
Online snippet generator

Option 1 - Use the Snippet Generator extension.
It supports code to JSON conversion with optional scope support and space to \t conversion.
Demo:
Option 2 - Another extension is snippet-creator (deprecated).
After installing it, all you have to do is to :
Select the code that you want to make a snippet.
Right-click on it and select "Command Palette"(or Ctrl+Shift+P).
Write "Create Snippet".
Choose the type of files needed to be watched to trigger your snippet shortcut.
Choose a snippet shortcut.
Choose a snippet name.
Option 3 - check this website. you can generate snippets for vs code, sublime text, and atom.
Once snippet being generated on this site. Go to the respective IDE's snippet file and paste the same. For example for a JS snippet in VS code go to File->preference->user snippet then it opens javascript.json file then paste the snippet code from an above site inside this and we are good to go.

As of version 0.10.6 you can add custom snippets. Read the documentation on Creating your Own Snippets.
You can find/create custom snippets by placing the json file in C:\Users\<yourUserName>\AppData\Roaming\Code\User\snippets.
For example, a custom javascript snippets would be in a \snippets\javascript.json
You can also publish you snippets which is a really neat feature as well. John Papa created a nice angular + typescript snippet you can download as an extension in the marketplace.
Here is an example snippet taken for the documentation on a javascript for loop:
"For Loop": {
"prefix": "for",
"body": [
"for (var ${index} = 0; ${index} < ${array}.length; ${index}++) {",
"\tvar ${element} = ${array}[${index}];",
"\t$0",
"}"
],
"description": "For Loop"
},
Where
For Loop is the snippet name
prefix defines a prefix used in the IntelliSense drop down. In this case for.
body is the snippet content.
Possible variables are:
$1, $2 for tab stops
${id} and ${id:label} and ${1:label} for variables
Variables with the same id are connected.
description is the description used in the
IntelliSense drop down

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
install snippet-creator extension (now deprecated).
Highlight the code that you need to make snippet.
press ctrl+shift+P and type "Create snippet" on the command palette and
press ENTER.
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 youcreated the snippet. You will find the snippet there.

You can add custom scripts, go to File --> Preferences --> User Snippets. Select your preferred language.
If you choose Javascript you can see default custom script for console.log(' '); like this:
"Print to console": {
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"
},

There's a VSCode Plugin called: snippet-creator (now deprecated).
After installing it , all you have to do is to:
Select the code that you want to make it a snippet.
Right click on it and select "Command Palette"(or Ctrl+Shift+P).
Write "Create Snippet".
Choose type of files needed to be watched to trigger your snippet shortcut.
Choose a snippet shortcut.
Choose a snippet name.
That's All.
Note : if you want to edit your snippets , you will find them in [fileType].json
Example : Ctrl+P , then select "javascript.json"

I tried by adding snippets in javascriptreact.json but it didn't worked for me.
I tried adding snippets into global scope, and it's working like charm.
FILE --> Preferences --> User snippets
here select New Global Snippets File, give name javascriptreact.code-snippets.
For other languages you can name like [your_longuage].code-snippets

This is an undocumented feature as of now but is coming soon. There is a folder you can add them to and they will appear, but it may change (its undocumented for a reason).
Best advice is to add this to the uservoice site and wait til its final. But it is coming.

On MacOS:
Open the VSCode
Code -> Preferences -> User Snippets
Search for "python" (or any language)
Write your snippet like this:
{
"Write pdb": {
"prefix": "pdb",
"body": [
"import pdb; pdb.set_trace()",
"$2"
],
"description": "Write pdb.set_trace() to debug Python scripts"
}
}
Save the file with command + S.

VSCode introduce this in version 0.5, see here.
Snippet syntax follows the TextMate snippet syntax and can write in User Preferences.

If you'd rather not deal with writing your snippets in JSON, check out Snipster. It lets you write snippets as you would write the code itself - not having to wrap each line in quotes, escape characters, add meta information, etc.
It also lets you write once, publish anywhere. So you can use your snippet in VS Code, Atom, and Sublime, plus more editors in the future.

This may not be a real answer (as some have answered above), but if you're interested in creating custom code snippets for other people, you can create extensions using yeoman and npm (which by default comes along with NodeJS) . NOTE: This is only for creating snippets for other's systems. But it also works for you too! Except you need JS code for whole thing.

You can add custom scripts, go to File --> Preferences --> User Snippets. Select your preferred language.
Like mine code is go, I do it as below:
"channel code": {
"prefix": "make_",
"body": [
"${1:variable} := make(chan ${2:type}, ${3:channel_length})",
"$4"
]
}
explanation: $1 will take your tabs & to give hints what are those tabs values, we make it like ${1:some_variable} which could give us hints what are those
I hope, it helps!

Related

Vs Code Small Guide

Whenever i write code in Dart in Vscode It shows me guide about stuff I don't want to see
How can I get rid if this annoying guide
These are called Parameter Hints (and are showing you the parameters for the function you're calling). You can disable them with this VS Code setting:
You can close quick suggestions by editing settings.json. To edit settings.json go to Preferences->Settings page (Shortcut: Cmd + Shift + P and type settings.json)
Then add the following code (or edit if there is 'editor.quickSuggestions' key in the file) to close quick suggestions.
"editor.quickSuggestions": {
"comments": false,
"other": true,
"strings": false
},

Add custom page/field to NSIS setup created with electron-builder

I have created an Electron app which is packaged into an NSIS installer with electron-builder.
Now I would like to add a custom text field to the installer, where the user can input a value (the value should be saved to disk/registry, it needs to be available in the app later).
I saw there is a customWelcomePage macro defined in the installer, which could probably be (mis)used for this purpose? But how would I create a macro which creates a complete page? NSIS is completely new to me, and the examples on the NSIS page seem to be for standalone installers, not for hooking into an existing installer. Or is there another, better approach?
I've been working on the same thing recently. Here's what I did:
First, use the include option to point to a .nsh file (I'm doing this in package.json):
{
"build": {
"appId": "...",
"nsis": {
"include": "build/installer.nsh"
}
}
}
Then you can put your custom NSIS code inside that .nsh file:
!include nsDialogs.nsh
XPStyle on
Var Dialog
Page custom myCustomPage
Function myCustomPage
nsDialogs::Create 1018
Pop $Dialog
${If} $Dialog == error
Abort
${EndIf}
...
nsDialogs::Show
FunctionEnd
Section
SectionEnd
I adapted code from Mevia's question when I was creating my custom page. This will make a page that appears before the actual installation (Mevia's problem), so you should be careful where you save the input data.
I believe that using include instead of a script is what allows you to write code for a single page, rather than having to write the entire installer script yourself.

Is there a "correct" folder where to place test resources in dart?

I have a simple dart class I am trying to test.
To test it I need to open a txt file, feed the content to an instance of the class and check that the output is correct.
Where do I place this txt file? The txt file is useless outside of testing.
Also, related, how do I acess its directory consistently? I tried placing it in the test folder, but the problem is that:
System.currentDirectory
Returns a different directory if I am running the test on its own or the script calling all the other test dart files on at a time
I check if System.currentDirectory is the directory containing the pubspec.yaml file, if not I move the current directory upwards until I found the directory containing the pubpsec.yaml file and then continue with the test code.
Looks like package https://pub.dev/packages/resource is also suitable for this now.
I have still not found a definitive answer to this question. I've been looking for something similar to the testdata directory in Go and the src/test/resources directory in Java.
I'm using Android studio and have settled on using a test_data.dart file at the top of my test directory. In there I define my test data (mostly JSON) and then import it into my individual tests. This doesn't help if you need to deal with binary files but it has been useful for my JSON data. I'll also inject the JSON language with //language=json so I can open the fragment in a separate window to format.
//language=json
const consolidatedWeatherJson = '''{
"consolidated_weather": [
{
"id": 4907479830888448,
"weather_state_name": "Showers",
"weather_state_abbr": "s",
"wind_direction_compass": "SW",
"created": "2020-10-26T00:20:01.840132Z",
"applicable_date": "2020-10-26",
"min_temp": 7.9399999999999995,
"max_temp": 13.239999999999998,
"the_temp": 12.825,
"wind_speed": 7.876886316914553,
"wind_direction": 246.17046093256732,
"air_pressure": 997.0,
"humidity": 73,
"visibility": 11.037727173307882,
"predictability": 73
}
]
}
''';
Using the Alt + Enter key combination will bring up the Edit JSON Fragment option. Selecting that open the fragment in a new editor and any changes made there (formatting for example) will be updated in the fragment.
Not perfect but it solves my issues.

Visual Studio macro to navigate to T4MVC link

I use T4MVC and I'm happy with it and want to keep it - it keeps down run time defects. Unfortunately, it makes it harder to navigate to views and content (a.k.a. Views and Links in T4MVC) though. Even using Resharper, I can't navigate to the referenced item:
T4MVC and Resharper Navigation
Can I get a hand building a macro to do this? Never having built a VS IDE macro before, I don't have a grasp on how to get at some things, like the internal results of the "Go To Definition" process, if that's even possible.
If you aren't familiar with T4MVC, here's generally what the macro might do to help:
Given the token: Links.Content.Scripts.jQuery_js in the file MyView.cshtml, '(F12) Go To Definition'. This behaves properly.
Having arrived at the the related assignment:
public readonly string jQuery_js = "~/Content/Scripts/jQuery.js"; in a file generated by T4MVC (which is very nice, thank you David, but we really don't ever need to see), capture the string assigned and close the file.
Navigate in Solution Explorer to the PhysicalPath represented by the captured string.
This process would also work for views/layouts/master-pages/partials, etc.
If you provide a macro or link to a macro to do this, or have another solution, wonderful. Otherwise, hints on how to do step 3 simply in a VS macro would be especially appreciated and receive upvote from me. I'd post the macro back here as an answer when done.
Thanks!
Here's a Visual Studio macro to help.
What it does
Now you probably use T4MVC references in places like this:
Layout = MVC.Shared.Views.MasterSiteTheme;
ScriptManager.AddResource(Links.Content.Script.jQueryXYZ_js);
<link type="text/css" href="#Links.Content.Style.SiteTheme_css" />
return View(MVC.Account.Views.SignIn);
#Html.Partial(MVC.Common.Views.ContextNavigationTree)
#Html.ActionLink("Sign in / Register", MVC.Account.SignIn())
F12 (Go to Definition) already works for the last bullet (actions), but this hack is intended to cover the other scenarios (resources).
Macro
Imports EnvDTE
Imports System.IO
Public Module NavT4Link
Sub NavigateToLink()
DTE.ExecuteCommand("Edit.GoToDefinition")
Dim navpath As String = Path.GetFileName(DTE.ActiveDocument.FullName)
Dim isContentLink As Boolean = navpath.Equals("T4MVC.cs")
If (isContentLink Or navpath.EndsWith("Controller.generated.cs")) Then
Dim t4doc As TextDocument = DTE.ActiveDocument.Object()
navpath = CurrentLinePathConstant(t4doc)
If isContentLink Then
t4doc.Selection.MoveToPoint(t4doc.Selection.ActivePoint.CodeElement(vsCMElement.vsCMElementClass).StartPoint)
t4doc.Selection.FindText("URLPATH")
navpath = Path.Combine(CurrentLinePathConstant(t4doc), navpath)
End If
If navpath.StartsWith("~") Then
DTE.ActiveDocument.Close(vsSaveChanges.vsSaveChangesPrompt)
Dim proj As Object = DTE.Solution.FindProjectItem(DTE.ActiveDocument.FullName).ContainingProject
navpath = Path.GetDirectoryName(proj.Fullname()) + navpath.TrimStart("~")
DTE.ItemOperations.OpenFile(navpath)
End If
End If
End Sub
Function CurrentLinePathConstant(ByVal t4doc As TextDocument) As String
t4doc.Selection.SelectLine()
Dim sa() As String = t4doc.Selection.Text().Split("""")
If sa.Length > 1 Then Return sa(sa.Length - 2) Else Return ""
End Function
End Module
Installation
In Visual Studio, press "Alt-F8" to open Macro Explorer.
Right-Click "My Macros", select "New Module...", and click "Add".
Replace all the text with the code shown here.
Save and exit the Macro Editor.
Open "Tools : Options".
In the left pane, select "Environment : Keyboard".
In the "Show commands containing" text field enter "T4".
In the "Press shortcut keys:" field press the "F12" key.
Click "Assign" and "OK".
On un-patched VS, this installation process doesn't result in a 'bindable' macro. A workaround was to (CTRL-SHIFT-R-R) to record an empty macro, and paste the code into it without renaming it. If someone knows of a more documentable approach to install a macro in VS, please comment.
Notes/Caveats
It's meant to replace the current F12 functionality, so if it isn't a T4MVC link, it will do the usual, otherwise it continues on to open the resource. It handles the majority of cases, but not T4MVC-generated empty controller methods. Those you get dumped off at the same place you did before.
For Content/Asset/Link resources, navigating to it in Solution Explorer would probably be in order, for image files for example, but I didn't see that functionality in the Visual Studio docs.

How do I setup/use ruby on rails snippets and autocomplete in sublime text 2?

I would appreciate if someone could direct me to a website that shows how to do this..
Can't seem to find anything decent enough via google.
This will be the first time I'm doing this kind of thing with a text editor.. It has got to the stage where typing out things like <%= %> is getting old and slow.
I've got a rails snippet package and also ryan-on-rails package installed. Just confused with how to start using them.
I'm on max osx - snow leopard
Kind regards
Update
This helped me out. http://webtempest.com/sublime-text-2-how-to-create-snippets/ but I still need a little practice.
I have a package "rails" can't remember where I got it but the triggering of snippets is working. I'd just like to find a nice list of the commands rather than have to go to each snippet and look for myself. I can find the by clicking on snippets but isn't there a way I can create a shortcut for that?
Also would like some auto indentation.. and also complete.
I'm puzzled that this isn't part of the default Rails package, but I found this to be just what I was looking for:
https://github.com/eddorre/SublimeERB
Since you're new to Sublime Text, I highly recommend you check out: ST2's Unofficial Documentation. If includes a ton of getting started info plus tons of info for extendibility and plugin development.
Another great "Getting Started" guide can be found here on Nettuts+.
If you're looking a list of your snippets and their associated shortcuts, go to "Tools > Snippets..." from your menu.
To expand <% into <%| %> (where | is the cursor), add the following you to your User-keybindings (Preferences > Keybindings - User):
{
"args": {
"contents": "% $0 %>"
},
"command": "insert_snippet",
"context": [
{
"key": "selector",
"match_all": true,
"operand": "source.ruby",
"operator": "equal"
},
{ "key": "preceding_text", "operator": "regex_match", "operand": ".*<", "match_all": true }
],
"keys": [
"%"
]
}
The latest beta includes improved auto-indentation, so if you don't have that installed, try that out.
As for autocompletion, Sublime Text 2 by default offers autocompletion of words in the current document (plus all of your snippets/completions from packages). However, if you're looking for IDE-like autocompletion, there is the SublimeCodeIntel plugin. I am reluctant to mention it because it has not been updated in months and the bug reports keep flowing in.
Hope that helps.
I use ERB Snippets
https://github.com/matthewrobertson/ERB-Sublime-Snippets
You can install via Sublime Package control
Cmd+Shift+P
Go to Package Control: Install Package.
Type ERB Snippets. Let it roll.
Then you can use tab autocomplete for lots of snippets such as:
print ERB tags = pe which auto completes to <%= %>
if block = if which auto completes to <% if %>...<% end %>
If you are looking for autocomplete suggest, change the auto_complete_selector in Preference like:
"auto_complete_selector": "text, source - comment",

Resources