vscode中的未命名/超薄片段 [英] unnamed/slim snippets in vscode

查看:32
本文介绍了vscode中的未命名/超薄片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 vscode 编辑乳胶(使用乳胶工作室插件),并且我最近开始创建自己的片段并且非常喜欢这个功能.但是,我发现创建小"片段的语法有点重,这些片段只是缩写频繁的单词序列.特别是,我发现必须为每个片段命名一个名称"很麻烦.

是否有苗条"片段/别名的机制,例如将一个文件作为输入,其中每个片段都是一行——第一个单词是缩写,其余的是缩写?

解决方案

你有几个选择.一种是编写一个可以做到这一点的扩展——我将展示像一个可以工作的扩展一样工作的代码——它看起来很复杂,但使用起来非常简单.

其次,您可以使用


或者,下载扩展程序 macro-commander.它允许您在设置中的宏中使用 vscode 扩展命令.这个宏会进入你的 settings.json 文件:

宏":{slimSnippetsInsertion": [{javascript":["const editor = vscode.window.activeTextEditor;",const 文档 = editor.document;","const we = new vscode.WorkspaceEdit();","const cursorPosition = editor.selection.active;",//使用是否为实际选择,返回一个 Position"let keyWordRange = document.getWordRangeAtPosition(cursorPosition);",//返回开始/结束位置的范围或未定义"如果 (keyWordRange === 未定义) {","await window.showInformationMessage(`光标必须在要替换的单词中或紧随其后`);",返回","}","let wordAtCursor = document.getText(keyWordRange);",//这是要在 slimSnippets.txt 中找到的关键字"const thisWorkspace = vscode.workspace.workspaceFolders[0].uri.toString();",//file:///c:/Users/Mark/OneDrive/Test Bed"const snippetFileContent = await vscode.workspace.fs.readFile(vscode.Uri.parse(`${thisWorkspace}/.vscode/slimSnippets.txt`));",const 片段 = snippetFileContent.toString();",//忽略键之前的前导空格/制表符//使用命名的捕获组来替换文本"const regex = new RegExp(`\r?(?<=\n|^)[\t]*(?<key>${wordAtCursor})[\t]+?(?<replacementText>.*?)(?=\r?\n|$)`);","let found = snippets.match(regex);",//如果没有匹配则返回 null//匹配一个键,但只有空格作为替换文本,所以什么都不做并退出"if (found && found.groups.replacementText.trimStart().length === 0) {","await window.showInformationMessage(`替换文字只是空格,不能替换`);""返回","}","if (found) {",//找到至少一个匹配键"if (found.groups.replacementText) {",//找到非空格替换文本//将 `
` 和 `	` 替换为换行符和制表符的 unicode 值"让替换 = found.groups.replacementText.replace(/\\n/g, '\u000A').replace(/\\t/g, '\u0009');"""让片段 = 新 vscode.SnippetString(replace)","if (editor.selections.length === 1) editor.insertSnippet(snippet, keyWordRange);",//如果选择 0 或 1"//如果多选,使用第一个键和替换文本""else editor.insertSnippet(snippet);","}","else await window.showInformationMessage(`找到匹配键但在 slimSnippets.txt 中没有替换文本`);","}","else await window.showInformationMessage(`在 slimSnippets.txt 中找不到匹配的键`);",]}

您可以看到我在哪里读取位于工作区中 .vscode 文件夹中的 simpleSnippets.txt 文件 - 但您可以更改位置,只要您更改命令中的路径信息:vscode.workspace.fs.readFile 上面.

slimSnippets.txt 文件只是一个简单的文本文件,其中每行中的第一个单词是 key,其余部分是替换.

howdy1 $1 第一个 $2 带制表符的句子howdy1 这不会被使用,重复上面的键howdy2 带有变量 $TM_FILENAME 的第二句key3 videos 111111//键和替换文本之间需要一个空格//将被删除,其他保留键1 222222stte 一些要扩展的文本mt2e 更多文本以展开[替换文本可以有占位符、制表符和选项,就像常规片段一样][用换行符将多行片段加入一个字符串,如下所示][一些文本
更多文本] [	 可用于制表符]key5 第 1 行
	 第 2 行
		 第 3 行

键是单个单词,如果没有替换文本(或文件中键后只有空格),则不会发生任何事情 - 键不会被替换.

实际插入的文本可以是纯文本,也可以使用 vscode 的代码片段格式 - 参见上面的示例文本文件.

光标必须紧跟在单词之后或单词中,并且可以选择或不选择该单词.它必须是正则表达式意义上的单词 - 不是与单词之前或之后相邻的连续文本 - 只是一个独立的单词,它可以在行中的任何位置.

如果您有重复的键,将使用第一个键.键/替换行之间可以有空行空格.

您不会获得按键的智能感知.我可能会努力.

最后,你需要一个键绑定来触发这个宏(在 keybindings.json 中):

<代码>{"key": "ctrl+;",//你想要的任何键绑定命令":macros.slimSnippetsInsertion"},

I'm using vscode to edit latex (with the latex workshop plugin), and I recently started creating my own snippets and really like the feature. However, I find the syntax a bit heavy for creating "small" snippets that just abbreviate frequent sequences of words. In particular, I find it cumbersome to have to give a 'name' to each snippet.

Is there a mechanism for "slim" snippets/aliases, that would e.g. take as input a file where each snippet is one line -- the first word being the abbreviation and the rest what is abbreviated?

解决方案

You have a couple of options. One is to write an extension that could do this - I'll show code that works like an extension that'll work - it looks complicated but use is pretty simple.

Second, you can come close using the Hyper Snips extension where your snippet file (say latex.hsnips) could like like this:

snippet dategreeting "Gives you the current date!"
Hello from your hsnip on ``rv = new Date().toDateString()``!
endsnippet

snippet // "Fraction simple" A
frac{$1}{$2}$0
endsnippet

snippet stte A
some text to expand
endsnippet

The descriptions in "" are not necessary and I eliminated it in the last snippet. The A flag will immediately insert your replacement text, without it you would Tab to insert the replacement text. As the examples here show you can use javascript within a snippet if you want.

The gif doesn't show it well bit here is a demo of auto-expansion with Hyper Snips:


Alternatively, download the extension macro-commander. It allows you to use vscode extension commands in a macro within your settings. This macro would go into your settings.json file:

"macros": {

  "slimSnippetsInsertion" : [
    { 
      "javascript": [

        "const editor = vscode.window.activeTextEditor;",
        "const document = editor.document;",
        "const we = new vscode.WorkspaceEdit();",
      
        "const cursorPosition = editor.selection.active;",   // use whether an actual selection or not, returns a Position
        "let keyWordRange = document.getWordRangeAtPosition(cursorPosition);",  // returns a Range of start/end Positions or undefined
        "if (keyWordRange === undefined) {",
          "await window.showInformationMessage(`cursor must be in or immediately after word to be replaced`);",
          "return;",
        "}",

        "let wordAtCursor = document.getText(keyWordRange);",  // this is the key word to find in slimSnippets.txt

        "const thisWorkspace = vscode.workspace.workspaceFolders[0].uri.toString();",
                // file:///c:/Users/Mark/OneDrive/Test Bed

        "const snippetFileContent = await vscode.workspace.fs.readFile(vscode.Uri.parse(`${thisWorkspace}/.vscode/slimSnippets.txt`));",

        "const snippets = snippetFileContent.toString();",

                    // ignore leading spaces/tabs before keys
                    // using a named capturing group for the replacement text
        "const regex = new RegExp(`\r?(?<=\n|^)[\t ]*(?<key>${wordAtCursor})[\t ]+?(?<replacementText>.*?)(?=\r?\n|$)`);",

        "let found = snippets.match(regex);",  // returns null if no matches

        // matched a key but only spaces as replacement text, so do nothing and exit
        "if (found && found.groups.replacementText.trimStart().length === 0) {",
          "await window.showInformationMessage(`replacement text is only spaces, not replacing`);",
          "return;",
        "}",

        "if (found) {",                      // found at least a matching key
          "if (found.groups.replacementText) {",  // found non-space replacement text

            // replace `
` and `	` with unicode values for newline and tab
            "let replace = found.groups.replacementText.replace(/\\n/g, '\u000A').replace(/\\t/g, '\u0009');",
            "let snippet = new vscode.SnippetString(replace)",

            "if (editor.selections.length === 1) editor.insertSnippet(snippet, keyWordRange);",  // if zero or one selection"
                 // if multiple selections, uses first key and replacement text"
            "else editor.insertSnippet(snippet);",
          "}",
          "else await window.showInformationMessage(`matching key found but with no replacement text in slimSnippets.txt`);",
        "}",
        "else await window.showInformationMessage(`no matching key found in slimSnippets.txt`);",
    ]
}

You can see where I made it to read a simpleSnippets.txt file located in the .vscode folder in the workspace - but you can change the location as long as you alter the path info in the command: vscode.workspace.fs.readFile above.

The slimSnippets.txt file is just a simple text file where the first word in each line is the key and the rest of the line is the replacement.

howdy1 $1 first $2 sentence with tabstops
howdy1 this won't be used, duplicate key above

howdy2 second sentence with variable $TM_FILENAME

key3    videos 111111    // one space necessary between key and replacement text
                     //     it will be removed, others retained
key1 222222

stte some text to expand
mt2e more text to expand


  [replacement text can have placeholders, tabstops and choices just like regular snippets]

  [join multiple-lines snippets into one string with newlines as below]
  [some text
some more text] [	 can be used for tabs]

 key5 line 1
	line 2
		line 3

Keys are single words and if there is no replacement text (or there are only spaces in the file after a key) nothing will happen - the key will not be replaced.

The text actually inserted can be plain text or use vscode's snippet format - see the sample text file above.

The cursor must be immediately after the word or in the word and the word can be selected or not. It must be a word in the regex sense - not continuous text adjoining the word before or after it - just a standalone word, it can be anywhere on the line.

If you have duplicate keys, the first will be used. There can be empty line spaces between key/replacement lines or not.

You will not get intellisense for the keys. I may work on that.

Finally, you will need a keybinding to trigger this macro (in keybindings.json):

{
  "key": "ctrl+;",             // whatever keybinding you wish
  "command": "macros.slimSnippetsInsertion"
},

这篇关于vscode中的未命名/超薄片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆