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 _query: 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 _argument: Option<String>,
127 _worktree: Option<&Worktree>,
128 ) -> Result<SlashCommandOutput, String> {
129 Err("`run_slash_command` not implemented".to_string())
130 }
131
132 fn index_docs(
133 &self,
134 _provider: String,
135 _package: String,
136 _database: &KeyValueStore,
137 ) -> Result<(), String> {
138 Err("`index_docs` not implemented".to_string())
139 }
140}
141
142/// Registers the provided type as a Zed extension.
143///
144/// The type must implement the [`Extension`] trait.
145#[macro_export]
146macro_rules! register_extension {
147 ($extension_type:ty) => {
148 #[export_name = "init-extension"]
149 pub extern "C" fn __init_extension() {
150 std::env::set_current_dir(std::env::var("PWD").unwrap()).unwrap();
151 zed_extension_api::register_extension(|| {
152 Box::new(<$extension_type as zed_extension_api::Extension>::new())
153 });
154 }
155 };
156}
157
158#[doc(hidden)]
159pub fn register_extension(build_extension: fn() -> Box<dyn Extension>) {
160 unsafe { EXTENSION = Some((build_extension)()) }
161}
162
163fn extension() -> &'static mut dyn Extension {
164 unsafe { EXTENSION.as_deref_mut().unwrap() }
165}
166
167static mut EXTENSION: Option<Box<dyn Extension>> = None;
168
169#[cfg(target_arch = "wasm32")]
170#[link_section = "zed:api-version"]
171#[doc(hidden)]
172pub static ZED_API_VERSION: [u8; 6] = *include_bytes!(concat!(env!("OUT_DIR"), "/version_bytes"));
173
174mod wit {
175 #![allow(clippy::too_many_arguments)]
176
177 wit_bindgen::generate!({
178 skip: ["init-extension"],
179 path: "./wit/since_v0.1.0",
180 });
181}
182
183wit::export!(Component);
184
185struct Component;
186
187impl wit::Guest for Component {
188 fn language_server_command(
189 language_server_id: String,
190 worktree: &wit::Worktree,
191 ) -> Result<wit::Command> {
192 let language_server_id = LanguageServerId(language_server_id);
193 extension().language_server_command(&language_server_id, worktree)
194 }
195
196 fn language_server_initialization_options(
197 language_server_id: String,
198 worktree: &Worktree,
199 ) -> Result<Option<String>, String> {
200 let language_server_id = LanguageServerId(language_server_id);
201 Ok(extension()
202 .language_server_initialization_options(&language_server_id, worktree)?
203 .and_then(|value| serde_json::to_string(&value).ok()))
204 }
205
206 fn language_server_workspace_configuration(
207 language_server_id: String,
208 worktree: &Worktree,
209 ) -> Result<Option<String>, String> {
210 let language_server_id = LanguageServerId(language_server_id);
211 Ok(extension()
212 .language_server_workspace_configuration(&language_server_id, worktree)?
213 .and_then(|value| serde_json::to_string(&value).ok()))
214 }
215
216 fn labels_for_completions(
217 language_server_id: String,
218 completions: Vec<Completion>,
219 ) -> Result<Vec<Option<CodeLabel>>, String> {
220 let language_server_id = LanguageServerId(language_server_id);
221 let mut labels = Vec::new();
222 for (ix, completion) in completions.into_iter().enumerate() {
223 let label = extension().label_for_completion(&language_server_id, completion);
224 if let Some(label) = label {
225 labels.resize(ix + 1, None);
226 *labels.last_mut().unwrap() = Some(label);
227 }
228 }
229 Ok(labels)
230 }
231
232 fn labels_for_symbols(
233 language_server_id: String,
234 symbols: Vec<Symbol>,
235 ) -> Result<Vec<Option<CodeLabel>>, String> {
236 let language_server_id = LanguageServerId(language_server_id);
237 let mut labels = Vec::new();
238 for (ix, symbol) in symbols.into_iter().enumerate() {
239 let label = extension().label_for_symbol(&language_server_id, symbol);
240 if let Some(label) = label {
241 labels.resize(ix + 1, None);
242 *labels.last_mut().unwrap() = Some(label);
243 }
244 }
245 Ok(labels)
246 }
247
248 fn complete_slash_command_argument(
249 command: SlashCommand,
250 query: String,
251 ) -> Result<Vec<SlashCommandArgumentCompletion>, String> {
252 extension().complete_slash_command_argument(command, query)
253 }
254
255 fn run_slash_command(
256 command: SlashCommand,
257 argument: Option<String>,
258 worktree: Option<&Worktree>,
259 ) -> Result<SlashCommandOutput, String> {
260 extension().run_slash_command(command, argument, worktree)
261 }
262
263 fn index_docs(
264 provider: String,
265 package: String,
266 database: &KeyValueStore,
267 ) -> Result<(), String> {
268 extension().index_docs(provider, package, database)
269 }
270}
271
272/// The ID of a language server.
273#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
274pub struct LanguageServerId(String);
275
276impl AsRef<str> for LanguageServerId {
277 fn as_ref(&self) -> &str {
278 &self.0
279 }
280}
281
282impl fmt::Display for LanguageServerId {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 write!(f, "{}", self.0)
285 }
286}
287
288impl CodeLabelSpan {
289 /// Returns a [`CodeLabelSpan::CodeRange`].
290 pub fn code_range(range: impl Into<wit::Range>) -> Self {
291 Self::CodeRange(range.into())
292 }
293
294 /// Returns a [`CodeLabelSpan::Literal`].
295 pub fn literal(text: impl Into<String>, highlight_name: Option<String>) -> Self {
296 Self::Literal(CodeLabelSpanLiteral {
297 text: text.into(),
298 highlight_name,
299 })
300 }
301}
302
303impl From<std::ops::Range<u32>> for wit::Range {
304 fn from(value: std::ops::Range<u32>) -> Self {
305 Self {
306 start: value.start,
307 end: value.end,
308 }
309 }
310}
311
312impl From<std::ops::Range<usize>> for wit::Range {
313 fn from(value: std::ops::Range<usize>) -> Self {
314 Self {
315 start: value.start as u32,
316 end: value.end as u32,
317 }
318 }
319}