Skip to content

Instantly share code, notes, and snippets.

@ninmonkey
Last active March 19, 2023 20:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ninmonkey/4fe8062d5ad1b2ad17e6f91a96984851 to your computer and use it in GitHub Desktop.
Save ninmonkey/4fe8062d5ad1b2ad17e6f91a96984851 to your computer and use it in GitHub Desktop.
vs code snippet patterns
[
/* powershell comes with */
{
"key": "ctrl+alt+j",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus && editorLangId == 'powershell'"
},
// you can opt-in to specific languages
{
"key": "ctrl+alt+j",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus && editorLangId == 'markdown' || editorLangId == 'powerquery' || editorLangId == 'swift'"
},
]
{
"Github Issue: Collapsable Details": {
"prefix": "Issue",
"description": "md : Collapsable Detail Section",
"body": [
"<details><summary>",
"${1:Summary} (Click to Expand)",
"</summary>",
"${0:$TM_SELECTED_TEXT}",
"</details>"
],
},
}
{
/*
Snippets: Power Query ( aka 'm' )
*/
"Web.Contents | Basic HTTP Request": {
"Web.Contents | Basic HTTP Request": {
"prefix": "Web Request",
"description": "Web ⁞ A basic HTTP Request",
"body": [
"webResponse = ",
" let",
" Headers = [",
" Accept=\"application/json\"",
" ],",
" BaseUrl = \"${1:https://httpbin.org}\",",
" Options = [",
" RelativePath = \"${2:/get}\",",
" Headers = Headers,",
" Query = [",
" ${3:ArgName = Value}",
" ]",
" ],",
" // wrap 'Response' in 'Binary.Buffer' if you are using it multiple times",
" Response = Web.Contents(BaseUrl, Options),",
" Result = Json.Document(Response)",
" in",
" Result${0}",
],
},
},
"Web.Contents | Advanced HTTP Request": {
"Web.Contents | Advanced HTTP Request": {
"prefix": "Web Request Advanced",
"description": "Web ⁞ A HTTP Request with all options",
"body": [
"/*",
"Handle authentication by passing an API token either through another query parameter called APIToken or via an HTTP header also called APIToken",
"",
"Header Key name used when saving API key in the credential store instead of power query",
"see more: <https://gist.github.com/ninmonkey/aab7ceddc3addd3c24c0d27ed976a785#preventing-errors-refreshing-on-the-live-service> , and <https://docs.microsoft.com/en-us/powerquery-m/web-contents#syntax>",
"*/",
"webResponse = ",
" let",
" Headers = [",
" Accept =\"application/json\"",
" // APIToken = \"...\"",
" // #\"Authorization\" = accessToken",
" ],",
" BaseUrl = \"https://httpbin.org\",",
" Query = [",
" ArgName = Value",
" ],",
" Options = [",
" Query = Query,",
" ApiKeyName = \"apikey\", // enables credential store",
" RelativePath = \"/get\",",
" Headers = Headers",
" // Timeout = 100, // using seconds",
" // IsRetry = true, // true will ignore existing response in the cache",
" // disable builtin handling of specific status codes",
" // ManualStatusHandling = {\"401\", \"404\"}",
"",
" // exclude these HTTP header keys from being part of the calculation for caching data.",
" // ExcludedFromCacheKey = {\"header_key_num1\", ...}",
" ",
" ],",
" // If key 'Content' is used: request type will be POST",
" // Content = \"\"",
"",
" Response = Web.Contents(BaseUrl, Options),",
" Result = Json.Document(Response)",
" in",
" Result",
"",
" ",
],
},
},
"Add Custom Column": {
"Add Custom Column": {
"prefix": "Add Column",
"description": "Table ⁞ Add a custom column. If text is selected that becomes the inner each expression.",
"body": [
"${1:StepName} = Table.AddColumn(",
" ${2:TableName},",
" \"${3:ColumnName}\",",
// " each ${0:$TM_SELECTED_TEXT}",
" each ${0}",
" ${4:type any}",
"),",
],
},
},
"Custom Function": {
"Custom Function": {
"prefix": "Function",
"description": "Function ⁞ add a new function",
"body": [
"/* about:",
"*/",
"${1:Name} = (${2}) as ${3} =>",
" let",
" ${4} = ${0}",
"",
" in",
" ${4},",
],
},
}
}
{
/*
Snippets: Powershell
Snippet pattern examples:
<https://gist.github.com/ninmonkey/4fe8062d5ad1b2ad17e6f91a96984851>
to disable the default pwsh snippets, see:
https: //code.visualstudio.com/docs/editor/userdefinedsnippets#_choice
see also:
https: //github.com/PowerShell/vscode-powershell/blob/master/docs/community_snippets.md
extension dir:
$Env:UserProfile\.vscode\extensions\ms-vscode.powershell[-preview]-<version>\snippets\PowerShell.json
*/
"CmdletBinding()": {
"prefix": "[CmdletBinding()]",
"description": "nin ⁞ CmdletBinding with initial params",
"body": [
"[CmdletBinding()]",
"param (",
" # ${3:docstring}",
" [Parameter(Mandatory, Position=0,",
// Best practice is to use doc strings, not the attribute
// " HelpMessage=\"doc\")]",
" [${1:TypeName}]$${2:ParameterName}$0",
")"
]
},
"CalculatedProperty": {
"prefix": "Calculated-Property ⇢ SingleLine",
"body": [
"@{name='${1:PropertyName}';expression={${2:${TM_SELECTED_TEXT:\\$_.PropertyValue}}}}$0"
],
"description": "nin ⁞ a CalculatedProperty on a Single Line",
},
"CalculatedProperty: Multiline": {
"prefix": "Calculated-Property ⇢ MultiLine",
"body": [
"@{",
" Name = '${1:PropertyName}'",
" Expression = {",
" ${2:${TM_SELECTED_TEXT:\\$_.PropertyValue}}",
" }",
"}",
"$0"
],
"description": "nin ⁞ a CalculatedProperty using multiple lines",
},
"IfShouldProcess": {
"prefix": "IfShouldProcess",
"description": "nin ⁞ Creates ShouldProcess block from your Selection",
"body": [
"if (\\$PSCmdlet.ShouldProcess(\"${1:Target}\", \"${2:Operation}\")) {",
" ${0:$TM_SELECTED_TEXT}",
"}"
],
},
"Parameter ⇢ Basic": {
"prefix": "[Parameter] : Basic",
"body": [
"# ${1:Docstring}",
"[Parameter(${2:Mandatory, Position=0})]",
"[${3:object}]$${4:ParameterName}$0",
],
"description": "A basic [Parameter()]"
},
"Parameter ⇢ Switch": {
"prefix": "[Parameter] ⇢ Switch",
"description": "nin ⁞ adds a [switch] parameter",
"body": [
"# ${1:Docstring}",
"[Parameter()][switch]\\$${0}"
]
},
"Function ⇢ Basic": {
"prefix": "Function ⇢ Basic",
"description": "nin ⁞ A basic function",
"body": [
"function ${1:Name} {",
" <#",
" .synopsis",
" ${2}",
" .description",
" .",
" .example",
" PS>",
" .notes",
" .",
" #>",
" param (",
" ${0}",
" )",
" begin {}",
" process {}",
" end {}",
"}",
],
},
"Parameter: Completer ⇢ ValidateSet": {
"prefix": "Completer ⇢ ValidateSet",
"description": "nin ⁞ Autocompleter parameter from a static list using ValidateSet()",
"body": [
"# ${1:Docstring}",
"[Parameter(",
" ${2:Mandatory}, ${3:Position=0},",
// " HelpMessage='${3}')]",
" [ValidateSet(${4})]",
" [string[]]$${5:ParameterName})",
"$0",
],
},
}
{
/*
description:
Examples of different input types
this isn't an actual snippet file to use
it's an example template
New: Snippet variables
https://code.visualstudio.com/updates/v1_53#_new-snippet-variables
docs:
https://code.visualstudio.com/docs/editor/userdefinedsnippets
regex transform:
https://code.visualstudio.com/docs/editor/userdefinedsnippets#_transform-examples
extension snippets tutorial:
https://code.visualstudio.com/api/language-extensions/snippet-guide
vscode variables:
https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables
additional examples:
https://rkeithhill.wordpress.com/2016/02/17/creating-a-powershell-command-that-process-paths-using-visual-studio-code/
todo:
selected text falls back to a default
${0:${TM_SELECTED_TEXT:fully-qualified-name}}
*/
// sample snippet using UUID and RELATIVE_FILEPATH
{
"scope": "javascript",
"description": "using variables",
"prefix": "newVars",
"body": "let someId = '${RELATIVE_FILEPATH}/${UUID}'$0"
},
"use selected text as input": {
"Add Custom Column": {
"prefix": "Add Column",
"description": "Table ⁞ Add a custom column. If text is selected that becomes the inner each expression.",
"body": [
"${1:StepName} = Table.AddColumn(",
" ${2:TableName},",
" \"${3:ColumnName}\",",
" each ${0:$TM_SELECTED_TEXT}",
" ${4:type any}",
"),",
],
},
},
"multiple tab groups including repeated values": {
"Custom Function": {
"prefix": "Function",
"description": "Function ⁞ add a new function. Note that 4 is used twice on purpose.",
"body": [
"/* about:",
"*/",
"${1:Name} = (${2}) as ${3} =>",
" let",
" ${4} = ${0}",
"",
" in",
" ${4},",
],
},
},
"Choice: Select One": {
"prefix": "choice",
"description": "select from UI Popup menu",
"body": [
"${1|one,two, three|}"
]
},
"Dynamic: Datetime": {
"prefix": "dynamic",
"description": "insert datetimes",
"body": [
"\\$CURRENT_YEAR = '$CURRENT_YEAR'", // The current year
"\\$CURRENT_YEAR_SHORT = '$CURRENT_YEAR_SHORT'", // The current year's last two digits
"\\$CURRENT_MONTH = '$CURRENT_MONTH'", // The month as two digits (example '02')
"\\$CURRENT_MONTH_NAME = '$CURRENT_MONTH_NAME'", // The full name of the month (example 'July')
"\\$CURRENT_MONTH_NAME_SHORT = '$CURRENT_MONTH_NAME_SHORT'", // The short name of the month (example 'Jul')d
"\\$CURRENT_DATE = '$CURRENT_DATE'", // The day of the month
"\\$CURRENT_DAY_NAME = '$CURRENT_DAY_NAME'", // The name of day (example 'Monday')
"\\$CURRENT_DAY_NAME_SHORT = '$CURRENT_DAY_NAME_SHORT'", // The short name of the day (example 'Mon')
"\\$CURRENT_HOUR = '$CURRENT_HOUR'", // The current hour in 24-hour clock format
"\\$CURRENT_MINUTE = '$CURRENT_MINUTE'", // The current minute
"\\$CURRENT_SECOND = '$CURRENT_SECOND'", // The current second
"\\$CURRENT_SECONDS_UNIX = '$CURRENT_SECONDS_UNIX'", // The number of seconds since the Unix epoch
]
},
"Date-Iso": {
"prefix": "date",
"description": "insert current [Date] (without time) in iso format",
"body": [
"$CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE"
]
},
"TabStop: order": {
"prefix": "tab",
"description": "tabs jump to the next number, 0 is the final location",
"body": [
"{",
" 'First': '$1'",
"}",
"$0"
]
},
"Variable: With defaults": {
"prefix": "variable",
"description": "variables fallback to an empty string, if default values are not set",
"body": [
"'${IDoNotExist}' so end up as text, tab-stopped",
// "$novar"
]
},
"selected Text: quote": {
"prefix": "select",
"description": "use currently selected text",
"body": [
";\nSelected text was: [",
"\t> $TM_SELECTED_TEXT",
"]\n",
]
},
"Dynamic: Filename": {
"prefix": "Filename",
"description": "get current filename and transform it",
"body": [
"\n\n<-- start:",
"\nFullName:",
"\t${TM_FILEPATH}",
"Directory: FullName:",
"\t${TM_FILEPATH/(.*)\\..+$/$1/}",
"\nFilename:\n\t$TM_FILENAME",
"\nBaseName:\n\t$TM_FILENAME_BASE",
"\nEnd -->\n",
]
},
"ex: conditional return statement": {
"prefix": "ex: conditional return statement",
"description": "Description",
"body": [
"test format of the popup",
"(${1:void})${2:methodName}",
"{${1/void$|(.+)/${1:+\n\treturn nil;}/}",
"}"
]
},
"regex: escape quotes": {
"prefix": "escape quotes",
"description": "escape double quotes",
"body": [
"${TM_SELECTED_TEXT/[\"]/\\\"_/gi}"
]
},
"regex: strip extension": {
"prefix": "regex: strip the final .text",
"description": "regex strip",
"body": [
"${TM_SELECTED_TEXT/(.*)\\..+?$/$1/}"
]
},
"regex: quote all lines, up to selection": {
"prefix": "regex: quote all lines, up to selection",
"description": "regex: quote all lines, to selection. at this point it's better to use an extension",
"body": [
"${TM_SELECTED_TEXT/^(.*)$/\"$1\"/gim}"
]
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment