斜杠命令
扩展可以为助手提供斜杠命令。
示例扩展
要查看提供斜杠命令的扩展的工作示例,请查看 slash-commands-example
扩展。
如果您想亲自试用,可以将此扩展 作为开发扩展安装。
定义斜杠命令
给定的扩展可以提供一个或多个斜杠命令。每个斜杠命令都必须在 extension.toml
中注册。
例如,这是一个提供两个斜杠命令的扩展:/echo
和 /pick-one
[slash_commands.echo]
description = "echoes the provided input"
requires_argument = true
[slash_commands.pick-one]
description = "pick one of three options"
requires_argument = true
每个斜杠命令可以定义以下属性
description
: 斜杠命令的描述,将在完成可用命令时显示。requires_argument
: 指示斜杠命令是否需要至少一个参数才能运行。
实现斜杠命令行为
要实现斜杠命令的行为,请为您的扩展实现 run_slash_command
。
此方法接受将要运行的斜杠命令、传递给它的参数列表和一个可选的 Worktree
。
此方法返回 SlashCommandOutput
,其中包含命令的文本输出(在 text
字段中)。输出还可以定义包含输出范围的 SlashCommandOutputSection
。然后,这些部分将呈现为助手上下文编辑器中的折叠。
您的扩展应该 match
命令名称(不带前导 /
),然后相应地执行行为
impl zed::Extension for MyExtension {
fn run_slash_command(
&self,
command: SlashCommand,
args: Vec<String>,
_worktree: Option<&Worktree>,
) -> Result<SlashCommandOutput, String> {
match command.name.as_str() {
"echo" => {
if args.is_empty() {
return Err("nothing to echo".to_string());
}
let text = args.join(" ");
Ok(SlashCommandOutput {
sections: vec![SlashCommandOutputSection {
range: (0..text.len()).into(),
label: "Echo".to_string(),
}],
text,
})
}
"pick-one" => {
let Some(selection) = args.first() else {
return Err("no option selected".to_string());
};
match selection.as_str() {
"option-1" | "option-2" | "option-3" => {}
invalid_option => {
return Err(format!("{invalid_option} is not a valid option"));
}
}
let text = format!("You chose {selection}.");
Ok(SlashCommandOutput {
sections: vec![SlashCommandOutputSection {
range: (0..text.len()).into(),
label: format!("Pick One: {selection}"),
}],
text,
})
}
command => Err(format!("unknown slash command: \"{command}\"")),
}
}
}
自动完成斜杠命令参数
对于具有参数的斜杠命令,您也可以选择实现 complete_slash_command_argument
以提供斜杠命令的补全。
此方法接受将要运行的斜杠命令和传递给它的参数列表。它返回将在补全菜单中显示的 SlashCommandArgumentCompletion
列表。
SlashCommandArgumentCompletion
包含以下属性
label
: 将在补全菜单中显示的标签。new_text
: 接受补全时将插入的文本。run_command
: 接受补全时是否运行斜杠命令。
同样,您的扩展应该 match
命令名称(不带前导 /
)并返回所需的参数补全
impl zed::Extension for MyExtension {
fn complete_slash_command_argument(
&self,
command: SlashCommand,
_args: Vec<String>,
) -> Result<Vec<SlashCommandArgumentCompletion>, String> {
match command.name.as_str() {
"echo" => Ok(vec![]),
"pick-one" => Ok(vec![
SlashCommandArgumentCompletion {
label: "Option One".to_string(),
new_text: "option-1".to_string(),
run_command: true,
},
SlashCommandArgumentCompletion {
label: "Option Two".to_string(),
new_text: "option-2".to_string(),
run_command: true,
},
SlashCommandArgumentCompletion {
label: "Option Three".to_string(),
new_text: "option-3".to_string(),
run_command: true,
},
]),
command => Err(format!("unknown slash command: \"{command}\"")),
}
}
}