简体   繁体   English

vscode扩展:如何创建特定于语言的命令

[英]vscode extension: how to create a language specific command

I wrote a simple extension for vscode, which registers a command, namely comandName . 我为vscode写了一个简单的扩展,它注册了一个命令comandName

In my package.json file I have: 在我的package.json文件中,我有:

"activationEvents": [
    "onLanguage:python",
    "onCommand:commandName"
]

I meant to execute this command only for Python. 我的意思是只对Python执行此命令。 To my knowledge, however, the activationEvents in my package.json means that the command would be activated when a Python file is opened or the command is executed. 据我所知,我的package.jsonactivationEvents表示,当打开Python文件或执行命令时,该命令将被激活。 But the command can be executed within any language. 但是该命令可以用任何语言执行。 I searched the documentation but found no way to execute the command for certain languages. 我搜索了文档,但发现无法对某些语言执行命令。

Is there any way to achieve this target? 有什么办法可以实现这个目标?

I'm afraid this is impossible for now. 恐怕这是不可能的。 However you can work around this to avoid any side effects on other files. 但是,您可以解决此问题,以避免对其他文件产生任何副作用。

If you bind this command to some key combination or to context menu you can use when clause to limit the command to specific types of files. 如果将此命令绑定到某些组合键或上下文菜单,则可以使用when子句将命令限制为特定类型的文件。

It will still allow to execute the command from command palette though. 尽管它仍然允许从命令面板执行命令。 To work around this you can just ignore it when being in file other than Python: 要解决此问题,您可以在将文件放入Python以外的文件时将其忽略:

vsc.commands.registerTextEditorCommand('testCommand', editor => {
    if (editor.document.languageId !== 'python') {
        return
    }
    // command logic
}))

Notice I used registerTextEditorCommand instead of regular command. 注意,我使用了registerTextEditorCommand而不是常规命令。 The difference is that this one requires user to be in text editor context to work which is what you probabl 所不同的是,这要求用户在文本编辑器上下文中才能工作,这是您可能遇到的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM