extension_api.rs

  1//! The Zed Rust Extension API allows you write extensions for [Zed](https://zed.dev/) in Rust.
  2
  3/// Provides access to Zed settings.
  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::http_client::{fetch, HttpRequest, HttpResponse},
 23    zed::extension::nodejs::{
 24        node_binary_path, npm_install_package, npm_package_installed_version,
 25        npm_package_latest_version,
 26    },
 27    zed::extension::platform::{current_platform, Architecture, Os},
 28    zed::extension::slash_command::{SlashCommand, SlashCommandOutput, SlashCommandOutputSection},
 29    CodeLabel, CodeLabelSpan, CodeLabelSpanLiteral, Command, DownloadedFileType, EnvVars,
 30    LanguageServerInstallationStatus, Range, Worktree,
 31};
 32
 33// Undocumented WIT re-exports.
 34//
 35// These are symbols that need to be public for the purposes of implementing
 36// the extension host, but aren't relevant to extension authors.
 37#[doc(hidden)]
 38pub use wit::Guest;
 39
 40/// Constructs for interacting with language servers over the
 41/// Language Server Protocol (LSP).
 42pub mod lsp {
 43    pub use crate::wit::zed::extension::lsp::{
 44        Completion, CompletionKind, InsertTextFormat, Symbol, SymbolKind,
 45    };
 46}
 47
 48/// A result returned from a Zed extension.
 49pub type Result<T, E = String> = core::result::Result<T, E>;
 50
 51/// Updates the installation status for the given language server.
 52pub fn set_language_server_installation_status(
 53    language_server_id: &LanguageServerId,
 54    status: &LanguageServerInstallationStatus,
 55) {
 56    wit::set_language_server_installation_status(&language_server_id.0, status)
 57}
 58
 59/// A Zed extension.
 60pub trait Extension: Send + Sync {
 61    /// Returns a new instance of the extension.
 62    fn new() -> Self
 63    where
 64        Self: Sized;
 65
 66    /// Returns the command used to start the language server for the specified
 67    /// language.
 68    fn language_server_command(
 69        &mut self,
 70        _language_server_id: &LanguageServerId,
 71        _worktree: &Worktree,
 72    ) -> Result<Command> {
 73        Err("`language_server_command` not implemented".to_string())
 74    }
 75
 76    /// Returns the initialization options to pass to the specified language server.
 77    fn language_server_initialization_options(
 78        &mut self,
 79        _language_server_id: &LanguageServerId,
 80        _worktree: &Worktree,
 81    ) -> Result<Option<serde_json::Value>> {
 82        Ok(None)
 83    }
 84
 85    /// Returns the workspace configuration options to pass to the language server.
 86    fn language_server_workspace_configuration(
 87        &mut self,
 88        _language_server_id: &LanguageServerId,
 89        _worktree: &Worktree,
 90    ) -> Result<Option<serde_json::Value>> {
 91        Ok(None)
 92    }
 93
 94    /// Returns the label for the given completion.
 95    fn label_for_completion(
 96        &self,
 97        _language_server_id: &LanguageServerId,
 98        _completion: Completion,
 99    ) -> Option<CodeLabel> {
100        None
101    }
102
103    /// Returns the label for the given symbol.
104    fn label_for_symbol(
105        &self,
106        _language_server_id: &LanguageServerId,
107        _symbol: Symbol,
108    ) -> Option<CodeLabel> {
109        None
110    }
111
112    /// Returns the completions that should be shown when completing the provided slash command with the given query.
113    fn complete_slash_command_argument(
114        &self,
115        _command: SlashCommand,
116        _query: String,
117    ) -> Result<Vec<String>, String> {
118        Ok(Vec::new())
119    }
120
121    /// Returns the output from running the provided slash command.
122    fn run_slash_command(
123        &self,
124        _command: SlashCommand,
125        _argument: Option<String>,
126        _worktree: &Worktree,
127    ) -> Result<SlashCommandOutput, String> {
128        Err("`run_slash_command` not implemented".to_string())
129    }
130}
131
132/// Registers the provided type as a Zed extension.
133///
134/// The type must implement the [`Extension`] trait.
135#[macro_export]
136macro_rules! register_extension {
137    ($extension_type:ty) => {
138        #[export_name = "init-extension"]
139        pub extern "C" fn __init_extension() {
140            std::env::set_current_dir(std::env::var("PWD").unwrap()).unwrap();
141            zed_extension_api::register_extension(|| {
142                Box::new(<$extension_type as zed_extension_api::Extension>::new())
143            });
144        }
145    };
146}
147
148#[doc(hidden)]
149pub fn register_extension(build_extension: fn() -> Box<dyn Extension>) {
150    unsafe { EXTENSION = Some((build_extension)()) }
151}
152
153fn extension() -> &'static mut dyn Extension {
154    unsafe { EXTENSION.as_deref_mut().unwrap() }
155}
156
157static mut EXTENSION: Option<Box<dyn Extension>> = None;
158
159#[cfg(target_arch = "wasm32")]
160#[link_section = "zed:api-version"]
161#[doc(hidden)]
162pub static ZED_API_VERSION: [u8; 6] = *include_bytes!(concat!(env!("OUT_DIR"), "/version_bytes"));
163
164mod wit {
165    #![allow(clippy::too_many_arguments)]
166
167    wit_bindgen::generate!({
168        skip: ["init-extension"],
169        path: "./wit/since_v0.0.7",
170    });
171}
172
173wit::export!(Component);
174
175struct Component;
176
177impl wit::Guest for Component {
178    fn language_server_command(
179        language_server_id: String,
180        worktree: &wit::Worktree,
181    ) -> Result<wit::Command> {
182        let language_server_id = LanguageServerId(language_server_id);
183        extension().language_server_command(&language_server_id, worktree)
184    }
185
186    fn language_server_initialization_options(
187        language_server_id: String,
188        worktree: &Worktree,
189    ) -> Result<Option<String>, String> {
190        let language_server_id = LanguageServerId(language_server_id);
191        Ok(extension()
192            .language_server_initialization_options(&language_server_id, worktree)?
193            .and_then(|value| serde_json::to_string(&value).ok()))
194    }
195
196    fn language_server_workspace_configuration(
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_workspace_configuration(&language_server_id, worktree)?
203            .and_then(|value| serde_json::to_string(&value).ok()))
204    }
205
206    fn labels_for_completions(
207        language_server_id: String,
208        completions: Vec<Completion>,
209    ) -> Result<Vec<Option<CodeLabel>>, String> {
210        let language_server_id = LanguageServerId(language_server_id);
211        let mut labels = Vec::new();
212        for (ix, completion) in completions.into_iter().enumerate() {
213            let label = extension().label_for_completion(&language_server_id, completion);
214            if let Some(label) = label {
215                labels.resize(ix + 1, None);
216                *labels.last_mut().unwrap() = Some(label);
217            }
218        }
219        Ok(labels)
220    }
221
222    fn labels_for_symbols(
223        language_server_id: String,
224        symbols: Vec<Symbol>,
225    ) -> Result<Vec<Option<CodeLabel>>, String> {
226        let language_server_id = LanguageServerId(language_server_id);
227        let mut labels = Vec::new();
228        for (ix, symbol) in symbols.into_iter().enumerate() {
229            let label = extension().label_for_symbol(&language_server_id, symbol);
230            if let Some(label) = label {
231                labels.resize(ix + 1, None);
232                *labels.last_mut().unwrap() = Some(label);
233            }
234        }
235        Ok(labels)
236    }
237
238    fn complete_slash_command_argument(
239        command: SlashCommand,
240        query: String,
241    ) -> Result<Vec<String>, String> {
242        extension().complete_slash_command_argument(command, query)
243    }
244
245    fn run_slash_command(
246        command: SlashCommand,
247        argument: Option<String>,
248        worktree: &Worktree,
249    ) -> Result<SlashCommandOutput, String> {
250        extension().run_slash_command(command, argument, worktree)
251    }
252}
253
254/// The ID of a language server.
255#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
256pub struct LanguageServerId(String);
257
258impl AsRef<str> for LanguageServerId {
259    fn as_ref(&self) -> &str {
260        &self.0
261    }
262}
263
264impl fmt::Display for LanguageServerId {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        write!(f, "{}", self.0)
267    }
268}
269
270impl CodeLabelSpan {
271    /// Returns a [`CodeLabelSpan::CodeRange`].
272    pub fn code_range(range: impl Into<wit::Range>) -> Self {
273        Self::CodeRange(range.into())
274    }
275
276    /// Returns a [`CodeLabelSpan::Literal`].
277    pub fn literal(text: impl Into<String>, highlight_name: Option<String>) -> Self {
278        Self::Literal(CodeLabelSpanLiteral {
279            text: text.into(),
280            highlight_name,
281        })
282    }
283}
284
285impl From<std::ops::Range<u32>> for wit::Range {
286    fn from(value: std::ops::Range<u32>) -> Self {
287        Self {
288            start: value.start,
289            end: value.end,
290        }
291    }
292}
293
294impl From<std::ops::Range<usize>> for wit::Range {
295    fn from(value: std::ops::Range<usize>) -> Self {
296        Self {
297            start: value.start as u32,
298            end: value.end as u32,
299        }
300    }
301}