extension_api.rs

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