├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ ├── automerge.yml │ ├── links.yml │ └── ci.yml ├── talk.png ├── .gitignore ├── .lycheeignore ├── contrib ├── find.gif ├── icon.png ├── findSelected.gif ├── findSelectedMenu.gif ├── findSelectedShortcut.gif ├── snippets-storage │ ├── move.gif │ ├── save.gif │ ├── vscdb.png │ ├── delete.gif │ ├── history.png │ ├── insert.gif │ ├── rename.gif │ ├── search.gif │ ├── create-folder.gif │ ├── intellisense.gif │ └── restore-backups.gif └── icon.svg ├── assets ├── Screenshot build task.png ├── Screenshot launch task.png └── icons │ ├── add-dark.svg │ ├── add-light.svg │ ├── history-dark.svg │ └── history-light.svg ├── src ├── cache.ts ├── date.ts ├── languages.ts ├── test │ ├── runTest.ts │ ├── suite │ │ ├── index.ts │ │ ├── toggleComments.test.ts │ │ ├── showPreviousAnswer.test.ts │ │ ├── showNextAnswer.test.ts │ │ ├── findSelectedText.test.ts │ │ ├── find.test.ts │ │ └── restoreBackups.test.ts │ └── testUtils.ts ├── clipboard.ts ├── completionManager.ts ├── provider.ts ├── config.ts ├── query.ts ├── backupManager.ts ├── snippetsTreeProvider.ts ├── extension.ts ├── snippet.ts ├── snippetsStorage.ts └── endpoints.ts ├── .vscodeignore ├── tsconfig.json ├── .eslintrc.json ├── Makefile ├── rollup.config.mjs ├── CONTRIBUTING.md ├── .vscode ├── launch.json └── tasks.json ├── LICENSE ├── README.md └── package.json /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: mre 2 | -------------------------------------------------------------------------------- /talk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/talk.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | out/ 3 | *.vsix 4 | .vscode 5 | .vscode-test 6 | -------------------------------------------------------------------------------- /.lycheeignore: -------------------------------------------------------------------------------- 1 | # Frequent network error; disabling for now 2 | https://cht.sh/ 3 | -------------------------------------------------------------------------------- /contrib/find.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/find.gif -------------------------------------------------------------------------------- /contrib/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/icon.png -------------------------------------------------------------------------------- /contrib/findSelected.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/findSelected.gif -------------------------------------------------------------------------------- /contrib/findSelectedMenu.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/findSelectedMenu.gif -------------------------------------------------------------------------------- /assets/Screenshot build task.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/assets/Screenshot build task.png -------------------------------------------------------------------------------- /contrib/findSelectedShortcut.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/findSelectedShortcut.gif -------------------------------------------------------------------------------- /assets/Screenshot launch task.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/assets/Screenshot launch task.png -------------------------------------------------------------------------------- /contrib/snippets-storage/move.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/move.gif -------------------------------------------------------------------------------- /contrib/snippets-storage/save.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/save.gif -------------------------------------------------------------------------------- /contrib/snippets-storage/vscdb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/vscdb.png -------------------------------------------------------------------------------- /contrib/snippets-storage/delete.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/delete.gif -------------------------------------------------------------------------------- /contrib/snippets-storage/history.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/history.png -------------------------------------------------------------------------------- /contrib/snippets-storage/insert.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/insert.gif -------------------------------------------------------------------------------- /contrib/snippets-storage/rename.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/rename.gif -------------------------------------------------------------------------------- /contrib/snippets-storage/search.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/search.gif -------------------------------------------------------------------------------- /contrib/snippets-storage/create-folder.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/create-folder.gif -------------------------------------------------------------------------------- /contrib/snippets-storage/intellisense.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/intellisense.gif -------------------------------------------------------------------------------- /contrib/snippets-storage/restore-backups.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mre/vscode-snippet/HEAD/contrib/snippets-storage/restore-backups.gif -------------------------------------------------------------------------------- /src/cache.ts: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | import * as vscode from "vscode"; 4 | 5 | export const cache = { 6 | state: null 7 | }; 8 | -------------------------------------------------------------------------------- /src/date.ts: -------------------------------------------------------------------------------- 1 | export function formatUnixTime(ms: number): string { 2 | const date = new Date(ms); 3 | return `${date.toDateString()}, ${date.toLocaleTimeString([], { 4 | hour: "2-digit", 5 | minute: "2-digit", 6 | })}`; 7 | } 8 | -------------------------------------------------------------------------------- /.vscodeignore: -------------------------------------------------------------------------------- 1 | # Everything is excluded unless we add it manually, preventing accidental 2 | # inclusion of unwanted files. 3 | * 4 | */** 5 | !LICENSE 6 | !README.md 7 | !assets/** 8 | !contrib/** 9 | !out/extension.js 10 | !package.json 11 | !package-lock.json 12 | -------------------------------------------------------------------------------- /assets/icons/add-dark.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/add-light.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "allowSyntheticDefaultImports": true, 5 | "target": "es6", 6 | "outDir": "out", 7 | "lib": [ 8 | "es6", 9 | "DOM", 10 | ], 11 | "sourceMap": true, 12 | "rootDir": "src" 13 | }, 14 | "include": [ 15 | "src" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: "/" 5 | ignore: 6 | - dependency-name: "@types/node" 7 | versions: 8 | - "> 12.12.11" 9 | - dependency-name: "@types/vscode" 10 | versions: 11 | - "> 1.40.0, < 1.41" 12 | groups: 13 | - dependencies: 14 | patterns: 15 | - "*" 16 | -------------------------------------------------------------------------------- /.github/workflows/automerge.yml: -------------------------------------------------------------------------------- 1 | name: Automerge 2 | 3 | on: 4 | pull_request_target: 5 | types: 6 | - opened 7 | - synchronized 8 | - reopened 9 | - edited 10 | - labeled 11 | - unlabeled 12 | - ready_for_review 13 | 14 | jobs: 15 | automerge: 16 | runs-on: ubuntu-latest 17 | if: ${{ github.actor == 'dependabot[bot]' }} 18 | steps: 19 | - uses: reitermarkus/automerge@v2 20 | with: 21 | token: ${{ secrets.GITHUB_TOKEN }} 22 | pull-request: ${{ github.event.inputs.pull-request }} 23 | -------------------------------------------------------------------------------- /.github/workflows/links.yml: -------------------------------------------------------------------------------- 1 | name: Links 2 | 3 | on: 4 | repository_dispatch: 5 | workflow_dispatch: 6 | schedule: 7 | - cron: "00 18 * * *" 8 | 9 | jobs: 10 | linkChecker: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | 15 | - name: Link Checker 16 | uses: lycheeverse/lychee-action@v1.5.0 17 | with: 18 | args: --verbose --no-progress **/*.md **/*.html 19 | env: 20 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 21 | 22 | - name: Create Issue From File 23 | uses: peter-evans/create-issue-from-file@v3 24 | with: 25 | title: Link Checker Report 26 | content-filepath: ./lychee/out.md 27 | labels: report, automated issue 28 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "es2021": true, 4 | "node": true 5 | }, 6 | "extends": [ 7 | "eslint:recommended", 8 | "plugin:@typescript-eslint/recommended" 9 | ], 10 | "overrides": [ 11 | ], 12 | "parser": "@typescript-eslint/parser", 13 | "parserOptions": { 14 | "ecmaVersion": "latest", 15 | "sourceType": "module" 16 | }, 17 | "plugins": [ 18 | "@typescript-eslint" 19 | ], 20 | "rules": { 21 | "@typescript-eslint/no-explicit-any": "warn", 22 | "indent": [ 23 | "error", 24 | 2 25 | ], 26 | "linebreak-style": [ 27 | "error", 28 | "unix" 29 | ], 30 | "semi": [ 31 | "error", 32 | "always" 33 | ] 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/languages.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | 3 | class Languages { 4 | constructor(private readonly fileExtensions = new Map()) { 5 | for (const extension of vscode.extensions.all) { 6 | const languages = extension?.packageJSON?.contributes?.languages; 7 | if (languages && Array.isArray(languages)) { 8 | for (const lang of languages) { 9 | if ( 10 | lang && 11 | lang.id && 12 | lang.extensions && 13 | Array.isArray(lang.extensions) 14 | ) { 15 | fileExtensions.set(lang.id, lang.extensions); 16 | } 17 | } 18 | } 19 | } 20 | } 21 | 22 | getExtensions(languageId: string): string[] { 23 | return this.fileExtensions.get(languageId) || []; 24 | } 25 | } 26 | 27 | export default new Languages(); 28 | -------------------------------------------------------------------------------- /src/test/runTest.ts: -------------------------------------------------------------------------------- 1 | import * as path from "path"; 2 | 3 | import { runTests } from "@vscode/test-electron"; 4 | 5 | async function main() { 6 | try { 7 | // The folder containing the Extension Manifest package.json 8 | // Passed to `--extensionDevelopmentPath` 9 | const extensionDevelopmentPath = path.resolve(__dirname, "../../"); 10 | 11 | // The path to the extension test runner script 12 | // Passed to --extensionTestsPath 13 | const extensionTestsPath = path.resolve(__dirname, "./suite/index"); 14 | 15 | // Download VS Code, unzip it and run the integration test 16 | await runTests({ 17 | extensionDevelopmentPath, 18 | extensionTestsPath, 19 | }); 20 | } catch (err) { 21 | console.error(err); 22 | console.error("Failed to run tests"); 23 | process.exit(1); 24 | } 25 | } 26 | 27 | main(); 28 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Needed SHELL since I'm using zsh 2 | SHELL := /bin/bash 3 | .PHONY: help 4 | 5 | .PHONY: update 6 | update: ## Update all dependencies 7 | npm update 8 | 9 | .PHONY: install 10 | install: ## Install npm package 11 | npm install 12 | 13 | .PHONY: ls 14 | ls: ## Lists all the files that will be published 15 | vsce ls 16 | 17 | .PHONY: package 18 | package: install update-vsce ls ## Package extension for publication 19 | vsce package 20 | 21 | .PHONY: update-vsce 22 | update-vsce: ## Update vsce extension manager 23 | npm update @vscode/vsce 24 | 25 | .PHONY: publish 26 | publish: update-vsce ls install package ## Publish on VSCode Marketplace 27 | vsce publish 28 | 29 | help: ## This help message 30 | @echo -e "$$(grep -hE '^\S+:.*##' $(MAKEFILE_LIST) | sed -e 's/:.*##\s*/:/' -e 's/^\(.\+\):\(.*\)/\\x1b[36m\1\\x1b[m:\2/' | column -c2 -t -s :)" 31 | 32 | clean: ## Clean up build artifacts 33 | rm -rf *.vsix -------------------------------------------------------------------------------- /src/test/suite/index.ts: -------------------------------------------------------------------------------- 1 | import * as path from "path"; 2 | import * as Mocha from "mocha"; 3 | import * as glob from "glob"; 4 | 5 | export function run(): Promise { 6 | // Create the mocha test 7 | const mocha = new Mocha({ 8 | ui: "tdd", 9 | color: true, 10 | timeout: 10000, 11 | }); 12 | 13 | const testsRoot = path.resolve(__dirname, ".."); 14 | 15 | return new Promise((c, e) => { 16 | const files = glob.globSync("**/**.test.js", { cwd: testsRoot }); 17 | 18 | // Add files to the test suite 19 | files.forEach((f) => mocha.addFile(path.resolve(testsRoot, f))); 20 | 21 | try { 22 | // Run the mocha test 23 | mocha.run((failures) => { 24 | if (failures > 0) { 25 | e(new Error(`${failures} tests failed.`)); 26 | } else { 27 | c(); 28 | } 29 | }); 30 | } catch (err) { 31 | e(err); 32 | } 33 | }); 34 | } 35 | -------------------------------------------------------------------------------- /src/clipboard.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | import { getConfig } from "./config"; 3 | 4 | export async function copySnippet(content: string): Promise { 5 | try { 6 | await vscode.env.clipboard.writeText(content); 7 | 8 | if (getConfig("showCopySuccessNotification")) { 9 | await showNotification(); 10 | } 11 | } catch { 12 | vscode.window.showErrorMessage( 13 | "Failed to copy the snippet to the clipboard" 14 | ); 15 | } 16 | } 17 | async function showNotification() { 18 | const doNotShowAgain = await vscode.window.showInformationMessage( 19 | "The snippet was copied to the clipboard", 20 | { modal: false }, 21 | "Do not show again" 22 | ); 23 | 24 | if (doNotShowAgain) { 25 | const config = vscode.workspace.getConfiguration("snippet"); 26 | await config.update( 27 | "showCopySuccessNotification", 28 | false, 29 | vscode.ConfigurationTarget.Global 30 | ); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import typescript from "@rollup/plugin-typescript"; 2 | import nodeResolve from "@rollup/plugin-node-resolve"; 3 | import commonjs from "@rollup/plugin-commonjs"; 4 | import json from "@rollup/plugin-json"; 5 | import terser from "@rollup/plugin-terser"; 6 | import externals from "rollup-plugin-node-externals"; 7 | 8 | 9 | const productionMode = process.env.NODE_ENV === "production"; 10 | 11 | const sourceMapEnabled = !productionMode; 12 | 13 | export default { 14 | input: "src/extension.ts", 15 | output: { 16 | dir: "out", 17 | format: "cjs", 18 | sourcemap: sourceMapEnabled, 19 | }, 20 | external: ["vscode"], 21 | plugins: [ 22 | commonjs(), 23 | json(), 24 | typescript({ 25 | compilerOptions: { 26 | module: "esnext", 27 | sourceMap: sourceMapEnabled, 28 | }, 29 | }), 30 | !productionMode && externals(), 31 | productionMode && nodeResolve(), 32 | productionMode && terser(), 33 | ], 34 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | This plugin is far from feature-complete. 4 | If you want to improve it, feel free to pick one of the [open issues](https://github.com/mre/vscode-snippet/issues) and give it a shot. 5 | In case you need any help, just add a comment to the issue to get a conversation started. :smiley: 6 | 7 | ## Dev setup 8 | 9 | Open this repo in VSCode, and you should be able to just Start the launch task "Launch Extension": 10 | 11 | ![screenshot](./assets/Screenshot%20launch%20task.png) 12 | 13 | You might need to wait a moment for the first `npm install` to finish. You can see progress in the "running build tasks" section of VSCode: 14 | 15 | ![screenshot](./assets/Screenshot%20build%20task.png) 16 | 17 | 18 | ## Packaging 19 | Run `make package` to package a `.vsix` file. 20 | 21 | ### additional commands 22 | To get a list of all available commands, try `make help`. 23 | To test your changes, go to the Debug panel in VSCode and click on the `play` button. This will start the extension in a new window where you can test it. 24 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Launch Extension", 9 | "type": "extensionHost", 10 | "request": "launch", 11 | "args": [ 12 | // development in clean environment - source: https://github.com/microsoft/vscode/issues/159572#issuecomment-1240523504 13 | "--profile=extension-dev", // optional, but recommended - will launch extension in a clean instance 14 | // "--profile-temp", // alternative - will launch extension in a clean instance everytime 15 | "--extensionDevelopmentPath=${workspaceFolder}", 16 | ], 17 | "outFiles": [ 18 | "${workspaceFolder}/out/**/*.js" 19 | ], 20 | "preLaunchTask": "npm: watch", 21 | } 22 | ] 23 | } -------------------------------------------------------------------------------- /assets/icons/history-dark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /assets/icons/history-light.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Matthias Endler 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/test/suite/toggleComments.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from "assert"; 2 | import * as vscode from "vscode"; 3 | import { after, before } from "mocha"; 4 | import { 5 | closeAllEditors, 6 | getResponseFromResultDocument, 7 | openDocumentAndFindSelectedText, 8 | } from "../testUtils"; 9 | 10 | suite("snippet.toggleComments", () => { 11 | suite("openInNewEditor is true", () => { 12 | before(async () => { 13 | await openDocumentAndFindSelectedText({ 14 | openInNewEditor: true, 15 | }); 16 | }); 17 | 18 | after(closeAllEditors); 19 | 20 | test("Toggles verbose state from false to true", async () => { 21 | await vscode.commands.executeCommand("snippet.toggleComments"); 22 | const response = getResponseFromResultDocument(); 23 | 24 | assert.strictEqual(response.verbose, true); 25 | }); 26 | 27 | test("Toggles verbose state from true to false", async () => { 28 | await vscode.commands.executeCommand("snippet.toggleComments"); 29 | const response = getResponseFromResultDocument(); 30 | 31 | assert.strictEqual(response.verbose, false); 32 | }); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "npm", 6 | "script": "install", 7 | "group": "build", 8 | "isBackground": true, 9 | "problemMatcher": [], 10 | "presentation": { 11 | "reveal": "silent" 12 | }, 13 | "label": "npm: install", 14 | "detail": "install dependencies from package" 15 | }, 16 | /* from: https://github.com/microsoft/vscode-extension-samples/blob/main/helloworld-sample/.vscode/tasks.json */ 17 | { 18 | "type": "npm", 19 | "script": "watch", 20 | "group": { 21 | "kind": "build", 22 | "isDefault": true 23 | }, 24 | "dependsOn": [ 25 | "npm: install" 26 | ], 27 | "isBackground": true, 28 | "problemMatcher": { 29 | "owner": "custom", 30 | "pattern": { 31 | "regexp": "IMJUSTHEREBECAUSETHERENEEDSTOBEADEFAULT - https://github.com/microsoft/vscode/issues/6209#issuecomment-1378126445" 32 | }, 33 | "background": { 34 | "activeOnStart": true, 35 | "beginsPattern": "rollup v", // e.g. 'rollup v3.18.0' 36 | "endsPattern": "waiting for changes..." 37 | }, 38 | }, 39 | "presentation": { 40 | "reveal": "silent" 41 | }, 42 | "label": "npm: watch", 43 | "detail": "compile & watch" 44 | } 45 | ] 46 | } -------------------------------------------------------------------------------- /src/test/suite/showPreviousAnswer.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from "assert"; 2 | import * as vscode from "vscode"; 3 | import { after, before } from "mocha"; 4 | import { 5 | closeAllEditors, 6 | getResponseFromResultDocument, 7 | openDocumentAndFindSelectedText, 8 | } from "../testUtils"; 9 | 10 | suite("snippet.showPreviousAnswer", () => { 11 | suite("openInNewEditor is true", () => { 12 | before(async () => { 13 | await openDocumentAndFindSelectedText({ 14 | openInNewEditor: true, 15 | }); 16 | }); 17 | 18 | after(closeAllEditors); 19 | 20 | test("Answer number does not go below 0", async () => { 21 | await vscode.commands.executeCommand("snippet.showPreviousAnswer"); 22 | const response = getResponseFromResultDocument(); 23 | 24 | assert.strictEqual(response.answerNumber, 0); 25 | }); 26 | 27 | test("Decrements answer number", async () => { 28 | await vscode.commands.executeCommand("snippet.showNextAnswer"); 29 | await vscode.commands.executeCommand("snippet.showNextAnswer"); 30 | await vscode.commands.executeCommand("snippet.showPreviousAnswer"); 31 | const response = getResponseFromResultDocument(); 32 | 33 | assert.strictEqual(response.answerNumber, 1); 34 | }); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /src/test/suite/showNextAnswer.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from "assert"; 2 | import * as vscode from "vscode"; 3 | import { after, before } from "mocha"; 4 | import { 5 | closeAllEditors, 6 | getResponseFromResultDocument, 7 | openDocumentAndFindSelectedText, 8 | } from "../testUtils"; 9 | 10 | suite("snippet.showNextAnswer", () => { 11 | suite("openInNewEditor is true", () => { 12 | before(async () => { 13 | await openDocumentAndFindSelectedText({ 14 | openInNewEditor: true, 15 | }); 16 | }); 17 | 18 | after(closeAllEditors); 19 | 20 | test("Initial answer number is 0", async () => { 21 | const response = getResponseFromResultDocument(); 22 | 23 | assert.strictEqual(response.answerNumber, 0); 24 | }); 25 | 26 | test("Increments answer number", async () => { 27 | const maxAnswers = 2; 28 | const answerNumbers = Array(maxAnswers).fill(0); 29 | const expectedAnswerNumbers = Array(maxAnswers) 30 | .fill(0) 31 | .map((_, i) => i + 1); 32 | 33 | for (let i = 0; i < maxAnswers; i++) { 34 | await vscode.commands.executeCommand("snippet.showNextAnswer"); 35 | const response = getResponseFromResultDocument(); 36 | answerNumbers[i] = response.answerNumber; 37 | } 38 | 39 | assert.deepEqual(answerNumbers, expectedAnswerNumbers); 40 | }); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /src/test/suite/findSelectedText.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from "assert"; 2 | import { after, before } from "mocha"; 3 | import * as vscode from "vscode"; 4 | import { 5 | closeAllEditors, 6 | getInitialDocument, 7 | getResponseFromResultDocument, 8 | openDocumentAndFindSelectedText, 9 | } from "../testUtils"; 10 | 11 | suite("snippet.findSelectedText", () => { 12 | suite("openInNewEditor is true", () => { 13 | const queryText = "query"; 14 | const language = "javascript"; 15 | 16 | before( 17 | async () => 18 | await openDocumentAndFindSelectedText({ 19 | language, 20 | queryText, 21 | openInNewEditor: true, 22 | }) 23 | ); 24 | 25 | after(closeAllEditors); 26 | 27 | test("Opens a new editor", async () => { 28 | assert.strictEqual(vscode.window.visibleTextEditors.length, 2); 29 | }); 30 | 31 | test("The text of the initial document is not changed", () => { 32 | const initialDocument = getInitialDocument(); 33 | 34 | assert.strictEqual(initialDocument.getText(), queryText); 35 | }); 36 | 37 | test("Sends the correct query", async () => { 38 | const response = getResponseFromResultDocument(); 39 | 40 | assert.strictEqual(response.query, queryText); 41 | }); 42 | 43 | test("Sends the correct language", async () => { 44 | const response = getResponseFromResultDocument(); 45 | 46 | assert.strictEqual(response.language, language); 47 | }); 48 | }); 49 | }); 50 | -------------------------------------------------------------------------------- /src/test/suite/find.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from "assert"; 2 | import * as vscode from "vscode"; 3 | import { after, before, afterEach } from "mocha"; 4 | import { 5 | closeAllEditors, 6 | getInitialDocument, 7 | getResponseFromResultDocument, 8 | openDocumentAndFind, 9 | } from "../testUtils"; 10 | import * as sinon from "sinon"; 11 | 12 | suite("snippet.find", () => { 13 | suite("openInNewEditor is true", () => { 14 | const queryText = "sort an array"; 15 | const language = "javascript"; 16 | const documentText = "let i = 0;"; 17 | 18 | before( 19 | async () => 20 | await openDocumentAndFind({ 21 | language, 22 | documentText, 23 | queryText, 24 | openInNewEditor: true, 25 | }) 26 | ); 27 | 28 | after(closeAllEditors); 29 | 30 | afterEach(() => { 31 | sinon.restore(); 32 | }); 33 | 34 | test("Opens a new editor", async () => { 35 | assert.strictEqual(vscode.window.visibleTextEditors.length, 2); 36 | }); 37 | 38 | test("The text of the initial document is not changed", async () => { 39 | const initialDocument = getInitialDocument(); 40 | 41 | assert.strictEqual(initialDocument.getText(), documentText); 42 | }); 43 | 44 | test("Sends the correct query", async () => { 45 | const response = getResponseFromResultDocument(); 46 | 47 | assert.strictEqual(response.query, queryText); 48 | }); 49 | 50 | test("Sends the correct language", async () => { 51 | const response = getResponseFromResultDocument(); 52 | 53 | assert.strictEqual(response.language, language); 54 | }); 55 | }); 56 | }); 57 | -------------------------------------------------------------------------------- /src/completionManager.ts: -------------------------------------------------------------------------------- 1 | import SnippetsStorage, { TreeElement } from "./snippetsStorage"; 2 | import * as vscode from "vscode"; 3 | 4 | export class CompletionManager { 5 | constructor( 6 | private readonly context: vscode.ExtensionContext, 7 | private readonly snippets: SnippetsStorage, 8 | private readonly registeredFileExtensions = new Set() 9 | ) { 10 | for (const snippet of snippets.getSnippets()) { 11 | this.ensureRegistered(snippet); 12 | } 13 | 14 | snippets.onSnippetSave = (snippet) => { 15 | this.ensureRegistered(snippet); 16 | }; 17 | } 18 | 19 | private ensureRegistered(snippet: TreeElement): void { 20 | const fileExtension = snippet.data.fileExtension; 21 | 22 | if (!fileExtension) { 23 | return; 24 | } 25 | 26 | if (this.registeredFileExtensions.has(fileExtension)) { 27 | return; 28 | } 29 | 30 | const fileSelector: vscode.DocumentSelector = { 31 | pattern: `**/*${fileExtension}`, 32 | }; 33 | const provider = vscode.languages.registerCompletionItemProvider( 34 | fileSelector, 35 | ((snippets: SnippetsStorage) => ({ 36 | provideCompletionItems() { 37 | const completions: vscode.CompletionItem[] = []; 38 | 39 | for (const snippet of snippets.getSnippets()) { 40 | if (snippet.data.fileExtension === fileExtension) { 41 | const completion = new vscode.CompletionItem(snippet.data.label); 42 | completion.insertText = snippet.data.content; 43 | completion.detail = "[snippet]"; 44 | completion.documentation = snippet.data.content; 45 | completions.push(completion); 46 | } 47 | } 48 | 49 | return completions; 50 | }, 51 | }))(this.snippets) 52 | ); 53 | this.context.subscriptions.push(provider); 54 | this.registeredFileExtensions.add(fileExtension); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/provider.ts: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | import * as vscode from "vscode"; 3 | import { TextDocumentContentProvider, Uri } from "vscode"; 4 | import snippet from "./snippet"; 5 | import { getConfig } from "./config"; 6 | 7 | export default class SnippetProvider implements TextDocumentContentProvider { 8 | /** 9 | * 10 | * @param {vscode.Uri} uri - a fake uri 11 | * @returns {string} - Code Snippet 12 | **/ 13 | public async provideTextDocumentContent(uri?: Uri): Promise { 14 | const request = decodeRequest(uri); 15 | const response = await snippet.load( 16 | request.language, 17 | request.query, 18 | request.answerNumber 19 | ); 20 | 21 | if (response.data.trimLeft().startsWith("/LANG/QUESTION")) { 22 | return `404 NOT FOUND 23 | 24 | Unknown cheat sheet. Please try to reformulate your query. 25 | Query format: 26 | 27 | /LANG/QUESTION 28 | 29 | Examples: 30 | 31 | /python/read+json 32 | /golang/run+external+program 33 | /js/regex+search 34 | 35 | See /:help for more info. 36 | 37 | If the problem persists, file a GitHub issue at 38 | github.com/chubin/cheat.sh or ping @igor_chubin 39 | `; 40 | } 41 | 42 | return response.data; 43 | } 44 | } 45 | 46 | export function encodeRequest( 47 | query: string, 48 | language: string, 49 | verbose: boolean, 50 | answerNumber: number 51 | ): vscode.Uri { 52 | const data = JSON.stringify({ 53 | query: query, 54 | language: language, 55 | answerNumber, 56 | verbose, 57 | }); 58 | const titleTemplate = getConfig("title"); 59 | const title = titleTemplate.replace( 60 | /(\$\{(.*?)\})/g, 61 | (match: string, _, variableName: string) => { 62 | return variableName === "language" 63 | ? language 64 | : variableName === "query" 65 | ? query 66 | : variableName === "index" 67 | ? answerNumber 68 | : match; 69 | } 70 | ); 71 | return vscode.Uri.parse(`snippet:${title}?${data}`); 72 | } 73 | 74 | export function decodeRequest(uri: vscode.Uri): any { 75 | const obj = JSON.parse(uri.query); 76 | return obj; 77 | } 78 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | import { Disposable } from "vscode"; 3 | 4 | export function getConfig(param: string) { 5 | return vscode.workspace.getConfiguration("snippet")[param]; 6 | } 7 | 8 | class LanguageItem implements vscode.QuickPickItem { 9 | public label: string; 10 | 11 | constructor(label: string) { 12 | this.label = label; 13 | } 14 | } 15 | 16 | export async function pickLanguage() { 17 | const languages = await vscode.languages.getLanguages(); 18 | const disposables: Disposable[] = []; 19 | 20 | try { 21 | return await new Promise((resolve) => { 22 | const input = vscode.window.createQuickPick(); 23 | input.placeholder = "Select or enter programming language"; 24 | const default_items = []; 25 | languages.forEach(language => { 26 | default_items.push(new LanguageItem(language)); 27 | }); 28 | input.items = default_items; 29 | 30 | disposables.push( 31 | input.onDidChangeValue(v => { 32 | input.items = [new LanguageItem(v)].concat(default_items); 33 | }), 34 | input.onDidAccept(() => { 35 | resolve(input.value); 36 | }), 37 | input.onDidChangeSelection((items: LanguageItem[]) => { 38 | const item = items[0]; 39 | resolve(item.label); 40 | input.hide(); 41 | }), 42 | input.onDidHide(() => { 43 | resolve(undefined); 44 | input.dispose(); 45 | }) 46 | ); 47 | input.show(); 48 | }); 49 | } finally { 50 | disposables.forEach(d => d.dispose()); 51 | } 52 | } 53 | 54 | async function getDefaultLanguage() { 55 | const defaultLanguage: string = getConfig("defaultLanguage"); 56 | if (defaultLanguage && defaultLanguage.trim()) { 57 | return defaultLanguage; 58 | } 59 | return await pickLanguage(); 60 | } 61 | 62 | export async function getLanguage(): Promise { 63 | if (vscode.window.visibleTextEditors.length === 0) { 64 | return getDefaultLanguage(); 65 | } 66 | const editor = vscode.window.activeTextEditor; 67 | return editor.document.languageId; 68 | } 69 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | matrix: 12 | node-version: [16.x, 18.x] 13 | name: Node ${{ matrix.node-version }} 14 | steps: 15 | - uses: actions/checkout@v1 16 | 17 | - name: Setup node 18 | uses: actions/setup-node@v1 19 | with: 20 | node-version: ${{ matrix.node-version }} 21 | 22 | - name: Install Dependencies 23 | run: npm install 24 | 25 | - name: Lint 26 | run: npm run lint 27 | 28 | - name: Test (Linux) 29 | run: xvfb-run -a npm test 30 | if: runner.os == 'Linux' 31 | 32 | - name: Test (non-Linux) 33 | run: npm test 34 | if: runner.os != 'Linux' 35 | 36 | - name: Vscode package plugin 37 | uses: JCofman/vscodeaction@master 38 | with: 39 | args: package -o package.vsix 40 | 41 | - uses: actions/upload-artifact@v2 42 | with: 43 | name: package 44 | path: package.vsix 45 | 46 | release: 47 | if: startsWith(github.ref, 'refs/tags/v') && !endsWith(github.ref, '-pre') 48 | needs: build 49 | runs-on: ubuntu-latest 50 | name: Release 51 | steps: 52 | - uses: actions/checkout@v1 53 | 54 | - uses: actions/download-artifact@v2 55 | with: 56 | name: package 57 | 58 | - name: Publish to Open VSX Registry 59 | uses: HaaLeo/publish-vscode-extension@v1 60 | with: 61 | pat: ${{ secrets.OPEN_VSX_TOKEN }} 62 | extensionFile: package.vsix 63 | - name: Publish to Visual Studio Marketplace 64 | uses: HaaLeo/publish-vscode-extension@v1 65 | with: 66 | pat: ${{ secrets.PUBLISHER_TOKEN }} 67 | registryUrl: https://marketplace.visualstudio.com 68 | extensionFile: package.vsix 69 | 70 | pre-release: 71 | if: endsWith(github.ref, '-pre') 72 | needs: build 73 | runs-on: ubuntu-latest 74 | name: Pre-release 75 | steps: 76 | - uses: actions/checkout@v1 77 | 78 | - name: Setup node 79 | uses: actions/setup-node@v1 80 | with: 81 | node-version: 18.x 82 | 83 | - run: npm install 84 | 85 | - name: Vscode release plugin 86 | uses: JCofman/vscodeaction@master 87 | env: 88 | PUBLISHER_TOKEN: ${{ secrets.PUBLISHER_TOKEN }} 89 | with: 90 | args: publish -p $PUBLISHER_TOKEN --pre-release 91 | -------------------------------------------------------------------------------- /src/query.ts: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | import * as vscode from "vscode"; 4 | import { cache } from "./cache"; 5 | import SnippetsStorage from "./snippetsStorage"; 6 | import languages from "./languages"; 7 | 8 | function quickPickCustom( 9 | items: vscode.QuickPickItem[], 10 | clearActiveItems = true 11 | ): Promise { 12 | return new Promise((resolve) => { 13 | const quickPick = vscode.window.createQuickPick(); 14 | quickPick.title = 'Enter keywords for snippet search (e.g. "read file")'; 15 | quickPick.items = items; 16 | 17 | quickPick.onDidChangeValue(() => { 18 | if (clearActiveItems) { 19 | quickPick.activeItems = []; 20 | } 21 | }); 22 | 23 | quickPick.onDidAccept(() => { 24 | let search: string | vscode.QuickPickItem = ""; 25 | if (quickPick.activeItems.length) { 26 | search = quickPick.activeItems[0]; 27 | } else { 28 | search = quickPick.value; 29 | } 30 | quickPick.hide(); 31 | resolve(search); 32 | }); 33 | quickPick.show(); 34 | }); 35 | } 36 | 37 | export interface QueryResult { 38 | input: string; 39 | savedSnippetContent?: string; 40 | } 41 | 42 | export async function query( 43 | language: string, 44 | snippetsStorage: SnippetsStorage, 45 | suggestOnlySaved = false 46 | ): Promise { 47 | const suggestions = new Set( 48 | cache.state.get(`snippet_suggestions_${language}`, []) 49 | ); 50 | 51 | const suggestionsQuickItems: Array = []; 52 | const languageFileExtensions = languages.getExtensions(language); 53 | const savedSnippetDescription = "[saved snippet]"; 54 | 55 | for (const snippet of snippetsStorage.getSnippets()) { 56 | if (languageFileExtensions.includes(snippet.data.fileExtension)) { 57 | suggestionsQuickItems.push({ 58 | label: snippet.data.label, 59 | detail: snippet.data.content, 60 | description: savedSnippetDescription, 61 | }); 62 | } 63 | } 64 | 65 | if (!suggestOnlySaved) { 66 | for (const suggestion of suggestions) { 67 | const tempQuickItem: vscode.QuickPickItem = { 68 | label: suggestion, 69 | description: "", 70 | }; 71 | suggestionsQuickItems.push(tempQuickItem); 72 | } 73 | } 74 | 75 | const selectedItem = await quickPickCustom( 76 | suggestionsQuickItems, 77 | !suggestOnlySaved 78 | ); 79 | const input = 80 | typeof selectedItem === "string" ? selectedItem : selectedItem.label; 81 | const savedSnippetContent = 82 | typeof selectedItem === "string" || 83 | selectedItem.description !== savedSnippetDescription 84 | ? undefined 85 | : selectedItem.detail; 86 | 87 | if (!savedSnippetContent) { 88 | suggestions.add(input); 89 | cache.state.update( 90 | `snippet_suggestions_${language}`, 91 | [...suggestions].sort() 92 | ); 93 | } 94 | return { input, savedSnippetContent }; 95 | } 96 | -------------------------------------------------------------------------------- /src/backupManager.ts: -------------------------------------------------------------------------------- 1 | import { randomUUID } from "crypto"; 2 | import * as vscode from "vscode"; 3 | import { getConfig } from "./config"; 4 | import { formatUnixTime } from "./date"; 5 | import SnippetsStorage, { 6 | StorageOperation, 7 | TreeElement, 8 | } from "./snippetsStorage"; 9 | 10 | export interface Backup { 11 | id: string; 12 | dateUnix: number; 13 | elements: TreeElement[]; 14 | beforeOperation?: string; 15 | } 16 | 17 | export interface BackupItem extends vscode.QuickPickItem { 18 | item: Backup; 19 | } 20 | 21 | const STORAGE_KEY = "snippet.snippetBackupsStorageKey"; 22 | const MAX_BACKUPS = 10; 23 | 24 | export class BackupManager { 25 | private backups: Backup[] = []; 26 | private elementsBeforeRestore: TreeElement[] | null = null; 27 | 28 | constructor( 29 | private readonly context: vscode.ExtensionContext, 30 | private readonly snippets: SnippetsStorage 31 | ) { 32 | this.load(); 33 | snippets.onBeforeSave = (elements, operation) => 34 | this.makeBackup(elements, operation); 35 | } 36 | 37 | getBackupItems(): BackupItem[] { 38 | const items = this.backups.map((backup) => { 39 | const time = `${formatUnixTime(backup.dateUnix)}`; 40 | const detail = backup.beforeOperation 41 | ? `before "${backup.beforeOperation}"` 42 | : undefined; 43 | const description = `${this.snippets.getSnippetCount( 44 | backup.elements 45 | )} snippet${ 46 | this.snippets.getSnippetCount(backup.elements) === 1 ? "" : "s" 47 | }`; 48 | 49 | return { 50 | label: time, 51 | item: backup, 52 | description, 53 | detail, 54 | }; 55 | }); 56 | 57 | items.sort((a, b) => b.item.dateUnix - a.item.dateUnix); 58 | 59 | return items; 60 | } 61 | 62 | async restoreBackup(id: string) { 63 | const backup = this.backups.find((backup) => backup.id === id); 64 | 65 | if (!backup) { 66 | console.error(`Backup with id ${id} not found.`); 67 | return; 68 | } 69 | 70 | this.elementsBeforeRestore = this.snippets.getElements(); 71 | await this.snippets.replaceElements(backup.elements); 72 | } 73 | 74 | async undoLastRestore() { 75 | if (this.elementsBeforeRestore === null) { 76 | return; 77 | } 78 | 79 | await this.snippets.replaceElements(this.elementsBeforeRestore); 80 | this.elementsBeforeRestore = null; 81 | } 82 | 83 | private load(): void { 84 | this.backups = JSON.parse( 85 | this.context.globalState.get(STORAGE_KEY) || "[]" 86 | ) as Backup[]; 87 | } 88 | 89 | private async makeBackup( 90 | elements: TreeElement[], 91 | operation?: StorageOperation 92 | ) { 93 | if (!getConfig("saveBackups")) { 94 | return; 95 | } 96 | 97 | const backup: Backup = { 98 | id: randomUUID(), 99 | dateUnix: Date.now(), 100 | elements, 101 | beforeOperation: operation, 102 | }; 103 | 104 | this.backups.push(backup); 105 | 106 | if (this.backups.length > MAX_BACKUPS) { 107 | this.backups.shift(); 108 | } 109 | 110 | await this.save(); 111 | } 112 | 113 | private async save() { 114 | await this.context.globalState.update( 115 | STORAGE_KEY, 116 | JSON.stringify(this.backups) 117 | ); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/test/testUtils.ts: -------------------------------------------------------------------------------- 1 | import * as sinon from "sinon"; 2 | import * as vscode from "vscode"; 3 | import { MockResponseData } from "../snippet"; 4 | 5 | export function getResponseFromResultDocument(): MockResponseData { 6 | const editors = vscode.window.visibleTextEditors.filter( 7 | (x) => !x.document.isUntitled 8 | ); 9 | const last = editors[editors.length - 1]; 10 | if (!last) { 11 | throw new Error("Response document not found."); 12 | } 13 | const responseText = last.document.getText(); 14 | return JSON.parse(responseText); 15 | } 16 | 17 | export async function openDocument({ 18 | language = "javascript", 19 | documentText, 20 | openInNewEditor, 21 | }: { 22 | language?: string; 23 | documentText: string; 24 | openInNewEditor: boolean; 25 | }): Promise { 26 | const document = await vscode.workspace.openTextDocument({ 27 | language, 28 | content: documentText, 29 | }); 30 | await vscode.window.showTextDocument(document); 31 | 32 | const config = vscode.workspace.getConfiguration("snippet"); 33 | const configTarget = vscode.ConfigurationTarget.Global; 34 | await config.update("openInNewEditor", openInNewEditor, configTarget); 35 | } 36 | 37 | export async function openDocumentAndSelectText({ 38 | language = "javascript", 39 | queryText = Date.now().toString(), 40 | openInNewEditor, 41 | }: { 42 | language?: string; 43 | queryText?: string; 44 | openInNewEditor: boolean; 45 | }): Promise { 46 | await openDocument({ language, documentText: queryText, openInNewEditor }); 47 | 48 | vscode.window.activeTextEditor.selection = new vscode.Selection( 49 | 0, 50 | 0, 51 | 0, 52 | queryText.length 53 | ); 54 | } 55 | 56 | export async function openDocumentAndFindSelectedText({ 57 | language = "javascript", 58 | queryText = Date.now().toString(), 59 | openInNewEditor, 60 | }: { 61 | language?: string; 62 | queryText?: string; 63 | openInNewEditor: boolean; 64 | }): Promise { 65 | await openDocumentAndSelectText({ 66 | language, 67 | queryText, 68 | openInNewEditor, 69 | }); 70 | 71 | await vscode.commands.executeCommand("snippet.findSelectedText"); 72 | } 73 | 74 | export async function openDocumentAndFind({ 75 | queryText, 76 | language, 77 | documentText, 78 | openInNewEditor, 79 | }: { 80 | queryText: string; 81 | language: string; 82 | documentText: string; 83 | openInNewEditor: boolean; 84 | }): Promise { 85 | await openDocument({ language, documentText, openInNewEditor }); 86 | 87 | const createQuickPickStub = sinon.stub(vscode.window, "createQuickPick"); 88 | const quickPick = createQuickPickStub.wrappedMethod(); 89 | sinon.stub(quickPick, "show").callsFake(() => { 90 | // Ignore this call 91 | }); 92 | sinon.stub(quickPick, "value").value(queryText); 93 | const onDidAcceptStub = sinon.stub(quickPick, "onDidAccept"); 94 | onDidAcceptStub.callsFake((listener) => { 95 | const disposable = onDidAcceptStub.wrappedMethod(listener); 96 | listener(); 97 | return disposable; 98 | }); 99 | createQuickPickStub.returns(quickPick); 100 | 101 | await vscode.commands.executeCommand("snippet.find"); 102 | } 103 | 104 | export async function closeAllEditors(): Promise { 105 | await vscode.commands.executeCommand("workbench.action.closeAllEditors"); 106 | } 107 | 108 | export function getInitialDocument(): vscode.TextDocument { 109 | return ( 110 | vscode.window.visibleTextEditors.find( 111 | (editor) => editor !== vscode.window.activeTextEditor 112 | )?.document ?? vscode.window.activeTextEditor.document 113 | ); 114 | } 115 | -------------------------------------------------------------------------------- /src/snippetsTreeProvider.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | import SnippetsStorage from "./snippetsStorage"; 3 | 4 | export class SnippetsTreeProvider 5 | implements 6 | vscode.TreeDataProvider, 7 | vscode.TreeDragAndDropController 8 | { 9 | dropMimeTypes = ["application/vnd.code.tree.snippetsView"]; 10 | dragMimeTypes = ["text/uri-list"]; 11 | 12 | private _onDidChangeTreeData: vscode.EventEmitter< 13 | SnippetsTreeItem | undefined | null | void 14 | > = new vscode.EventEmitter(); 15 | 16 | readonly onDidChangeTreeData: vscode.Event< 17 | SnippetsTreeItem | undefined | null | void 18 | > = this._onDidChangeTreeData.event; 19 | 20 | constructor( 21 | context: vscode.ExtensionContext, 22 | public readonly storage: SnippetsStorage 23 | ) { 24 | const view = vscode.window.createTreeView("snippetsView", { 25 | treeDataProvider: this, 26 | showCollapseAll: true, 27 | canSelectMany: false, 28 | dragAndDropController: this, 29 | }); 30 | context.subscriptions.push(view); 31 | this.storage.onSave = () => this.refresh(); 32 | } 33 | 34 | getTreeItem( 35 | element: SnippetsTreeItem 36 | ): vscode.TreeItem | Thenable { 37 | return element; 38 | } 39 | 40 | getChildren( 41 | element?: SnippetsTreeItem | undefined 42 | ): vscode.ProviderResult { 43 | return ( 44 | this.storage.getElement(element?.id)?.childIds?.map((id) => { 45 | const curElement = this.storage.getElement(id); 46 | 47 | return new SnippetsTreeItem( 48 | curElement.data.label, 49 | curElement.data.content, 50 | curElement.childIds == null 51 | ? vscode.TreeItemCollapsibleState.None 52 | : vscode.TreeItemCollapsibleState.Expanded, 53 | id, 54 | curElement.data.fileExtension 55 | ); 56 | }) ?? [] 57 | ); 58 | } 59 | 60 | handleDrag( 61 | source: readonly SnippetsTreeItem[], 62 | dataTransfer: vscode.DataTransfer, 63 | token: vscode.CancellationToken 64 | ): void | Thenable { 65 | if (token.isCancellationRequested) { 66 | return; 67 | } 68 | 69 | if (source.length > 1) { 70 | throw new Error("Expected canSelectMany to be false"); 71 | } 72 | 73 | dataTransfer.set( 74 | "application/vnd.code.tree.snippetsView", 75 | new vscode.DataTransferItem(source[0]) 76 | ); 77 | } 78 | 79 | handleDrop( 80 | target: SnippetsTreeItem | undefined, 81 | dataTransfer: vscode.DataTransfer, 82 | token: vscode.CancellationToken 83 | ): void | Thenable { 84 | if (token.isCancellationRequested) { 85 | return; 86 | } 87 | 88 | const transferItem = dataTransfer.get( 89 | "application/vnd.code.tree.snippetsView" 90 | ); 91 | 92 | if (!transferItem) { 93 | return; 94 | } 95 | 96 | return this.storage.moveElement(transferItem.value.id, target?.id); 97 | } 98 | 99 | private refresh(): void { 100 | this._onDidChangeTreeData.fire(); 101 | } 102 | } 103 | 104 | export class SnippetsTreeItem extends vscode.TreeItem { 105 | constructor( 106 | public readonly label: string, 107 | content: string, 108 | public readonly collapsibleState: vscode.TreeItemCollapsibleState, 109 | id: string, 110 | fileExtension?: string 111 | ) { 112 | super(label, collapsibleState); 113 | 114 | this.id = id; 115 | this.tooltip = content; 116 | this.contextValue = 117 | collapsibleState === vscode.TreeItemCollapsibleState.None 118 | ? "snippet" 119 | : "folder"; 120 | 121 | if (collapsibleState !== vscode.TreeItemCollapsibleState.None) { 122 | return; 123 | } 124 | 125 | this.resourceUri = vscode.Uri.file(`./some-file${fileExtension || ""}`); 126 | this.command = { 127 | arguments: [this.id], 128 | command: "snippet.insertSnippet", 129 | title: "Insert code", 130 | tooltip: "Insert code", 131 | }; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/extension.ts: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | import * as vscode from "vscode"; 4 | import { BackupManager } from "./backupManager"; 5 | import { cache } from "./cache"; 6 | import { CompletionManager } from "./completionManager"; 7 | import * as endpoints from "./endpoints"; 8 | import SnippetProvider from "./provider"; 9 | import SnippetsStorage from "./snippetsStorage"; 10 | import { SnippetsTreeProvider } from "./snippetsTreeProvider"; 11 | 12 | export function activate(ctx: vscode.ExtensionContext) { 13 | const snippetStorageKey = "snippet.snippetsStorageKey"; 14 | ctx.globalState.setKeysForSync([snippetStorageKey]); 15 | 16 | const snippetsStorage = new SnippetsStorage(ctx, snippetStorageKey); 17 | const snippetsTreeProvider = new SnippetsTreeProvider(ctx, snippetsStorage); 18 | new CompletionManager(ctx, snippetsStorage); 19 | const backupManager = new BackupManager(ctx, snippetsStorage); 20 | 21 | ctx.subscriptions.push( 22 | vscode.commands.registerCommand("snippet.find", () => 23 | endpoints.findDefault(snippetsStorage) 24 | ) 25 | ); 26 | ctx.subscriptions.push( 27 | vscode.commands.registerCommand("snippet.findForLanguage", () => 28 | endpoints.findForLanguage(snippetsStorage) 29 | ) 30 | ); 31 | ctx.subscriptions.push( 32 | vscode.commands.registerCommand("snippet.findInplace", () => 33 | endpoints.findInplace(snippetsStorage) 34 | ) 35 | ); 36 | ctx.subscriptions.push( 37 | vscode.commands.registerCommand("snippet.findInNewEditor", () => 38 | endpoints.findInNewEditor(snippetsStorage) 39 | ) 40 | ); 41 | ctx.subscriptions.push( 42 | vscode.commands.registerCommand( 43 | "snippet.findSelectedText", 44 | endpoints.findSelectedText 45 | ) 46 | ); 47 | ctx.subscriptions.push( 48 | vscode.commands.registerCommand("snippet.showPreviousAnswer", () => 49 | endpoints.showPreviousAnswer(snippetsStorage) 50 | ) 51 | ); 52 | ctx.subscriptions.push( 53 | vscode.commands.registerCommand("snippet.showNextAnswer", () => 54 | endpoints.showNextAnswer(snippetsStorage) 55 | ) 56 | ); 57 | ctx.subscriptions.push( 58 | vscode.commands.registerCommand( 59 | "snippet.toggleComments", 60 | endpoints.toggleComments 61 | ) 62 | ); 63 | 64 | ctx.subscriptions.push( 65 | vscode.commands.registerCommand( 66 | "snippet.saveSnippet", 67 | endpoints.saveSnippet(snippetsTreeProvider) 68 | ) 69 | ); 70 | ctx.subscriptions.push( 71 | vscode.commands.registerCommand( 72 | "snippet.insertSnippet", 73 | endpoints.insertSnippet(snippetsTreeProvider) 74 | ) 75 | ); 76 | ctx.subscriptions.push( 77 | vscode.commands.registerCommand( 78 | "snippet.deleteSnippet", 79 | endpoints.deleteSnippet(snippetsTreeProvider) 80 | ) 81 | ); 82 | ctx.subscriptions.push( 83 | vscode.commands.registerCommand( 84 | "snippet.renameSnippet", 85 | endpoints.renameSnippet(snippetsTreeProvider) 86 | ) 87 | ); 88 | ctx.subscriptions.push( 89 | vscode.commands.registerCommand( 90 | "snippet.copySnippet", 91 | endpoints.copySnippet(snippetsTreeProvider) 92 | ) 93 | ); 94 | ctx.subscriptions.push( 95 | vscode.commands.registerCommand( 96 | "snippet.findAndCopy", 97 | endpoints.findAndCopy(snippetsStorage) 98 | ) 99 | ); 100 | ctx.subscriptions.push( 101 | vscode.commands.registerCommand( 102 | "snippet.createFolder", 103 | endpoints.createFolder(snippetsTreeProvider) 104 | ) 105 | ); 106 | ctx.subscriptions.push( 107 | vscode.commands.registerCommand( 108 | "snippet.restoreBackups", 109 | endpoints.showBackups(backupManager) 110 | ) 111 | ); 112 | 113 | if (process.env.NODE_ENV === "test") { 114 | // Expose the "moveElement" method for test purposes 115 | ctx.subscriptions.push( 116 | vscode.commands.registerCommand( 117 | "snippet.test_moveElement", 118 | async (sourceId, targetId) => 119 | await snippetsStorage.moveElement(sourceId, targetId) 120 | ) 121 | ); 122 | } 123 | 124 | cache.state = ctx.globalState; 125 | const provider = new SnippetProvider(); 126 | ctx.subscriptions.push( 127 | vscode.workspace.registerTextDocumentContentProvider("snippet", provider) 128 | ); 129 | } 130 | -------------------------------------------------------------------------------- /src/snippet.ts: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | import * as vscode from "vscode"; 4 | import axios, { AxiosHeaders, AxiosRequestConfig, AxiosResponse } from "axios"; 5 | import { getConfig } from "./config"; 6 | import { HttpProxyAgent } from "http-proxy-agent"; 7 | 8 | export interface Response { 9 | language: string; 10 | data: string; 11 | } 12 | 13 | export interface MockResponseData { 14 | language: string; 15 | query: string; 16 | verbose: boolean; 17 | answerNumber: number; 18 | } 19 | 20 | class Snippet { 21 | // Current language we're searching for 22 | currLanguage?: string; 23 | 24 | // Query string that was executed (not escaped) 25 | currQuery?: string; 26 | 27 | // Answer number that was shown 28 | currNum: number; 29 | 30 | // Current state of comments (for toggleComments) 31 | verboseState: boolean; 32 | 33 | // Local cache for saving unnecessary requests 34 | requestCache: object; 35 | 36 | constructor() { 37 | this.currNum = 0; 38 | this.verboseState = getConfig("verbose"); 39 | this.requestCache = new Object(); 40 | } 41 | 42 | toggleVerbose() { 43 | this.verboseState = !this.verboseState; 44 | } 45 | 46 | async load(language: string, query: string, num: number): Promise { 47 | this.currLanguage = language; 48 | this.currQuery = query; 49 | this.currNum = num; 50 | 51 | const response = await this._doRequest(); 52 | return { language, data: response.data }; 53 | } 54 | 55 | getNextAnswerNumber(): number { 56 | this.currNum++; 57 | return this.currNum; 58 | } 59 | 60 | getPreviousAnswerNumber(): number | null { 61 | if (this.currNum == 0) { 62 | return null; 63 | } 64 | this.currNum--; 65 | return this.currNum; 66 | } 67 | 68 | getCurrentQuery(): string | undefined { 69 | return this.currQuery; 70 | } 71 | 72 | getCurrentAnswerNumber(): number { 73 | return this.currNum; 74 | } 75 | 76 | getVerbose(): boolean { 77 | return this.verboseState; 78 | } 79 | 80 | private _requestConfig(): AxiosRequestConfig { 81 | const config: AxiosRequestConfig = { 82 | // Fake user agent to get plain-text output. 83 | // See https://github.com/chubin/cheat.sh/blob/1e21d96d065b6cce7d198c1a3edba89081c78a0b/bin/srv.py#L47 84 | headers: { 85 | "User-Agent": "curl/7.43.0", 86 | }, 87 | }; 88 | 89 | // Apply proxy setting if provided 90 | const proxy = vscode.workspace.getConfiguration("http")["proxy"]; 91 | if (proxy !== "") { 92 | const agent = new HttpProxyAgent(proxy); 93 | config["agent"] = agent; 94 | } 95 | return config; 96 | } 97 | 98 | private getUrl(language: string, query: string) { 99 | const baseUrl = getConfig("baseUrl"); 100 | const num = this.currNum; 101 | const params = this.verboseState ? "qT" : "QT"; 102 | const path = `/vscode:${language}/${query}/${num}?${params}&style=bw`; 103 | return baseUrl + path; 104 | } 105 | 106 | private async _doRequest(): Promise { 107 | const query = encodeURI(this.currQuery.replace(/ /g, "+")); 108 | const url = this.getUrl(this.currLanguage, query); 109 | const data = this.requestCache[url]; 110 | if (data) { 111 | return data; 112 | } 113 | try { 114 | const res = 115 | process.env.NODE_ENV === "test" 116 | ? await this.getMock() 117 | : await axios.get(url, this._requestConfig()); 118 | this.requestCache[url] = res; 119 | return res; 120 | } catch (err) { 121 | vscode.window.showErrorMessage( 122 | "Error while fetching snippets : " + err.toJSON().message 123 | ); 124 | } 125 | } 126 | 127 | private async getMock(): Promise { 128 | return { 129 | data: this.getMockResponseData(), 130 | status: 200, 131 | statusText: "OK", 132 | headers: {}, 133 | config: { headers: new AxiosHeaders() }, 134 | }; 135 | } 136 | 137 | private getMockResponseData(): string { 138 | const result: MockResponseData = { 139 | language: this.currLanguage, 140 | query: this.currQuery, 141 | verbose: this.verboseState, 142 | answerNumber: this.currNum, 143 | }; 144 | return JSON.stringify(result); 145 | } 146 | } 147 | 148 | export default new Snippet(); 149 | -------------------------------------------------------------------------------- /src/test/suite/restoreBackups.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from "assert"; 2 | import { afterEach } from "mocha"; 3 | import * as sinon from "sinon"; 4 | import * as vscode from "vscode"; 5 | import { MessageItem } from "vscode"; 6 | import { BackupItem } from "../../backupManager"; 7 | import { cache } from "../../cache"; 8 | import SnippetsStorage, { TreeElement } from "../../snippetsStorage"; 9 | import { closeAllEditors, openDocumentAndSelectText } from "../testUtils"; 10 | 11 | suite("snippet.restoreBackups", () => { 12 | afterEach(() => { 13 | sinon.restore(); 14 | }); 15 | 16 | test("No backups initially", async () => { 17 | const backups = await getBackups(); 18 | 19 | assert.strictEqual(backups.length, 0); 20 | }); 21 | 22 | test("Creates a backup after rename", async () => { 23 | sinon.stub(vscode.window, "showInputBox").callsFake(() => { 24 | return Promise.resolve("new name"); 25 | }); 26 | const originalElementsJson = getElementsJson(); 27 | const snippet = getAnySnippet(originalElementsJson); 28 | 29 | await vscode.commands.executeCommand("snippet.renameSnippet", { 30 | id: snippet.data.id, 31 | }); 32 | const backups = await getBackups(); 33 | 34 | assert.strictEqual(backups.length, 1); 35 | assert.strictEqual( 36 | JSON.stringify(backups[0].item.elements), 37 | originalElementsJson 38 | ); 39 | }); 40 | 41 | test("Creates a backup after delete", async () => { 42 | sinon.stub(vscode.window, "showInformationMessage").callsFake(() => { 43 | return Promise.resolve("Yes" as unknown as MessageItem); 44 | }); 45 | const originalElementsJson = getElementsJson(); 46 | const snippet = getAnySnippet(originalElementsJson); 47 | 48 | await vscode.commands.executeCommand("snippet.deleteSnippet", { 49 | id: snippet.data.id, 50 | }); 51 | const backups = await getBackups(); 52 | 53 | assert.strictEqual(backups.length, 2); 54 | assert.strictEqual( 55 | JSON.stringify(backups[0].item.elements), 56 | originalElementsJson 57 | ); 58 | }); 59 | 60 | test("Creates a backup after save", async () => { 61 | await openDocumentAndSelectText({ 62 | language: "javascript", 63 | queryText: "query", 64 | openInNewEditor: true, 65 | }); 66 | sinon.stub(vscode.window, "showQuickPick").callsFake((folders) => { 67 | return folders[0]; 68 | }); 69 | sinon.stub(vscode.window, "showInputBox").callsFake(() => { 70 | return Promise.resolve("new snippet"); 71 | }); 72 | const originalElementsJson = getElementsJson(); 73 | 74 | await vscode.commands.executeCommand("snippet.saveSnippet"); 75 | sinon.restore(); 76 | const backups = await getBackups(); 77 | await closeAllEditors(); 78 | 79 | assert.strictEqual(backups.length, 3); 80 | assert.strictEqual( 81 | JSON.stringify(backups[0].item.elements), 82 | originalElementsJson 83 | ); 84 | }); 85 | 86 | test("Creates a backup after move", async () => { 87 | const originalElementsJson = getElementsJson(); 88 | const elements = parseElements(originalElementsJson); 89 | 90 | await vscode.commands.executeCommand( 91 | "snippet.test_moveElement", 92 | elements[2].data.id, 93 | elements[1].data.id 94 | ); 95 | const backups = await getBackups(); 96 | 97 | assert.strictEqual(backups.length, 4); 98 | assert.strictEqual( 99 | JSON.stringify(backups[0].item.elements), 100 | originalElementsJson 101 | ); 102 | }); 103 | 104 | test("Restores backup", async () => { 105 | sinon.stub(vscode.window, "showInputBox").callsFake(() => { 106 | return Promise.resolve("new name"); 107 | }); 108 | sinon.stub(vscode.window, "showInformationMessage").callsFake(() => { 109 | return Promise.resolve("Ok" as unknown as MessageItem); 110 | }); 111 | const originalElementsJson = getElementsJson(); 112 | const snippet = getAnySnippet(originalElementsJson); 113 | 114 | await vscode.commands.executeCommand("snippet.renameSnippet", { 115 | id: snippet.data.id, 116 | }); 117 | const backups = await getBackups(true); 118 | 119 | assert.strictEqual(backups.length, 5); 120 | assert.strictEqual(getElementsJson(), originalElementsJson); 121 | }); 122 | 123 | test("Undoes backup restoration", async () => { 124 | sinon.stub(vscode.window, "showInformationMessage").callsFake(() => { 125 | return Promise.resolve("Undo" as unknown as MessageItem); 126 | }); 127 | sinon.stub(vscode.window, "showInputBox").callsFake(() => { 128 | return Promise.resolve("new name"); 129 | }); 130 | const originalElementsJson = getElementsJson(); 131 | const snippet = getAnySnippet(originalElementsJson); 132 | 133 | await vscode.commands.executeCommand("snippet.renameSnippet", { 134 | id: snippet.data.id, 135 | }); 136 | const elementsAfterChange = getElementsJson(); 137 | const backups = await getBackups(true); 138 | 139 | assert.strictEqual(backups.length, 6); 140 | assert.notStrictEqual(getElementsJson(), originalElementsJson); 141 | assert.strictEqual(getElementsJson(), elementsAfterChange); 142 | }); 143 | 144 | test("Saves up to 10 backups", async () => { 145 | sinon.stub(vscode.window, "showInputBox").callsFake(() => { 146 | return Promise.resolve("new name"); 147 | }); 148 | const originalElementsJson = getElementsJson(); 149 | const snippet = getAnySnippet(originalElementsJson); 150 | 151 | for (let i = 0; i < 11; i++) { 152 | await vscode.commands.executeCommand("snippet.renameSnippet", { 153 | id: snippet.data.id, 154 | }); 155 | } 156 | const backups = await getBackups(); 157 | 158 | assert.strictEqual(backups.length, 10); 159 | }); 160 | }); 161 | 162 | async function getBackups(restoreLatest = false): Promise { 163 | return new Promise((resolve) => { 164 | const showQuickPickStub = sinon.stub(vscode.window, "showQuickPick"); 165 | 166 | let result: BackupItem[] = []; 167 | showQuickPickStub.callsFake(async (backups: BackupItem[]) => { 168 | result = backups; 169 | return restoreLatest && backups[0] ? backups[0] : null; 170 | }); 171 | 172 | vscode.commands.executeCommand("snippet.restoreBackups").then(() => { 173 | resolve(result); 174 | }); 175 | }); 176 | } 177 | 178 | function getElementsJson(): string { 179 | return cache.state.get("snippet.snippetsStorageKey") || "[]"; 180 | } 181 | 182 | function parseElements(json: string): TreeElement[] { 183 | return JSON.parse(json); 184 | } 185 | 186 | function getAnySnippet(elementsJson: string): TreeElement { 187 | return parseElements(elementsJson).find((x) => !SnippetsStorage.isFolder(x)); 188 | } 189 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # vscode-snippet 4 | 5 | [![The MIT License](https://img.shields.io/badge/license-MIT-orange.svg?style=flat-square)](http://opensource.org/licenses/MIT) 6 | [![GitHub](https://img.shields.io/github/release/mre/vscode-snippet.svg?style=flat-square)](https://github.com/mre/vscode-snippet/releases) 7 | [![GitHub Marketplace](https://img.shields.io/badge/Marketplace-Snippet-blue.svg?colorA=24292e&colorB=0366d6&style=flat&longCache=true&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAM6wAADOsB5dZE0gAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAERSURBVCiRhZG/SsMxFEZPfsVJ61jbxaF0cRQRcRJ9hlYn30IHN/+9iquDCOIsblIrOjqKgy5aKoJQj4O3EEtbPwhJbr6Te28CmdSKeqzeqr0YbfVIrTBKakvtOl5dtTkK+v4HfA9PEyBFCY9AGVgCBLaBp1jPAyfAJ/AAdIEG0dNAiyP7+K1qIfMdonZic6+WJoBJvQlvuwDqcXadUuqPA1NKAlexbRTAIMvMOCjTbMwl1LtI/6KWJ5Q6rT6Ht1MA58AX8Apcqqt5r2qhrgAXQC3CZ6i1+KMd9TRu3MvA3aH/fFPnBodb6oe6HM8+lYHrGdRXW8M9bMZtPXUji69lmf5Cmamq7quNLFZXD9Rq7v0Bpc1o/tp0fisAAAAASUVORK5CYII=)](https://marketplace.visualstudio.com/items?itemName=vscode-snippet.Snippet) 8 | 9 | A Visual Studio Code extension for [cht.sh](https://cht.sh/). 10 | [Watch this lightning talk to learn more](https://www.youtube.com/watch?v=edGVRJf6uvg). 11 | 12 | ## Features 13 | 14 | - Zero configuration: works out of the box. 15 | - Automatically detects programming language from current editor window. 16 | 17 | ## Config options 18 | 19 | - `openInNewEditor`: open snippets or in new editor window (default) in line with current document. 20 | - `verbose`: add comments around code snippets. 21 | - `baseUrl`: base url of the cheat server ([see cheat.sh documentation](https://github.com/chubin/cheat.sh/issues/98#issuecomment-412472258)) 22 | - `http.proxy`: VS Code proxy setting. If set, requests made by vscode-snippet will be sent through provided proxy ([see Visual Studio Code network settings](https://code.visualstudio.com/docs/setup/network)) 23 | - `defaultLanguage`: Programming language name in lower case to use as default language when there is no open editor window. 24 | - `title`: Template string of a snippet title. You can use the following variables: 25 | - ${language} - the programming language 26 | - ${query} - the snippet query (search text) 27 | - ${index} - the index of the snippet (e.g. 2 for the third answer) 28 | - `insertWithDoubleClick`: insert snippet with double click. 29 | - `showCopySuccessNotification`: Whether to show a notification after the snippet is copied to the clipboard. 30 | - `saveBackups`: Whether to create backups of the snippets. 31 | 32 | ## Installation 33 | 34 | Install this extension from the [VSCode 35 | Marketplace](https://marketplace.visualstudio.com/items?itemName=vscode-snippet.Snippet) 36 | 37 | ## Usage 38 | 39 | ### Search for a snippet 40 | 41 | 1. Hit ⌘ Command + ⇧ Shift + p 42 | 2. Run `Snippet: Find`. 43 | 3. Type your query and hit enter. 44 | 45 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/find.gif) 46 | 47 | ### Moving between answers 48 | 49 | Sometimes the first answer is not what you're looking for. 50 | In that case, use `Snippet: Show next answer` and `Snippet: Show previous answer` to show alternative snippets. 51 | 52 | ### Search for snippet based on selected text 53 | 54 | 1. Select some text in an editor window. 55 | 2. Right click and choose "Find snippet from selected text" 56 | 57 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/findSelectedMenu.gif) 58 | 59 | Alternatively, you can also run the `Snippet: Find Selected Text` from the 60 | command menu: 61 | 62 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/findSelected.gif) 63 | 64 | You can configure a keyboard shortcut. By default this is ⌘ Command + ⇧ Shift + s: 65 | 66 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/findSelectedShortcut.gif) 67 | 68 | ### Saving a snippet 69 | 70 | 1. Select some text in an editor window. 71 | 2. Right click and choose "Save snippet" 72 | 3. Select a folder for the snippet 73 | 4. Enter a name of the snippet 74 | 5. Press Enter 75 | 76 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/save.gif) 77 | 78 | ### Inserting a snippet 79 | 80 | 1. Open the Explorer by clicking Ctrl + Shift + E 81 | 2. Open the Snippets section 82 | 3. Click on the snippet that you want to insert 83 | 84 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/insert.gif) 85 | 86 | ### Creating a folder for the snippets 87 | 88 | 1. Open the Snippets section 89 | 2. Click on the + icon (alternatively, you can right click on any snippet or a folder and select "New Folder") 90 | 3. Enter a name of the folder 91 | 4. Press Enter 92 | 93 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/create-folder.gif) 94 | 95 | ### Renaming a snippet or a folder 96 | 97 | 1. Open the Snippets section 98 | 2. Right click on the snippet or a folder that you want to rename 99 | 3. Select "Rename" 100 | 4. Enter a new name 101 | 5. Press Enter 102 | 103 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/rename.gif) 104 | 105 | ### Deleting a snippet or a folder 106 | 107 | 1. Open the Snippets section 108 | 2. Right click on the snippet or a folder that you want to delete 109 | 3. Select "Delete" 110 | 4. Confirm your choice 111 | 112 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/delete.gif) 113 | 114 | ### Copying a snippet to the clipboard 115 | 116 | 1. Open the Snippets section 117 | 2. Right click on the snippet that you want to copy 118 | 3. Select "Copy" 119 | 120 | ### Moving a snippet or a folder 121 | 122 | You can move snippets or folders in the Snippets view by dragging and dropping them 123 | 124 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/move.gif) 125 | 126 | ### IntelliSense 127 | 128 | Saved snippets are displayed in IntelliSense 129 | 130 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/intellisense.gif) 131 | 132 | ### Searching for saved snippets 133 | 134 | ![Preview](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/search.gif) 135 | 136 | ## Restoring snippets from backups 137 | 138 | ### Restoring with the built-in backup mechanism 139 | 140 | vscode-snippet creates backups of your snippets when you delete, rename, move or save snippets. These backups are stored **locally** on your computer. 141 | 142 | To restore a backup: 143 | 144 | 1. Open the Snippets section 145 | 2. Click on the ![History icon](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/history.png) icon (alternatively, you can run the "Restore backups" command) 146 | 3. Select one of the backups from the list 147 | 148 | ![Demo of restoring backups](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/restore-backups.gif) 149 | 150 | ### Restoring with the VSCode settings sync 151 | 152 | If you have [VSCode settings sync](https://code.visualstudio.com/docs/editor/settings-sync) enabled, you can restore snippets by using VSCode's built-in backup mechanisms: [https://code.visualstudio.com/docs/editor/settings-sync#\_restoring-data](https://code.visualstudio.com/docs/editor/settings-sync#_restoring-data) 153 | 154 | ## Exporting snippets 155 | 156 | VSCode stores snippets in the `state.vscdb` file in a `JSON` format. 157 | 158 | To export the snippets: 159 | 160 | 1. Find the `state.vscdb` file 161 | - On Ubuntu Linux: `~/.config/Code/User/globalStorage/state.vscdb` 162 | - On Windows: `AppData\Roaming\Code\User\globalStorage\state.vscdb` 163 | - On macOS: `~/Library/Application Support/Code/User/globalStorage/state.vscdb` 164 | 2. Inspect the content of this file using some tool that can open SQLite files, for example: [https://inloop.github.io/sqlite-viewer](https://inloop.github.io/sqlite-viewer) 165 | 1. On this website, upload the `state.vscdb` file and run the following command: 166 | ```sql 167 | SELECT * FROM 'ItemTable' WHERE key like 'vscode-snippet.snippet' 168 | ``` 169 | ![SQLite Viewer](https://raw.githubusercontent.com/mre/vscode-snippet/master/contrib/snippets-storage/vscdb.png) 2. Then click "Execute". You should get a single row with the key `vscode-snippet.snippet` and a `JSON` value. This `JSON` contains all of your snippets. 170 | 171 | ## Contributing 172 | 173 | See [CONTRIBUTING.md](./CONTRIBUTING.md) 174 | -------------------------------------------------------------------------------- /src/snippetsStorage.ts: -------------------------------------------------------------------------------- 1 | import { randomUUID } from "crypto"; 2 | import * as vscode from "vscode"; 3 | 4 | export interface TreeElement { 5 | data: TreeElementData; 6 | parentId?: string; 7 | childIds?: string[]; 8 | } 9 | 10 | export interface TreeElementData { 11 | id: string; 12 | label: string; 13 | content: string; 14 | fileExtension?: string; 15 | } 16 | 17 | export interface FolderListItem extends vscode.QuickPickItem { 18 | id: string; 19 | label: string; 20 | } 21 | 22 | export enum StorageOperation { 23 | Save = "save snippet", 24 | LoadDefault = "load default snippets", 25 | Delete = "delete", 26 | Rename = "rename", 27 | CreateFolder = "create folder", 28 | Move = "move", 29 | } 30 | 31 | export default class SnippetsStorage { 32 | public onSave?: () => void; 33 | public onBeforeSave?: ( 34 | elements: TreeElement[], 35 | operation?: StorageOperation 36 | ) => void; 37 | public onSnippetSave?: (snippet: TreeElement) => void; 38 | private readonly elements = new Map(); 39 | private rootId = ""; 40 | 41 | constructor( 42 | private readonly context: vscode.ExtensionContext, 43 | private readonly storageKey: string 44 | ) { 45 | this.load(); 46 | 47 | if (!this.elements.size) { 48 | this.loadDefaultElements(); 49 | } 50 | } 51 | 52 | getElements(): TreeElement[] { 53 | return [...this.elements.values()]; 54 | } 55 | 56 | getFoldersList(): FolderListItem[] { 57 | const result: FolderListItem[] = []; 58 | 59 | this.populateFoldersList(result, this.getElement(this.rootId), { 60 | id: this.rootId, 61 | label: "/", 62 | }); 63 | result.sort((a, b) => a.label.localeCompare(b.label)); 64 | 65 | return result; 66 | } 67 | 68 | private populateFoldersList( 69 | list: FolderListItem[], 70 | parent: TreeElement, 71 | current: FolderListItem 72 | ): void { 73 | list.push(current); 74 | 75 | for (const childId of parent.childIds) { 76 | const child = this.getElement(childId); 77 | 78 | if (SnippetsStorage.isFolder(child)) { 79 | const joinedName = `${ 80 | current.label === "/" ? "/" : `${current.label}/` 81 | }${child.data.label}`; 82 | 83 | this.populateFoldersList(list, child, { 84 | id: childId, 85 | label: joinedName, 86 | }); 87 | } 88 | } 89 | } 90 | 91 | getElement(id?: string): TreeElement | undefined { 92 | const providedOrRootId = id ?? this.rootId; 93 | 94 | const result = this.elements.get(providedOrRootId); 95 | 96 | return result || undefined; 97 | } 98 | 99 | async deleteElement(id: string): Promise { 100 | const toDelete = this.getElement(id); 101 | const messageForUser = SnippetsStorage.isFolder(toDelete) 102 | ? "Are you sure you want to delete this folder? Everything inside it will be deleted too." 103 | : "Are you sure you want to delete this snippet?"; 104 | 105 | const answer = await vscode.window.showInformationMessage( 106 | messageForUser, 107 | { modal: true }, 108 | "Yes", 109 | "No" 110 | ); 111 | 112 | if (answer !== "Yes") { 113 | return; 114 | } 115 | 116 | this.elements.delete(id); 117 | const parent = this.getElement(toDelete.parentId); 118 | parent.childIds?.splice( 119 | parent.childIds.findIndex((x) => x === id), 120 | 1 121 | ); 122 | 123 | await this.save(StorageOperation.Delete); 124 | } 125 | 126 | async renameElement(id: string, newName: string): Promise { 127 | this.getElement(id).data.label = newName; 128 | await this.save(StorageOperation.Rename); 129 | } 130 | 131 | async createFolder(name: string, relativeToId?: string): Promise { 132 | const relativeToElement = this.getElement(relativeToId); 133 | 134 | const parentId = SnippetsStorage.isFolder(relativeToElement) 135 | ? relativeToElement.data.id 136 | : relativeToElement.parentId; 137 | 138 | const folder: TreeElementData = { 139 | id: randomUUID(), 140 | label: name, 141 | content: "", 142 | }; 143 | 144 | this.elements.set(folder.id, { childIds: [], data: folder, parentId }); 145 | this.getElement(parentId).childIds?.push(folder.id); 146 | 147 | await this.save(StorageOperation.CreateFolder); 148 | } 149 | 150 | async moveElement(sourceId: string, targetId?: string): Promise { 151 | if (targetId === sourceId) { 152 | return; 153 | } 154 | 155 | const sourceElement = this.getElement(sourceId); 156 | const targetElement = this.getElement(targetId); 157 | 158 | const newParentId = SnippetsStorage.isFolder(targetElement) 159 | ? targetElement.data.id 160 | : targetElement.parentId; 161 | 162 | let tempId = newParentId; 163 | while (tempId) { 164 | const curElement = this.getElement(tempId); 165 | if ( 166 | curElement?.data.id === sourceId || 167 | curElement?.parentId === sourceId 168 | ) { 169 | return; 170 | } 171 | tempId = curElement?.parentId; 172 | } 173 | 174 | const previousParent = this.getElement(sourceElement.parentId); 175 | previousParent.childIds?.splice( 176 | previousParent.childIds.findIndex((id) => id === sourceId), 177 | 1 178 | ); 179 | 180 | sourceElement.parentId = newParentId; 181 | const newParentElement = this.getElement(newParentId); 182 | newParentElement.childIds?.push(sourceId); 183 | 184 | await this.save(StorageOperation.Move); 185 | } 186 | 187 | async saveSnippet( 188 | content: string, 189 | fileExtension: string, 190 | label: string, 191 | parentId: string 192 | ): Promise { 193 | const data: TreeElementData = { 194 | id: randomUUID(), 195 | label, 196 | content, 197 | fileExtension, 198 | }; 199 | 200 | const element: TreeElement = { data, parentId }; 201 | this.elements.set(data.id, element); 202 | this.getElement(parentId).childIds?.push(data.id); 203 | 204 | await this.save(StorageOperation.Save); 205 | this.onSnippetSave?.(element); 206 | } 207 | 208 | getSnippet(id: string): string { 209 | return this.getElement(id).data.content?.toString() || ""; 210 | } 211 | 212 | async save(operation?: StorageOperation): Promise { 213 | const originalElements = JSON.parse( 214 | this.context.globalState.get(this.storageKey) || "[]" 215 | ) as TreeElement[]; 216 | this.onBeforeSave?.(originalElements, operation); 217 | await this.context.globalState.update(this.storageKey, this.serialize()); 218 | this.onSave?.(); 219 | } 220 | 221 | *getSnippets(): IterableIterator { 222 | for (const element of this.elements.values()) { 223 | if (!SnippetsStorage.isFolder(element)) { 224 | yield element; 225 | } 226 | } 227 | } 228 | 229 | getSnippetCount(elements: TreeElement[]) { 230 | return elements.filter((x) => !SnippetsStorage.isFolder(x)).length; 231 | } 232 | 233 | async replaceElements(newElements: TreeElement[]): Promise { 234 | this.deserialize(JSON.stringify(newElements)); 235 | await this.context.globalState.update(this.storageKey, this.serialize()); 236 | this.onSave?.(); 237 | } 238 | 239 | private load(): void { 240 | this.deserialize(this.context.globalState.get(this.storageKey) || "[]"); 241 | } 242 | 243 | private async loadDefaultElements(): Promise { 244 | const root: TreeElementData = { 245 | id: randomUUID(), 246 | label: "root", 247 | content: "", 248 | }; 249 | const exampleFolder: TreeElementData = { 250 | id: randomUUID(), 251 | label: "example folder", 252 | content: "", 253 | }; 254 | const exampleSnippet: TreeElementData = { 255 | id: randomUUID(), 256 | label: "example snippet", 257 | fileExtension: ".js", 258 | content: `for (let i = 0; i < 5; i++) { 259 | console.log('Hello world!'); 260 | } 261 | `, 262 | }; 263 | 264 | this.rootId = root.id; 265 | 266 | this.elements.set(root.id, { 267 | data: root, 268 | childIds: [exampleFolder.id], 269 | }); 270 | this.elements.set(exampleFolder.id, { 271 | data: exampleFolder, 272 | childIds: [exampleSnippet.id], 273 | parentId: root.id, 274 | }); 275 | this.elements.set(exampleSnippet.id, { 276 | data: exampleSnippet, 277 | parentId: exampleFolder.id, 278 | }); 279 | 280 | await this.save(StorageOperation.LoadDefault); 281 | } 282 | 283 | private serialize(): string { 284 | return JSON.stringify([...this.elements.values()]); 285 | } 286 | 287 | private deserialize(json: string): void { 288 | this.elements.clear(); 289 | const tree = JSON.parse(json) as TreeElement[]; 290 | 291 | tree.forEach((element) => { 292 | this.elements.set(element.data.id, element); 293 | 294 | if (!element.parentId) { 295 | this.rootId = element.data.id; 296 | } 297 | }); 298 | } 299 | 300 | static isFolder(element: TreeElement): boolean { 301 | return element.childIds != null; 302 | } 303 | } 304 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "snippet", 3 | "displayName": "Snippet", 4 | "description": "Insert a snippet from cht.sh for Python, JavaScript, Ruby, C#, Go, Rust (and any other language)", 5 | "version": "1.2.0", 6 | "publisher": "vscode-snippet", 7 | "engines": { 8 | "vscode": "^1.74.0" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/mre/vscode-snippet.git" 13 | }, 14 | "license": "MIT", 15 | "icon": "contrib/icon.png", 16 | "galleryBanner": { 17 | "color": "#6cfff9", 18 | "theme": "light" 19 | }, 20 | "categories": [ 21 | "Programming Languages", 22 | "Snippets", 23 | "Other" 24 | ], 25 | "tags": [ 26 | "python", 27 | "ruby", 28 | "php", 29 | "rust", 30 | "C#", 31 | "go", 32 | "haskell", 33 | "typescript", 34 | "shell", 35 | "javascript", 36 | "node", 37 | "snippet", 38 | "examples", 39 | "documentation", 40 | "help", 41 | "tldr", 42 | "helper", 43 | "cheatsheet" 44 | ], 45 | "main": "./out/extension", 46 | "contributes": { 47 | "commands": [ 48 | { 49 | "title": "Find", 50 | "command": "snippet.find", 51 | "category": "Snippet" 52 | }, 53 | { 54 | "title": "Find for language", 55 | "command": "snippet.findForLanguage", 56 | "category": "Snippet" 57 | }, 58 | { 59 | "title": "Find Inplace", 60 | "command": "snippet.findInplace", 61 | "category": "Snippet" 62 | }, 63 | { 64 | "title": "Find in new editor window", 65 | "command": "snippet.findInNewEditor", 66 | "category": "Snippet" 67 | }, 68 | { 69 | "title": "Find snippet from selected text", 70 | "command": "snippet.findSelectedText", 71 | "category": "Snippet" 72 | }, 73 | { 74 | "title": "Show previous answer", 75 | "command": "snippet.showPreviousAnswer", 76 | "category": "Snippet" 77 | }, 78 | { 79 | "title": "Show next answer", 80 | "command": "snippet.showNextAnswer", 81 | "category": "Snippet" 82 | }, 83 | { 84 | "title": "Toggle comments", 85 | "command": "snippet.toggleComments", 86 | "category": "Snippet" 87 | }, 88 | { 89 | "title": "Save snippet", 90 | "command": "snippet.saveSnippet", 91 | "category": "Snippet" 92 | }, 93 | { 94 | "title": "Insert snippet", 95 | "command": "snippet.insertSnippet", 96 | "category": "Snippet" 97 | }, 98 | { 99 | "title": "Delete", 100 | "command": "snippet.deleteSnippet", 101 | "category": "Snippet" 102 | }, 103 | { 104 | "title": "Rename", 105 | "command": "snippet.renameSnippet", 106 | "category": "Snippet" 107 | }, 108 | { 109 | "title": "Copy", 110 | "command": "snippet.copySnippet", 111 | "category": "Snippet" 112 | }, 113 | { 114 | "title": "Find and copy", 115 | "command": "snippet.findAndCopy", 116 | "category": "Snippet" 117 | }, 118 | { 119 | "title": "New Folder", 120 | "command": "snippet.createFolder", 121 | "category": "Snippet", 122 | "icon": { 123 | "light": "assets/icons/add-light.svg", 124 | "dark": "assets/icons/add-dark.svg" 125 | } 126 | }, 127 | { 128 | "title": "Restore backups", 129 | "command": "snippet.restoreBackups", 130 | "category": "Snippet", 131 | "icon": { 132 | "light": "assets/icons/history-light.svg", 133 | "dark": "assets/icons/history-dark.svg" 134 | } 135 | } 136 | ], 137 | "configuration": { 138 | "title": "Snippet", 139 | "properties": { 140 | "snippet.baseUrl": { 141 | "type": "string", 142 | "default": "https://cht.sh", 143 | "description": "Base URL of the cheat sheet server" 144 | }, 145 | "snippet.openInNewEditor": { 146 | "type": "boolean", 147 | "default": true, 148 | "description": "Open snippet result in new editor." 149 | }, 150 | "snippet.verbose": { 151 | "type": "boolean", 152 | "default": false, 153 | "description": "Also show explanations for code snippets." 154 | }, 155 | "snippet.defaultLanguage": { 156 | "type": "string", 157 | "default": null, 158 | "description": "Programming language name in lower case to use as default language when there is no open editor window." 159 | }, 160 | "snippet.title": { 161 | "type": "string", 162 | "default": "[${language}] ${query} (${index})", 163 | "markdownDescription": "Template string of a snippet title. \nYou can use the following variables:\n- ${language} - the programming language\n- ${query} - the snippet query (search text)\n- ${index} - the index of the snippet (e.g. 2 for the third answer)" 164 | }, 165 | "snippet.insertWithDoubleClick": { 166 | "type": "boolean", 167 | "default": false, 168 | "description": "Insert snippet with double click." 169 | }, 170 | "snippet.showCopySuccessNotification": { 171 | "type": "boolean", 172 | "default": true, 173 | "description": "Whether to show a notification after the snippet is copied to the clipboard." 174 | }, 175 | "snippet.saveBackups": { 176 | "type": "boolean", 177 | "default": true, 178 | "description": "Whether to create backups of the snippets." 179 | } 180 | } 181 | }, 182 | "menus": { 183 | "view/title": [ 184 | { 185 | "command": "snippet.createFolder", 186 | "when": "view == snippetsView", 187 | "group": "navigation" 188 | }, 189 | { 190 | "command": "snippet.restoreBackups", 191 | "when": "view == snippetsView", 192 | "group": "navigation" 193 | } 194 | ], 195 | "view/item/context": [ 196 | { 197 | "command": "snippet.createFolder", 198 | "when": "view == snippetsView", 199 | "group": "snippet.viewItemContext.baseGroup@1" 200 | }, 201 | { 202 | "command": "snippet.copySnippet", 203 | "when": "view == snippetsView && viewItem == snippet", 204 | "group": "snippet.viewItemContext.baseGroup@2" 205 | }, 206 | { 207 | "command": "snippet.renameSnippet", 208 | "when": "view == snippetsView", 209 | "group": "snippet.viewItemContext.baseGroup@3" 210 | }, 211 | { 212 | "command": "snippet.deleteSnippet", 213 | "when": "view == snippetsView", 214 | "group": "snippet.viewItemContext.baseGroup@4" 215 | } 216 | ], 217 | "editor/context": [ 218 | { 219 | "when": "editorHasSelection", 220 | "command": "snippet.findSelectedText", 221 | "group": "1_modification" 222 | }, 223 | { 224 | "when": "editorHasSelection", 225 | "command": "snippet.saveSnippet", 226 | "group": "1_modification" 227 | } 228 | ] 229 | }, 230 | "views": { 231 | "explorer": [ 232 | { 233 | "id": "snippetsView", 234 | "name": "Snippets" 235 | } 236 | ] 237 | }, 238 | "keybindings": [ 239 | { 240 | "command": "snippet.findSelectedText", 241 | "key": "ctrl+shift+s", 242 | "mac": "cmd+shift+s", 243 | "when": "editorHasSelection" 244 | }, 245 | { 246 | "key": "c", 247 | "command": "snippet.showNextAnswer", 248 | "when": "resourceScheme == 'snippet' && editorReadonly" 249 | }, 250 | { 251 | "key": "v", 252 | "command": "snippet.showPreviousAnswer", 253 | "when": "resourceScheme == 'snippet' && editorReadonly" 254 | } 255 | ] 256 | }, 257 | "activationEvents": [ 258 | "onCommand:snippet.find", 259 | "onCommand:snippet.findForLanguage", 260 | "onCommand:snippet.findSelectedText", 261 | "onCommand:snippet.findInplace", 262 | "onCommand:snippet.findInNewEditor", 263 | "onCommand:snippet.showPreviousAnswer", 264 | "onCommand:snippet.showNextAnswer", 265 | "onCommand:snippet.toggleComments" 266 | ], 267 | "scripts": { 268 | "vscode:prepublish": "NODE_ENV=production npm run compile", 269 | "compile": "rollup -c", 270 | "precompile": "rimraf out", 271 | "watch": "rollup -c --watch", 272 | "prewatch": "rimraf out", 273 | "lint": "eslint src", 274 | "test": "npm run test-compile && export NODE_ENV=test && node ./out/test/runTest.js", 275 | "test-compile": "tsc -p ./ --allowSyntheticDefaultImports", 276 | "pretest-compile": "rimraf out" 277 | }, 278 | "dependencies": { 279 | "@vscode/vsce": "^2.31.1", 280 | "axios": "^1.7.3", 281 | "event-stream": "4.0.1", 282 | "http-proxy-agent": "^7.0.2" 283 | }, 284 | "devDependencies": { 285 | "@rollup/plugin-commonjs": "^26.0.1", 286 | "@rollup/plugin-json": "^6.1.0", 287 | "@rollup/plugin-node-resolve": "^15.2.3", 288 | "@rollup/plugin-terser": "^0.4.4", 289 | "@rollup/plugin-typescript": "^11.1.6", 290 | "@types/glob": "^8.1.0", 291 | "@types/mocha": "^10.0.7", 292 | "@types/node": "^14.17.0", 293 | "@types/sinon": "^17.0.3", 294 | "@types/vscode": "^1.74.0", 295 | "@typescript-eslint/eslint-plugin": "^7.17.0", 296 | "@typescript-eslint/parser": "^7.18.0", 297 | "@vscode/test-electron": "^2.4.1", 298 | "eslint": "^8.57.0", 299 | "glob": "^11.0.0", 300 | "mocha": "^10.7.0", 301 | "rimraf": "^6.0.1", 302 | "rollup-plugin-node-externals": "^7.1.2", 303 | "sinon": "^18.0.0", 304 | "rollup": "^4.20.0", 305 | "typescript": "^5.4.5" 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /src/endpoints.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | import { BackupManager } from "./backupManager"; 3 | import * as clipboard from "./clipboard"; 4 | import { getConfig, getLanguage, pickLanguage } from "./config"; 5 | import { formatUnixTime } from "./date"; 6 | import languages from "./languages"; 7 | import { encodeRequest } from "./provider"; 8 | import { query } from "./query"; 9 | import snippet from "./snippet"; 10 | import SnippetsStorage from "./snippetsStorage"; 11 | import { SnippetsTreeItem, SnippetsTreeProvider } from "./snippetsTreeProvider"; 12 | 13 | export interface Request { 14 | language: string; 15 | query: string; 16 | savedSnippetContent?: string; 17 | } 18 | 19 | const loadingStatus = vscode.window.createStatusBarItem( 20 | vscode.StatusBarAlignment.Left 21 | ); 22 | loadingStatus.text = "$(clock) Loading Snippet ..."; 23 | 24 | export async function findWithProvider( 25 | language: string, 26 | userQuery: string, 27 | verbose: boolean, 28 | number: number, 29 | openInNewEditor = true, 30 | savedSnippetContent?: string 31 | ) { 32 | let doc: vscode.TextDocument | null = null; 33 | 34 | if (!savedSnippetContent) { 35 | loadingStatus.show(); 36 | try { 37 | const uri = encodeRequest(userQuery, language, verbose, number); 38 | 39 | // Calls back into the provider 40 | doc = await vscode.workspace.openTextDocument(uri); 41 | } finally { 42 | loadingStatus.hide(); 43 | } 44 | 45 | try { 46 | doc = await vscode.languages.setTextDocumentLanguage(doc, language); 47 | } catch (e) { 48 | console.log(`Cannot set document language to ${language}: ${e}`); 49 | } 50 | } 51 | 52 | const editor = vscode.window.activeTextEditor; 53 | 54 | // Open in new editor in case there is no saved snippet content and the respective config flag is set to true 55 | // or there is no open user-created editor where we could paste the snippet in. 56 | if ( 57 | !savedSnippetContent && 58 | (openInNewEditor || !editor || editor.document.uri.scheme == "snippet") 59 | ) { 60 | await vscode.window.showTextDocument(doc, { 61 | viewColumn: vscode.ViewColumn.Two, 62 | preview: true, 63 | preserveFocus: false, 64 | }); 65 | } else { 66 | const text = savedSnippetContent ? savedSnippetContent : doc.getText(); 67 | const success = await editor.edit((builder) => { 68 | builder.insert(editor.selection.start, text); 69 | }); 70 | if (!success) { 71 | vscode.window.showInformationMessage("Error while opening snippet."); 72 | } 73 | } 74 | } 75 | 76 | export async function getInput( 77 | snippetsStorage: SnippetsStorage 78 | ): Promise { 79 | const language = await getLanguage(); 80 | const userQuery = await query(language, snippetsStorage); 81 | return { 82 | language, 83 | query: userQuery.input, 84 | savedSnippetContent: userQuery.savedSnippetContent, 85 | }; 86 | } 87 | 88 | export async function findForLanguage(snippetsStorage: SnippetsStorage) { 89 | const language = await pickLanguage(); 90 | const userQuery = await query(language, snippetsStorage); 91 | await findWithProvider( 92 | language, 93 | userQuery.input, 94 | snippet.getVerbose(), 95 | 0, 96 | getConfig("openInNewEditor"), 97 | userQuery.savedSnippetContent 98 | ); 99 | } 100 | 101 | export async function findDefault(snippetsStorage: SnippetsStorage) { 102 | const request = await getInput(snippetsStorage); 103 | await findWithProvider( 104 | request.language, 105 | request.query, 106 | snippet.getVerbose(), 107 | 0, 108 | getConfig("openInNewEditor"), 109 | request.savedSnippetContent 110 | ); 111 | } 112 | 113 | export async function findInplace(snippetsStorage: SnippetsStorage) { 114 | const request = await getInput(snippetsStorage); 115 | await findWithProvider( 116 | request.language, 117 | request.query, 118 | snippet.getVerbose(), 119 | 0, 120 | false, 121 | request.savedSnippetContent 122 | ); 123 | } 124 | 125 | export async function findInNewEditor(snippetsStorage: SnippetsStorage) { 126 | const request = await getInput(snippetsStorage); 127 | await findWithProvider( 128 | request.language, 129 | request.query, 130 | snippet.getVerbose(), 131 | 0, 132 | true, 133 | request.savedSnippetContent 134 | ); 135 | } 136 | 137 | export async function showNextAnswer(snippetsStorage: SnippetsStorage) { 138 | if (!snippet.getCurrentQuery()) { 139 | return await findDefault(snippetsStorage); 140 | } 141 | const answerNumber = snippet.getNextAnswerNumber(); 142 | await findWithProvider( 143 | await getLanguage(), 144 | snippet.getCurrentQuery(), 145 | snippet.getVerbose(), 146 | answerNumber, 147 | getConfig("openInNewEditor") 148 | ); 149 | } 150 | 151 | export async function showPreviousAnswer(snippetsStorage: SnippetsStorage) { 152 | if (!snippet.getCurrentQuery()) { 153 | return await findDefault(snippetsStorage); 154 | } 155 | const answerNumber = snippet.getPreviousAnswerNumber(); 156 | if (answerNumber == null) { 157 | vscode.window.showInformationMessage("already at first snippet"); 158 | return; 159 | } 160 | await findWithProvider( 161 | await getLanguage(), 162 | snippet.getCurrentQuery(), 163 | snippet.getVerbose(), 164 | answerNumber, 165 | getConfig("openInNewEditor") 166 | ); 167 | } 168 | 169 | export async function toggleComments() { 170 | snippet.toggleVerbose(); 171 | await findWithProvider( 172 | await getLanguage(), 173 | snippet.getCurrentQuery(), 174 | snippet.getVerbose(), 175 | snippet.getCurrentAnswerNumber(), 176 | getConfig("openInNewEditor") 177 | ); 178 | } 179 | 180 | export async function findSelectedText() { 181 | const editor = vscode.window.activeTextEditor; 182 | if (!editor) { 183 | vscode.window.showErrorMessage("There is no open editor window"); 184 | return; 185 | } 186 | const selection = editor.selection; 187 | const query = editor.document.getText(selection); 188 | const language = await getLanguage(); 189 | await findWithProvider( 190 | language, 191 | query, 192 | snippet.getVerbose(), 193 | 0, 194 | getConfig("openInNewEditor") 195 | ); 196 | } 197 | 198 | export function saveSnippet(treeProvider: SnippetsTreeProvider) { 199 | return () => { 200 | const showNoTextMsg = () => 201 | vscode.window.showInformationMessage( 202 | "Select a piece of code in the editor to save it." 203 | ); 204 | 205 | const editor = vscode.window.activeTextEditor; 206 | if (!editor) { 207 | showNoTextMsg(); 208 | return; 209 | } 210 | 211 | editor.edit(async () => { 212 | const content = editor.document.getText(editor.selection); 213 | 214 | if (content.length < 1) { 215 | showNoTextMsg(); 216 | return; 217 | } 218 | 219 | const foldersList = treeProvider.storage.getFoldersList(); 220 | const folder = await vscode.window.showQuickPick(foldersList, { 221 | placeHolder: "Folder name", 222 | title: "Select a folder", 223 | }); 224 | 225 | if (!folder) { 226 | return; 227 | } 228 | 229 | const defaultLabel = content.substring(0, 100); 230 | const fileName = editor.document.fileName; 231 | const indexOfLastDot = fileName.lastIndexOf("."); 232 | const extensionByLangId = 233 | languages.getExtensions(editor.document.languageId)[0] || ""; 234 | const fileExtension = 235 | indexOfLastDot === -1 236 | ? extensionByLangId 237 | : fileName.slice(indexOfLastDot); 238 | 239 | const nameInputOptions: vscode.InputBoxOptions = { 240 | ignoreFocusOut: false, 241 | placeHolder: "Snippet Name", 242 | prompt: "Give the snippet a name...", 243 | value: defaultLabel, 244 | }; 245 | 246 | vscode.window.showInputBox(nameInputOptions).then(async (label) => { 247 | if (!label) { 248 | return; 249 | } 250 | 251 | await treeProvider.storage.saveSnippet( 252 | content, 253 | fileExtension, 254 | label, 255 | folder.id 256 | ); 257 | 258 | await vscode.commands.executeCommand("snippetsView.focus"); 259 | }); 260 | }); 261 | }; 262 | } 263 | 264 | export function insertSnippet(treeProvider: SnippetsTreeProvider) { 265 | const clickedOnce = new Set(); 266 | 267 | return (id: string) => { 268 | const isInsertWithDoubleClick = getConfig("insertWithDoubleClick"); 269 | 270 | if (isInsertWithDoubleClick && !clickedOnce.has(id)) { 271 | clickedOnce.add(id); 272 | setTimeout(() => { 273 | clickedOnce.delete(id); 274 | }, 250); 275 | return; 276 | } 277 | 278 | if (!id) { 279 | vscode.window.showInformationMessage( 280 | "Insert a snippet into the editor by clicking on it in the Snippets view." 281 | ); 282 | return; 283 | } 284 | 285 | const editor = vscode.window.activeTextEditor; 286 | if (!editor) { 287 | vscode.window.showInformationMessage( 288 | "Open a file in the editor to insert a snippet." 289 | ); 290 | return; 291 | } 292 | 293 | const content = treeProvider.storage.getSnippet(id); 294 | 295 | if (content) { 296 | editor.edit((builder) => { 297 | builder.insert(editor.selection.start, content); 298 | }); 299 | } 300 | }; 301 | } 302 | 303 | export function deleteSnippet(treeProvider: SnippetsTreeProvider) { 304 | return async (item: SnippetsTreeItem) => { 305 | if (!item) { 306 | vscode.window.showInformationMessage( 307 | 'Delete a snippet or a folder by right clicking on it in the list and selecting "Delete"' 308 | ); 309 | return; 310 | } 311 | 312 | await treeProvider.storage.deleteElement(item.id!); 313 | }; 314 | } 315 | 316 | export function renameSnippet(treeProvider: SnippetsTreeProvider) { 317 | return async (item: SnippetsTreeItem) => { 318 | if (!item) { 319 | vscode.window.showInformationMessage( 320 | 'Rename a snippet or a folder by right clicking on it in the list and selecting "Rename"' 321 | ); 322 | return; 323 | } 324 | 325 | const opt: vscode.InputBoxOptions = { 326 | ignoreFocusOut: false, 327 | placeHolder: "New Name", 328 | prompt: "Rename...", 329 | value: item.label, 330 | }; 331 | 332 | const newName = await vscode.window.showInputBox(opt); 333 | 334 | if (!newName) { 335 | return; 336 | } 337 | 338 | await treeProvider.storage.renameElement(item.id, newName); 339 | }; 340 | } 341 | 342 | export function copySnippet(treeProvider: SnippetsTreeProvider) { 343 | return async (item: SnippetsTreeItem) => { 344 | if (!item) { 345 | vscode.window.showInformationMessage( 346 | 'Copy a snippet right clicking on it in the list and selecting "Copy"' 347 | ); 348 | return; 349 | } 350 | 351 | const content = treeProvider.storage.getSnippet(item.id); 352 | await clipboard.copySnippet(content); 353 | }; 354 | } 355 | 356 | export function findAndCopy(snippetsStorage: SnippetsStorage) { 357 | return async () => { 358 | const language = await getLanguage(); 359 | const userQuery = await query(language, snippetsStorage, true); 360 | 361 | await clipboard.copySnippet(userQuery.savedSnippetContent); 362 | }; 363 | } 364 | 365 | export function createFolder(treeProvider: SnippetsTreeProvider) { 366 | return async (item?: SnippetsTreeItem) => { 367 | const opt: vscode.InputBoxOptions = { 368 | ignoreFocusOut: false, 369 | placeHolder: "Folder Name", 370 | prompt: "Specify Folder Name...", 371 | validateInput: (value: string) => { 372 | if (value.includes("/")) { 373 | return 'Folder name cannot contain "/"'; 374 | } 375 | return null; 376 | }, 377 | }; 378 | 379 | const folderName = await vscode.window.showInputBox(opt); 380 | 381 | if (!folderName) { 382 | return; 383 | } 384 | 385 | await treeProvider.storage.createFolder(folderName, item?.id); 386 | }; 387 | } 388 | 389 | export function showBackups(backupManager: BackupManager) { 390 | return async () => { 391 | const backups = backupManager.getBackupItems(); 392 | const selectedBackup = await vscode.window.showQuickPick(backups, { 393 | placeHolder: 394 | "Select a backup to restore. You will be able to undo this operation.", 395 | title: "Select a backup", 396 | }); 397 | 398 | if (!selectedBackup) { 399 | return; 400 | } 401 | 402 | await backupManager.restoreBackup(selectedBackup.item.id); 403 | await vscode.commands.executeCommand("snippetsView.focus"); 404 | const answer = await vscode.window.showInformationMessage( 405 | `Restored backup from ${formatUnixTime(selectedBackup.item.dateUnix)}`, 406 | "Ok", 407 | "Undo" 408 | ); 409 | 410 | if (answer === "Undo") { 411 | await backupManager.undoLastRestore(); 412 | } 413 | }; 414 | } 415 | -------------------------------------------------------------------------------- /contrib/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 20 | 22 | 25 | 29 | 30 | 33 | 37 | 38 | 41 | 45 | 46 | 49 | 53 | 54 | 57 | 61 | 62 | 65 | 69 | 70 | 73 | 77 | 78 | 85 | 88 | 91 | 93 | 95 | 98 | 106 | 107 | 108 | 109 | 110 | 111 | 118 | 124 | 125 | 128 | 132 | 133 | 136 | 140 | 141 | 144 | 148 | 149 | 152 | 156 | 157 | 160 | 164 | 165 | 168 | 172 | 173 | 176 | 180 | 181 | 184 | 188 | 189 | 196 | 199 | 202 | 204 | 206 | 209 | 217 | 218 | 219 | 220 | 221 | 222 | 229 | 235 | 236 | 239 | 243 | 244 | 247 | 251 | 252 | 255 | 259 | 260 | 263 | 267 | 268 | 271 | 275 | 276 | 279 | 283 | 284 | 287 | 291 | 292 | 299 | 302 | 305 | 307 | 309 | 312 | 320 | 321 | 322 | 323 | 324 | 325 | 332 | 338 | 339 | 342 | 346 | 347 | 350 | 354 | 355 | 358 | 362 | 363 | 366 | 370 | 371 | 374 | 378 | 379 | 382 | 386 | 387 | 394 | 397 | 400 | 402 | 404 | 407 | 415 | 416 | 417 | 418 | 419 | 420 | 427 | 433 | 434 | 437 | 441 | 442 | 445 | 449 | 450 | 453 | 457 | 458 | 461 | 465 | 466 | 469 | 473 | 474 | 477 | 481 | 482 | 485 | 489 | 490 | 497 | 500 | 503 | 505 | 507 | 510 | 518 | 519 | 520 | 521 | 522 | 523 | 530 | 536 | 537 | 540 | 544 | 545 | 548 | 552 | 553 | 556 | 560 | 561 | 564 | 568 | 569 | 572 | 576 | 577 | 580 | 584 | 585 | 588 | 592 | 593 | 600 | 603 | 606 | 608 | 610 | 613 | 621 | 622 | 623 | 624 | 625 | 626 | 633 | 639 | 640 | 643 | 647 | 648 | 651 | 655 | 656 | 659 | 663 | 664 | 667 | 671 | 672 | 675 | 679 | 680 | 683 | 687 | 688 | 689 | 707 | 709 | 710 | 712 | image/svg+xml 713 | 715 | 716 | 717 | 718 | 719 | 723 | 726 | 730 | 732 | 735 | 737 | 742 | 747 | 752 | 757 | 762 | 767 | 768 | 770 | 771 | 772 | 773 | --------------------------------------------------------------------------------