1//! The Zed Rust Extension API allows you write extensions for [Zed](https://zed.dev/) in Rust.
2
3pub mod http_client;
4pub mod settings;
5
6use core::fmt;
7
8use wit::*;
9
10pub use serde_json;
11
12// WIT re-exports.
13//
14// We explicitly enumerate the symbols we want to re-export, as there are some
15// that we may want to shadow to provide a cleaner Rust API.
16pub use wit::{
17 download_file, make_file_executable,
18 zed::extension::github::{
19 github_release_by_tag_name, latest_github_release, GithubRelease, GithubReleaseAsset,
20 GithubReleaseOptions,
21 },
22 zed::extension::nodejs::{
23 node_binary_path, npm_install_package, npm_package_installed_version,
24 npm_package_latest_version,
25 },
26 zed::extension::platform::{current_platform, Architecture, Os},
27 zed::extension::slash_command::{
28 SlashCommand, SlashCommandArgumentCompletion, SlashCommandOutput, SlashCommandOutputSection,
29 },
30 CodeLabel, CodeLabelSpan, CodeLabelSpanLiteral, Command, DownloadedFileType, EnvVars,
31 KeyValueStore, LanguageServerInstallationStatus, Range, Worktree,
32};
33
34// Undocumented WIT re-exports.
35//
36// These are symbols that need to be public for the purposes of implementing
37// the extension host, but aren't relevant to extension authors.
38#[doc(hidden)]
39pub use wit::Guest;
40
41/// Constructs for interacting with language servers over the
42/// Language Server Protocol (LSP).
43pub mod lsp {
44 pub use crate::wit::zed::extension::lsp::{
45 Completion, CompletionKind, InsertTextFormat, Symbol, SymbolKind,
46 };
47}
48
49/// A result returned from a Zed extension.
50pub type Result<T, E = String> = core::result::Result<T, E>;
51
52/// Updates the installation status for the given language server.
53pub fn set_language_server_installation_status(
54 language_server_id: &LanguageServerId,
55 status: &LanguageServerInstallationStatus,
56) {
57 wit::set_language_server_installation_status(&language_server_id.0, status)
58}
59
60/// A Zed extension.
61pub trait Extension: Send + Sync {
62 /// Returns a new instance of the extension.
63 fn new() -> Self
64 where
65 Self: Sized;
66
67 /// Returns the command used to start the language server for the specified
68 /// language.
69 fn language_server_command(
70 &mut self,
71 _language_server_id: &LanguageServerId,
72 _worktree: &Worktree,
73 ) -> Result<Command> {
74 Err("`language_server_command` not implemented".to_string())
75 }
76
77 /// Returns the initialization options to pass to the specified language server.
78 fn language_server_initialization_options(
79 &mut self,
80 _language_server_id: &LanguageServerId,
81 _worktree: &Worktree,
82 ) -> Result<Option<serde_json::Value>> {
83 Ok(None)
84 }
85
86 /// Returns the workspace configuration options to pass to the language server.
87 fn language_server_workspace_configuration(
88 &mut self,
89 _language_server_id: &LanguageServerId,
90 _worktree: &Worktree,
91 ) -> Result<Option<serde_json::Value>> {
92 Ok(None)
93 }
94
95 /// Returns the label for the given completion.
96 fn label_for_completion(
97 &self,
98 _language_server_id: &LanguageServerId,
99 _completion: Completion,
100 ) -> Option<CodeLabel> {
101 None
102 }
103
104 /// Returns the label for the given symbol.
105 fn label_for_symbol(
106 &self,
107 _language_server_id: &LanguageServerId,
108 _symbol: Symbol,
109 ) -> Option<CodeLabel> {
110 None
111 }
112
113 /// Returns the completions that should be shown when completing the provided slash command with the given query.
114 fn complete_slash_command_argument(
115 &self,
116 _command: SlashCommand,
117 _args: Vec<String>,
118 ) -> Result<Vec<SlashCommandArgumentCompletion>, String> {
119 Ok(Vec::new())
120 }
121
122 /// Returns the output from running the provided slash command.
123 fn run_slash_command(
124 &self,
125 _command: SlashCommand,
126 _args: Vec<String>,
127 _worktree: Option<&Worktree>,
128 ) -> Result<SlashCommandOutput, String> {
129 Err("`run_slash_command` not implemented".to_string())
130 }
131
132 /// Returns the command used to start a context server.
133 fn context_server_command(&mut self, _context_server_id: &ContextServerId) -> Result<Command> {
134 Err("`context_server_command` not implemented".to_string())
135 }
136
137 /// Returns a list of package names as suggestions to be included in the
138 /// search results of the `/docs` slash command.
139 ///
140 /// This can be used to provide completions for known packages (e.g., from the
141 /// local project or a registry) before a package has been indexed.
142 fn suggest_docs_packages(&self, _provider: String) -> Result<Vec<String>, String> {
143 Ok(Vec::new())
144 }
145
146 /// Indexes the docs for the specified package.
147 fn index_docs(
148 &self,
149 _provider: String,
150 _package: String,
151 _database: &KeyValueStore,
152 ) -> Result<(), String> {
153 Err("`index_docs` not implemented".to_string())
154 }
155}
156
157/// Registers the provided type as a Zed extension.
158///
159/// The type must implement the [`Extension`] trait.
160#[macro_export]
161macro_rules! register_extension {
162 ($extension_type:ty) => {
163 #[export_name = "init-extension"]
164 pub extern "C" fn __init_extension() {
165 std::env::set_current_dir(std::env::var("PWD").unwrap()).unwrap();
166 zed_extension_api::register_extension(|| {
167 Box::new(<$extension_type as zed_extension_api::Extension>::new())
168 });
169 }
170 };
171}
172
173#[doc(hidden)]
174pub fn register_extension(build_extension: fn() -> Box<dyn Extension>) {
175 unsafe { EXTENSION = Some((build_extension)()) }
176}
177
178fn extension() -> &'static mut dyn Extension {
179 unsafe { EXTENSION.as_deref_mut().unwrap() }
180}
181
182static mut EXTENSION: Option<Box<dyn Extension>> = None;
183
184#[cfg(target_arch = "wasm32")]
185#[link_section = "zed:api-version"]
186#[doc(hidden)]
187pub static ZED_API_VERSION: [u8; 6] = *include_bytes!(concat!(env!("OUT_DIR"), "/version_bytes"));
188
189mod wit {
190 #![allow(clippy::too_many_arguments, clippy::missing_safety_doc)]
191
192 wit_bindgen::generate!({
193 skip: ["init-extension"],
194 path: "./wit/since_v0.2.0",
195 });
196}
197
198wit::export!(Component);
199
200struct Component;
201
202impl wit::Guest for Component {
203 fn language_server_command(
204 language_server_id: String,
205 worktree: &wit::Worktree,
206 ) -> Result<wit::Command> {
207 let language_server_id = LanguageServerId(language_server_id);
208 extension().language_server_command(&language_server_id, worktree)
209 }
210
211 fn language_server_initialization_options(
212 language_server_id: String,
213 worktree: &Worktree,
214 ) -> Result<Option<String>, String> {
215 let language_server_id = LanguageServerId(language_server_id);
216 Ok(extension()
217 .language_server_initialization_options(&language_server_id, worktree)?
218 .and_then(|value| serde_json::to_string(&value).ok()))
219 }
220
221 fn language_server_workspace_configuration(
222 language_server_id: String,
223 worktree: &Worktree,
224 ) -> Result<Option<String>, String> {
225 let language_server_id = LanguageServerId(language_server_id);
226 Ok(extension()
227 .language_server_workspace_configuration(&language_server_id, worktree)?
228 .and_then(|value| serde_json::to_string(&value).ok()))
229 }
230
231 fn labels_for_completions(
232 language_server_id: String,
233 completions: Vec<Completion>,
234 ) -> Result<Vec<Option<CodeLabel>>, String> {
235 let language_server_id = LanguageServerId(language_server_id);
236 let mut labels = Vec::new();
237 for (ix, completion) in completions.into_iter().enumerate() {
238 let label = extension().label_for_completion(&language_server_id, completion);
239 if let Some(label) = label {
240 labels.resize(ix + 1, None);
241 *labels.last_mut().unwrap() = Some(label);
242 }
243 }
244 Ok(labels)
245 }
246
247 fn labels_for_symbols(
248 language_server_id: String,
249 symbols: Vec<Symbol>,
250 ) -> Result<Vec<Option<CodeLabel>>, String> {
251 let language_server_id = LanguageServerId(language_server_id);
252 let mut labels = Vec::new();
253 for (ix, symbol) in symbols.into_iter().enumerate() {
254 let label = extension().label_for_symbol(&language_server_id, symbol);
255 if let Some(label) = label {
256 labels.resize(ix + 1, None);
257 *labels.last_mut().unwrap() = Some(label);
258 }
259 }
260 Ok(labels)
261 }
262
263 fn complete_slash_command_argument(
264 command: SlashCommand,
265 args: Vec<String>,
266 ) -> Result<Vec<SlashCommandArgumentCompletion>, String> {
267 extension().complete_slash_command_argument(command, args)
268 }
269
270 fn run_slash_command(
271 command: SlashCommand,
272 args: Vec<String>,
273 worktree: Option<&Worktree>,
274 ) -> Result<SlashCommandOutput, String> {
275 extension().run_slash_command(command, args, worktree)
276 }
277
278 fn context_server_command(context_server_id: String) -> Result<wit::Command> {
279 let context_server_id = ContextServerId(context_server_id);
280 extension().context_server_command(&context_server_id)
281 }
282
283 fn suggest_docs_packages(provider: String) -> Result<Vec<String>, String> {
284 extension().suggest_docs_packages(provider)
285 }
286
287 fn index_docs(
288 provider: String,
289 package: String,
290 database: &KeyValueStore,
291 ) -> Result<(), String> {
292 extension().index_docs(provider, package, database)
293 }
294}
295
296/// The ID of a language server.
297#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
298pub struct LanguageServerId(String);
299
300impl AsRef<str> for LanguageServerId {
301 fn as_ref(&self) -> &str {
302 &self.0
303 }
304}
305
306impl fmt::Display for LanguageServerId {
307 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308 write!(f, "{}", self.0)
309 }
310}
311
312/// The ID of a context server.
313#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
314pub struct ContextServerId(String);
315
316impl AsRef<str> for ContextServerId {
317 fn as_ref(&self) -> &str {
318 &self.0
319 }
320}
321
322impl fmt::Display for ContextServerId {
323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324 write!(f, "{}", self.0)
325 }
326}
327
328impl CodeLabelSpan {
329 /// Returns a [`CodeLabelSpan::CodeRange`].
330 pub fn code_range(range: impl Into<wit::Range>) -> Self {
331 Self::CodeRange(range.into())
332 }
333
334 /// Returns a [`CodeLabelSpan::Literal`].
335 pub fn literal(text: impl Into<String>, highlight_name: Option<String>) -> Self {
336 Self::Literal(CodeLabelSpanLiteral {
337 text: text.into(),
338 highlight_name,
339 })
340 }
341}
342
343impl From<std::ops::Range<u32>> for wit::Range {
344 fn from(value: std::ops::Range<u32>) -> Self {
345 Self {
346 start: value.start,
347 end: value.end,
348 }
349 }
350}
351
352impl From<std::ops::Range<usize>> for wit::Range {
353 fn from(value: std::ops::Range<usize>) -> Self {
354 Self {
355 start: value.start as u32,
356 end: value.end as u32,
357 }
358 }
359}