Skip to content

Instantly share code, notes, and snippets.

@Geogboe
Last active January 5, 2021 17:05
Show Gist options
  • Save Geogboe/de28f56d2cc3700fc1ffc0224b3914e0 to your computer and use it in GitHub Desktop.
Save Geogboe/de28f56d2cc3700fc1ffc0224b3914e0 to your computer and use it in GitHub Desktop.
vscode-snippet-copy-paste - Convert Code Block to VSCode Snippet
# 2021 - George Bowen
# Usage:
# Add this to your vscode powershell profile "code $profile",
# then, select any text in your editor, type alt+shift+s, select Convert Code Block to Snippet,
# which will return a json code block for you to add to your vscode snippets file
function ConvertTo-JsonCodeBlock {
<#
.SYNOPSIS
Converts a given block of text to a JSON encoded snippet
for use withen VSCODE
#>
param (
[string] $Name,
[string[]] $Scope,
[string] $Prefix,
[string] $Description = $Name,
[string[]] $Body
)
$Object = [PSCustomObject]@{
"$Name" = [PSCustomObject]@{
scope = $Scope -join ","
prefix = $Prefix
description = $Description
body = $Body
}
}
# Convert to json object
$JsonObject = $Object | ConvertTo-Json
# Replace $ with \\$ for vscode
$JsonObject = ( $JsonObject -replace "\$", "\\$" ) -split "`n"
# Remove the starting and trailing {}
return $JsonObject[1..($JsonObject.Length-2)]
}
Register-EditorCommand -Name "ConvertToSnippet" -DisplayName "Covert Code Block to Snippet" -ScriptBlock {
param (
[object]$Context
)
$SelectedText = ( Get-Content $Context.CurrentFile.Path )[($Context.SelectedRange.Start.Line - 2)..($Context.SelectedRange.End.Line - 1)]
ConvertTo-JsonCodeBlock -Name "CHANGE_ME" -Scope "CHANGE_ME" -Prefix "CHANGE_ME" -Body $SelectedText
}
Register-EditorCommand -Name "ConvertToSnippet-Prompt" -DisplayName "Covert Code Block to Snippet With Prompts" -ScriptBlock {
param (
[object]$Context
)
$SelectedText = ( Get-Content $Context.CurrentFile.Path )[($Context.SelectedRange.Start.Line - 2)..($Context.SelectedRange.End.Line - 1)]
ConvertTo-JsonCodeBlock -Name ( Read-Host "Snippet Name" ) -Scope ( Read-Host "Snippet Scope" ) -Prefix ( Read-Host "Snippet Prefix" ) -Body $SelectedText
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment