How to access user settings for a snippets extension in VSCode

只谈情不闲聊 提交于 2019-12-24 02:45:34

问题


I am trying to give the option to customise a VS Code Extension with user defined settings (configuration) of their preferred quote style. I have configured it in my package.json:

"contributes": {
  "configuration": {
    "type": "object",
    "title": "Jasmine code snippets configuration",
    "properties": {
      "jasmineSnippets.quoteStyle": {
        "type": "string",
        "enum": [
          "'",
          "\"",
          "`"
        ],
        "default": "'",
        "description": "Code snippets quote style"
      }
    }
  }
},

And can access it in my settings.json like this:

"jasmineSnippets.quoteStyle": "`"

How can I now use that value in my snippets.json file? For this snippet, for example, I want to change the hardcoded ` to the configured property.

"it": {
  "prefix": "it",
  "body": "it(`${1:should behave...}`, () => {\n\t$2\n});",
  "description": "creates a test method",
  "scope": "source.js"
},

All I could find from the docs is not helpful as it assumes you're reading it from a JavaScript file not a JSON file:

You can read these values from your extension using vscode.workspace.getConfiguration('myExtension').


回答1:


I think this requires implementing a CompletionItemProvider and returning the snippet from that, rather than statically declaring it in a JSON. Here's an example of what that might look like:

'use strict';
import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    vscode.languages.registerCompletionItemProvider('javascript', {
        provideCompletionItems(doc, pos, token, context) {
            var quote = vscode.workspace.getConfiguration('jasmineSnippets').get("quoteStyle", "`");
            return [
                {
                    label: "it",
                    insertText: new vscode.SnippetString(
                        `it(${quote}\${1:should behave...}${quote}, () => {\n\t$2\n});`),
                    detail: "creates a test method",
                    kind: vscode.CompletionItemKind.Snippet,
                },
            ];
        }
    });
}

And then with "jasmineSnippets.quoteStyle": "\"" in the settings:



来源:https://stackoverflow.com/questions/55136207/how-to-access-user-settings-for-a-snippets-extension-in-vscode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!