制作一个可以使用可变数量参数的 vscode 片段 [英] Make a vscode snippet that can use a variable number of arguments

查看:51
本文介绍了制作一个可以使用可变数量参数的 vscode 片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 VSCode 的新手.考虑到代码片段,我四处寻找一种在代码片段中编写脚本的方法.我的意思是做的不仅仅是填充或转换变量.例如...

I am new to VSCode. Thinking about code snippets, I looked around for a way to kind of script inside the snippet. I mean to do more than just fill or transform a variable. For example...

这是一个简单的片段.我将为类初始值设定项键入 rci.当我输入方法参数时,我希望赋值和文档+其他一些事情发生.

This is a simple snippet. I am going to type rci for the class initializer. When I enter the method arguments I would like the assignment and documentation + some other things to happen.

rci 然后 def initialize(a, b)) 导致这样的结果...

rci<tab> and then def initialize(a, b)) to result in something like this...

attr_reader :a
attr_reader :b

# @param a [...] ...
# @param b [...] ...
def initialize(a, b)
  @a = a
  @b = b
end

有可能吗?如何实现?可以有任意数量的参数.每个参数都会触发类初始值设定项的另一行.

Is it possible? How can it be achieved? There could be any number of arguments. And each argument would trigger another line of the class initializer.

推荐答案

"Class Initializer": {
  "prefix": "rci",
  "body": [

    "${1/([^,]+)([,\s]*|)/attr_reader :$1
/g}",    
    "${1/([^,]+)([,\s]*|)/# @param $1 [...]${2:+
}/g}",    
    "def initialize($1)",        
    "${1/([^,]+)((,\s*)|)/	@$1 = $1${2:+
}/g}",
    "end"
  ],

  "description": "Initialize Class"
}

使其适用于任意数量的方法参数的关键是将它们放入相同的正则表达式捕获组.

The key to get it to work for any number of method arguments is to get them into the same regex capture group.

然后,设置全局标志后,每个捕获组将触发替换文本.例如,如果您有 3 个方法参数,/attr_reader :$1 /g 将被触发 3 次.

Then, with the global flag set, each capture group will trigger the replacement text. So for instance, /attr_reader :$1 /g will get triggered 3 times if you have 3 method arguments.

您将在上面的转换中看到这个 ${2:+ }.这意味着如果有捕获组 2,请添加换行符.正则表达式的设计使得如果参数之间有另一个 , ,则只有一个捕获组 2.因此,最后一个参数之后的最终 ) 不会触发另一个换行符 - 因此输出与换行符的所需输出完全匹配(但您可以轻松添加或删除换行符).

You will see this ${2:+ } in the transforms above. That means if there is a capture group 2, add a newline. The regex is designed so that there is only a capture group 2 if there is another , between arguments. So a final ) after the last argument will not trigger another newline - so the output exactly matches your desired output as to newlines (but you could easily add or remove newlines).

您的输入必须采用正确的形式:

Your input must be in the correct form:

v1、v2、v3

这是一个演示:

所以必要的形式只是v1 v2 v3.参数之间不需要有空格,但是你会得到 def initialize(v1,v2,v3) 没有空格.

在最后一个参数后点击 Tab 以触发完成.

Hit Tab after the final argument to trigger completion.

事实证明代码片段非常强大!!

有关使用多个参数的类似问题,请参见 VSCode 片段:向类构造函数添加多个对象

For a similar question about using multiple arguments, see VSCode snippet: add multiple objects to a class constructor

这篇关于制作一个可以使用可变数量参数的 vscode 片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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