### Update Language Server Installation Status with Rust Source: https://context7.com/mrtomatepng/zed_extension_api/llms.txt Demonstrates how to update and display the installation status of language servers using the `zed_extension_api`. This provides user feedback during the setup process. It covers 'Downloading', 'CheckingForUpdate', and 'Failed' statuses, clearing the status upon success. ```rust use zed_extension_api::{ set_language_server_installation_status, LanguageServerInstallationStatus, LanguageServerId, }; fn install_server(server_id: &LanguageServerId) -> Result<(), String> { // Show downloading status set_language_server_installation_status( server_id, &LanguageServerInstallationStatus::Downloading, ); // Download the server... // download_file(...)?; // Show extraction/installation status set_language_server_installation_status( server_id, &LanguageServerInstallationStatus::CheckingForUpdate, ); // Verify installation... // Clear status on success (None means installed and ready) set_language_server_installation_status( server_id, &LanguageServerInstallationStatus::None, ); Ok(()) } fn handle_install_failure(server_id: &LanguageServerId, error: &str) { set_language_server_installation_status( server_id, &LanguageServerInstallationStatus::Failed(error.to_string()), ); } ``` -------------------------------- ### Get Language Server Command (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/trait.Extension.html Retrieves the command used to start a language server for a given language server ID and worktree. It returns a Result containing a Command, or an error if the command cannot be retrieved. ```rust fn language_server_command(&mut self, _language_server_id: &LanguageServerId, _worktree: &Worktree) -> Result ``` -------------------------------- ### Install NPM Package (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/fn.npm_install_package.html The `npm_install_package` function installs a specified NPM package and version. It takes the package name and version as string slices and returns a Result indicating success or failure with an error message. ```Rust pub fn npm_install_package( package_name: &str, version: &str, ) -> Result<(), String> ``` -------------------------------- ### Set Language Server Installation Status in Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/fn.set_language_server_installation_status.html Updates the installation status for a given language server. This function takes a LanguageServerId and a LanguageServerInstallationStatus as input. ```rust pub fn set_language_server_installation_status( language_server_id: &LanguageServerId, status: &LanguageServerInstallationStatus, ) ``` -------------------------------- ### StartDebuggingRequestArguments Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.StartDebuggingRequestArguments.html Arguments for starting a debugging session. This structure defines the necessary parameters to initiate debugging within Zed extensions. ```APIDOC ## Struct StartDebuggingRequestArguments ### Description Arguments for starting a debugging session. This structure defines the necessary parameters to initiate debugging within Zed extensions. ### Fields #### `configuration` - **Type**: String - **Description**: JSON-encoded configuration for a given debug adapter. It is specific to each debug adapter. `configuration` will have its Zed variable references substituted prior to being passed to the debug adapter. #### `request` - **Type**: StartDebuggingRequestArgumentsRequest (enum) - **Description**: Specifies the type of debugging request. ### Example Request Body ```json { "configuration": "{\"program\": \"main.py\", \"request\": \"launch\"}", "request": { "type": "launch" } } ``` ### Example Success Response (200) ```json { "success": true } ``` ### Error Handling - **400 Bad Request**: Invalid request parameters. - **500 Internal Server Error**: An unexpected error occurred on the server. ``` -------------------------------- ### Get Language Server Initialization Options (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/trait.Extension.html Fetches the initialization options for a specified language server and worktree. The options are returned as an Option containing a JSON Value, or None if no options are configured. ```rust fn language_server_initialization_options(&mut self, _language_server_id: &LanguageServerId, _worktree: &Worktree) -> Result> ``` -------------------------------- ### Set Language Server Installation Status Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/fn.set_language_server_installation_status.html Updates the installation status for a specific language server within the Zed extension API. ```APIDOC ## POST /_extensions/language_servers/:language_server_id/installation_status ### Description Updates the installation status for the given language server. ### Method POST ### Endpoint /_extensions/language_servers/:language_server_id/installation_status ### Parameters #### Path Parameters - **language_server_id** (LanguageServerId) - Required - The unique identifier for the language server. #### Query Parameters None #### Request Body - **status** (LanguageServerInstallationStatus) - Required - The new installation status for the language server. ### Request Example ```json { "status": "installed" } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the status update was successful. #### Response Example ```json { "message": "Language server installation status updated successfully." } ``` ``` -------------------------------- ### Manage NPM Packages for Language Servers (Rust) Source: https://context7.com/mrtomatepng/zed_extension_api/llms.txt Provides helper functions for managing NPM packages, specifically for Node.js-based language servers. It includes logic to check the installed version, compare it with the latest available version, install or update the package if necessary, and locate the Node.js binary. ```rust use zed_extension_api::{ node_binary_path, npm_install_package, npm_package_installed_version, npm_package_latest_version, Result, Command, }; fn setup_typescript_server() -> Result { let package = "typescript-language-server"; // Check installed version let installed = npm_package_installed_version(package)?; let latest = npm_package_latest_version(package)?; // Install or update if needed if installed.as_ref() != Some(&latest) { npm_install_package(package, &latest)?; } // Get the Node.js binary path let node = node_binary_path()?; Ok(Command { command: node, args: vec![ "node_modules/.bin/typescript-language-server".to_string(), "--stdio".to_string(), ], env: vec![], }) } ``` -------------------------------- ### Get Additional Language Server Initialization Options (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/trait.Extension.html Fetches initialization options intended for a target language server, distinct from the primary one. This is useful for inter-language-server communication or specific configurations. ```rust fn language_server_additional_initialization_options(&mut self, _language_server_id: &LanguageServerId, _target_language_server_id: &LanguageServerId, _worktree: &Worktree) -> Result> ``` -------------------------------- ### Index Documentation with KeyValueStore in Rust Source: https://context7.com/mrtomatepng/zed_extension_api/llms.txt Illustrates how to use `KeyValueStore` for persistent storage of indexed documentation. This example shows an extension that suggests packages to index and then uses `index_docs` to store searchable documentation entries. It relies on a `fetch_package_docs` helper function. ```rust use zed_extension_api::{Extension, KeyValueStore, Result}; struct DocsIndexer; impl Extension for DocsIndexer { fn new() -> Self { DocsIndexer } fn suggest_docs_packages(&self, provider: String) -> Result, String> { // Suggest packages that can be indexed Ok(vec![ "react".to_string(), "vue".to_string(), "angular".to_string(), ]) } fn index_docs( &self, provider: String, package: String, database: &KeyValueStore, ) -> Result<(), String> { // Fetch documentation for the package let docs = fetch_package_docs(&package)?; // Index each documentation entry for (key, content) in docs { database.insert(&key, &content)?; } Ok(()) } } fn fetch_package_docs(package: &str) -> Result, String> { // Fetch and parse documentation... Ok(vec![ (format!("{}/getting-started", package), "# Getting Started\n...".to_string()), (format!("{}/api-reference", package), "# API Reference\n...".to_string()), ]) } ``` -------------------------------- ### Get Language Server Workspace Configuration (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/trait.Extension.html Retrieves the workspace configuration options for a language server within a given worktree. The configuration is returned as an Option containing a JSON Value, or None if no configuration is set. ```rust fn language_server_workspace_configuration(&mut self, _language_server_id: &LanguageServerId, _worktree: &Worktree) -> Result> ``` -------------------------------- ### Implement Zed Extension Trait and Register Source: https://context7.com/mrtomatepng/zed_extension_api/llms.txt Demonstrates implementing the core `Extension` trait for a Zed extension in Rust. It includes the required `new()` method and an example of `language_server_command` for finding and configuring a language server binary. The `zed::register_extension!` macro is used to make the extension discoverable by Zed. ```rust use zed_extension_api::{self as zed, Extension, Result, Command, LanguageServerId, Worktree}; use zed_extension_api::serde_json::{self, json}; struct MyExtension { cached_binary_path: Option, } impl Extension for MyExtension { fn new() -> Self { MyExtension { cached_binary_path: None, } } fn language_server_command( &mut self, language_server_id: &LanguageServerId, worktree: &Worktree, ) -> Result { // Find or download the language server binary let binary_path = worktree .which("my-language-server") .ok_or_else(|| "my-language-server not found in PATH".to_string())?; Ok(Command { command: binary_path, args: vec!["--stdio".to_string()], env: vec![("MY_ENV_VAR".to_string(), "value".to_string())], }) } fn language_server_initialization_options( &mut self, _language_server_id: &LanguageServerId, _worktree: &Worktree, ) -> Result> { Ok(Some(json!({ "typescript": { "tsdk": "./node_modules/typescript/lib" }, "diagnostics": { "enable": true } }))) } } zed::register_extension!(MyExtension); ``` -------------------------------- ### Get DAP Binary Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/trait.Extension.html Retrieves the debug adapter binary for a given adapter name and configuration. This is essential for launching or attaching to debug sessions. ```APIDOC ## GET /mrtomatepng/zed_extension_api/dap/binary ### Description Retrieves the debug adapter binary for the specified adapter name and configuration. ### Method GET ### Endpoint /mrtomatepng/zed_extension_api/dap/binary ### Parameters #### Query Parameters - **adapter_name** (String) - Required - The name of the debug adapter. - **config** (DebugTaskDefinition) - Required - The debug task definition configuration. - **user_provided_debug_adapter_path** (Option) - Optional - The user-provided path to the debug adapter. - **worktree** (Worktree) - Required - The worktree context. ### Response #### Success Response (200) - **DebugAdapterBinary** - An object representing the debug adapter binary. #### Response Example ```json { "path": "/path/to/debug/adapter", "args": ["--arg1", "--arg2"] } ``` ``` -------------------------------- ### Redirect to npm_package_installed_version Function Documentation Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/wit/zed/extension/nodejs/fn.npm_package_installed_version.html This JavaScript code snippet demonstrates how to redirect the current page to the documentation for the `npm_package_installed_version` function within the Zed Extension API. It preserves the existing query parameters and hash fragments from the current URL. This is useful for dynamically guiding users to relevant API documentation. ```javascript location.replace("../../../../../zed_extension_api/fn.npm_package_installed_version.html" + location.search + location.hash); ``` -------------------------------- ### Get Additional Language Server Workspace Configuration (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/trait.Extension.html Retrieves workspace configuration options for a target language server, separate from the main language server's configuration. This allows for fine-grained control over configurations passed between language servers. ```rust fn language_server_additional_workspace_configuration(&mut self, _language_server_id: &LanguageServerId, _target_language_server_id: &LanguageServerId, _worktree: &Worktree) -> Result> ``` -------------------------------- ### Define ContextServerConfiguration Struct in Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.ContextServerConfiguration.html Defines the ContextServerConfiguration struct in Rust, which contains fields for installation instructions, settings schema, and default settings. These fields are all of type String. ```rust pub struct ContextServerConfiguration { pub installation_instructions: String, pub settings_schema: String, pub default_settings: String, } ``` -------------------------------- ### Rust Enum: LanguageServerInstallationStatus Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/enum.LanguageServerInstallationStatus.html Defines the possible states for a language server's installation process. It includes variants for no status, downloading, checking for updates, and a failed state that carries an error message. ```rust pub enum LanguageServerInstallationStatus { None, Downloading, CheckingForUpdate, Failed(String), } ``` -------------------------------- ### Get Debug Adapter Binary (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/trait.Extension.html Retrieves the debug adapter binary based on the adapter name and configuration. It takes adapter name, debug task definition, an optional user-provided path, and the worktree as input. It returns a Result containing the DebugAdapterBinary or an error string. ```rust fn get_dap_binary(&mut self, _adapter_name: String, _config: DebugTaskDefinition, _user_provided_debug_adapter_path: Option, _worktree: &[Worktree]) -> Result ``` -------------------------------- ### Get Current Platform (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/fn.current_platform.html Retrieves the current operating system and architecture using the `current_platform` function. This function returns a tuple containing the OS and Architecture. No external dependencies are required beyond the `zed_extension_api` library itself. ```rust pub fn current_platform() -> (Os, Architecture) ``` -------------------------------- ### Get NPM Package Installed Version (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/fn.npm_package_installed_version.html This Rust function, `npm_package_installed_version`, takes an NPM package name as a string and returns a `Result` containing an `Option` which is the installed version if found, or an error string if an issue occurs. It is part of the zed_extension_api. ```rust pub fn npm_package_installed_version( package_name: &str, ) -> Result, String> ``` -------------------------------- ### CloneToUninit Trait Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/lsp/struct.Completion.html Documentation for the CloneToUninit trait, which allows for efficient cloning to uninitialized memory. ```APIDOC ## CloneToUninit Trait ### Description Provides a method for performing copy-assignment from `self` to an uninitialized destination. ### Method `unsafe fn clone_to_uninit(&self, dest: *mut u8)` ### Endpoint N/A (Trait method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage within a context where clone_to_uninit is applicable // let mut uninit_buffer = vec![0u8; size_of::()]; // unsafe { // my_value.clone_to_uninit(uninit_buffer.as_mut_ptr()); // } ``` ### Response #### Success Response (N/A) This is an unsafe method that modifies memory directly. #### Response Example None ``` -------------------------------- ### From and Into Traits Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/lsp/struct.Completion.html Documentation for the From and Into traits, facilitating type conversions. ```APIDOC ## From and Into Traits ### Description The `From for T` trait indicates that a type can be created from itself, essentially returning the argument unchanged. The `Into for T` trait provides a convenient way to perform conversions where `U` implements `From`. ### Method `fn from(t: T) -> T` (for `From`) `fn into(self) -> U` (for `Into`) ### Endpoint N/A (Trait methods) ### Parameters None ### Request Example ```rust let value = 5; let from_value: i32 = From::from(value); let into_value: i32 = value.into(); ``` ### Response #### Success Response (N/A) Returns the converted value. #### Response Example ```json // No specific JSON response, as these are type conversions. ``` ``` -------------------------------- ### TryFrom and TryInto Traits Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/lsp/struct.Completion.html Documentation for the TryFrom and TryInto traits, enabling fallible type conversions. ```APIDOC ## TryFrom and TryInto Traits ### Description These traits facilitate fallible type conversions. `TryFrom for T` attempts to convert a `U` into a `T`, returning a `Result`. `TryInto for T` is the reciprocal, attempting to convert `T` into `U`. ### Associated Type `type Error` (for `TryFrom`) ### Methods `fn try_from(value: U) -> Result` ### Endpoint N/A (Trait methods) ### Parameters None ### Request Example ```rust // Assuming a conversion from u8 to i32 is possible and infallible in this context use std::convert::TryFrom; let u8_val: u8 = 10; let i32_val: Result = i32::try_from(u8_val); // Example with a fallible conversion (conceptual) // let result: Result = MyType::try_from(some_other_type); ``` ### Response #### Success Response (N/A) Returns a `Result` containing the converted value on success or an error on failure. #### Response Example ```json // No specific JSON response, as these are type conversions. ``` ``` -------------------------------- ### Define Range Struct in Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/type.Range.html Defines the Range struct with 'start' and 'end' fields, both of type u32. The #[repr(C)] attribute ensures C-compatible memory layout, which is often used for FFI or when interoperability with other languages is required. 'start' is inclusive, and 'end' is exclusive. ```rust #[repr(C)] pub struct Range { pub start: u32, pub end: u32, } ``` -------------------------------- ### npm_package_installed_version Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/fn.npm_package_installed_version.html Retrieves the installed version of a specified NPM package. ```APIDOC ## npm_package_installed_version ### Description Returns the installed version of the given NPM package, if it exists. ### Method GET (Assumed, as it retrieves information) ### Endpoint /npm_package_installed_version ### Parameters #### Query Parameters - **package_name** (string) - Required - The name of the NPM package to check. ### Request Example ```json { "package_name": "react" } ``` ### Response #### Success Response (200) - **version** (string | null) - The installed version of the package, or null if not found. #### Response Example ```json { "version": "18.2.0" } ``` #### Error Response (500) - **error** (string) - A message describing the error. #### Response Example ```json { "error": "Failed to retrieve package version." } ``` ``` -------------------------------- ### CloneToUninit API Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.DebugConfig.html Documentation for the `clone_to_uninit` method, which performs copy-assignment from self to a destination. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method `unsafe fn` ### Endpoint N/A (Rust method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (requires nightly Rust) // let mut buffer = [0u8; 10]; // let data_to_clone = [1, 2, 3]; // data_to_clone.clone_to_uninit(buffer.as_mut_ptr()); ``` ### Response #### Success Response (200) N/A (Rust method) #### Response Example N/A (Rust method) ``` -------------------------------- ### Get Current Platform Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/fn.current_platform.html Retrieves the current operating system and architecture of the Zed environment. ```APIDOC ## GET /current_platform ### Description Gets the current operating system and architecture. ### Method GET ### Endpoint /current_platform ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **os** (Os) - The current operating system. - **architecture** (Architecture) - The current architecture. #### Response Example ```json { "os": "linux", "architecture": "x86_64" } ``` ``` -------------------------------- ### LSP Module Overview Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/lsp/index.html This section details the available structs and enums for interacting with Language Servers via LSP. ```APIDOC ## LSP Module Overview This module provides constructs for interacting with language servers over the Language Server Protocol (LSP). ### Structs * **Completion**: Represents an LSP completion. * **Symbol**: Represents an LSP symbol. ### Enums * **CompletionKind**: Defines the kind of an LSP completion. * **InsertTextFormat**: Defines how to interpret the insert text in a completion item. * **SymbolKind**: Defines the kind of an LSP symbol. ``` -------------------------------- ### Get Latest GitHub Release Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/fn.latest_github_release.html Retrieves the latest release information for a specified GitHub repository. ```APIDOC ## GET /latest_github_release ### Description Returns the latest release for the given GitHub repository. ### Method GET ### Endpoint /latest_github_release ### Parameters #### Query Parameters - **repo** (string) - Required - The repository name in the format "owner/repo", for example: "zed-industries/zed". - **options** (GithubReleaseOptions) - Optional - Additional options for fetching the release. (Specific fields for GithubReleaseOptions are not detailed in the provided text). ### Request Example (No explicit request example provided, but would typically involve a GET request with query parameters) ### Response #### Success Response (200) - **release** (GithubRelease) - An object containing details about the latest GitHub release. (Specific fields for GithubRelease are not detailed in the provided text). #### Response Example ```json { "release": { "tag_name": "v1.2.3", "published_at": "2023-10-27T10:00:00Z", "assets": [ { "name": "extension.zip", "url": "https://example.com/asset.zip" } ] } } ``` #### Error Response - **error** (string) - A message describing the error if the release could not be fetched. ``` -------------------------------- ### Initialize HttpRequestBuilder in Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/http_client/struct.HttpRequestBuilder.html Creates a new instance of HttpRequestBuilder. This is the starting point for constructing an HTTP request. ```Rust pub fn new() -> Self ``` -------------------------------- ### Any Trait Implementation Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/enum.Architecture.html Details the 'Any' trait implementation, which provides a way to get the TypeId of a value. ```APIDOC ## GET /any/type_id ### Description Retrieves the TypeId of a given value using the 'Any' trait. ### Method GET ### Endpoint `/any/type_id` ### Parameters #### Query Parameters - **value** (any) - Required - The value for which to get the TypeId. ### Response #### Success Response (200) - **type_id** (TypeId) - The TypeId of the provided value. #### Response Example ```json { "type_id": "some_type_id_string" } ``` ``` -------------------------------- ### Access Project Files and Environment with Worktree (Rust) Source: https://context7.com/mrtomatepng/zed_extension_api/llms.txt Demonstrates how to use the `Worktree` struct to access the project's root path, read files, find binaries on the system's PATH, and retrieve shell environment variables. This is useful for configuring language servers or other project-specific tools. ```rust use zed_extension_api::{Worktree, Result, Command}; fn configure_from_worktree(worktree: &Worktree) -> Result { // Get the worktree root path let root = worktree.root_path(); println!("Project root: {}", root); // Read a configuration file let config = worktree.read_text_file("package.json") .unwrap_or_else(|_| "{}".to_string()); // Find a binary on PATH let node_path = worktree.which("node") .ok_or_else(|| "Node.js not found".to_string())?; // Get shell environment variables let env_vars = worktree.shell_env(); // Build a command with the discovered paths Ok(Command { command: node_path, args: vec![ format!("{}/node_modules/.bin/typescript-language-server", root), "--stdio".to_string(), ], env: env_vars, }) } ``` -------------------------------- ### DebugAdapterBinary Struct Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.DebugAdapterBinary.html Represents the configuration for starting a debug adapter process and a debug session using the DAP protocol. ```APIDOC ## Struct DebugAdapterBinary ### Description The lowest-level representation of a debug session, which specifies: * How to start a debug adapter process * How to start a debug session with it (using DAP protocol) for a given debug scenario. ### Fields #### `command` - **command** (Option) - Optional. The command to execute for the debug adapter. #### `arguments` - **arguments** (Vec) - Required. Arguments to pass to the debug adapter command. #### `envs` - **envs** (Vec<(String, String)>) - Required. Environment variables to set for the debug adapter process. #### `cwd` - **cwd** (Option) - Optional. The current working directory for the debug adapter process. #### `connection` - **connection** (Option) - Optional. If specified, Zed will use TCP transport for communication with the debug adapter. #### `request_args` - **request_args** (StartDebuggingRequestArguments) - Required. Arguments for starting the debugging session. ### Example Request Body ```json { "command": "/path/to/debug/adapter", "arguments": ["--arg1", "--arg2"], "envs": [["VAR_NAME", "VAR_VALUE"]], "cwd": "/path/to/working/directory", "connection": { "host": "127.0.0.1", "port": 12345 }, "request_args": { "type": "node", "request": "launch", "program": "${workspaceFolder}/app.js" } } ``` ### Example Success Response (200) ```json { "status": "Debug session started successfully" } ``` ### Error Handling - **400 Bad Request**: Invalid request body format or missing required fields. - **500 Internal Server Error**: An unexpected error occurred on the server. ``` -------------------------------- ### Process Module Overview Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/process/index.html This module provides functionality for interacting with operating system processes. ```APIDOC ## Module: process ### Description A module for working with processes. ### Structs * **Command**: Represents a command to be executed. * **Output**: Represents the output of a finished process. ``` -------------------------------- ### Generic Blanket Implementations Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.LaunchRequest.html Describes common traits implemented generically for types, such as Any, Borrow, BorrowMut, and CloneToUninit. ```APIDOC ## Generic Type Implementations ### Description This section details common traits that are implemented generically for various types (`T`). These implementations provide fundamental functionalities like type identification, borrowing, and cloning. ### Traits - **Any**: Allows for runtime type identification using `TypeId`. - **Borrow**: Provides immutable borrowing of a value. - **BorrowMut**: Provides mutable borrowing of a value. - **CloneToUninit**: Enables cloning a value into an uninitialized memory location, requiring the type to implement `Clone`. ### Method - `type_id()`: Returns the `TypeId` of the instance. - `borrow()`: Returns an immutable reference to the borrowed value. - `borrow_mut()`: Returns a mutable reference to the borrowed value. - `clone_to_uninit()`: Clones the value into an uninitialized memory location. ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Rust: Get Type ID Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/http_client/enum.HttpMethod.html Retrieves the unique TypeId of a given type. This is useful for runtime type identification and comparisons. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Range Type Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/type.Range.html Defines the Range type used within the Zed Extension API. This type represents a range with a start and end point. ```APIDOC ## Type Alias Range ### Description Represents a range with inclusive start and exclusive end points. ### Type Definition ```rust #[repr(C)] pub struct Range { pub start: u32, pub end: u32, } ``` ### Fields * **start** (u32) - The start of the range (inclusive). * **end** (u32) - The end of the range (exclusive). ### Trait Implementations * **From>** Converts from a standard Rust `Range` to the API's `Range` type. ```rust fn from(value: Range) -> Self; ``` * **From>** Converts from a standard Rust `Range` to the API's `Range` type. ```rust fn from(value: Range) -> Self; ``` ``` -------------------------------- ### Implement Debug Adapter Support with Rust Source: https://context7.com/mrtomatepng/zed_extension_api/llms.txt Shows how to implement Debug Adapter Protocol (DAP) support for extensions. This includes finding debug binaries, converting configurations, and handling requests. It requires implementing the `Extension` trait and its relevant methods like `get_dap_binary`, `dap_request_kind`, and `dap_config_to_scenario`. ```rust use zed_extension_api::{ Extension, DebugAdapterBinary, DebugTaskDefinition, DebugScenario, DebugConfig, DebugRequest, Worktree, Result, StartDebuggingRequestArgumentsRequest, }; use zed_extension_api::serde_json::{json, Value}; struct DebugExtension; impl Extension for DebugExtension { fn new() -> Self { DebugExtension } fn get_dap_binary( &mut self, adapter_name: String, config: DebugTaskDefinition, user_provided_path: Option, worktree: &Worktree, ) -> Result { let binary_path = user_provided_path .or_else(|| worktree.which("lldb-vscode")) .ok_or_else(|| "Debug adapter not found".to_string())?; Ok(DebugAdapterBinary { command: binary_path, args: vec![], envs: vec![], cwd: Some(worktree.root_path()), connection: None, }) } fn dap_request_kind( &mut self, adapter_name: String, config: Value, ) -> Result { // Determine if this is a launch or attach request if config.get("processId").is_some() || config.get("pid").is_some() { Ok(StartDebuggingRequestArgumentsRequest::Attach) } else { Ok(StartDebuggingRequestArgumentsRequest::Launch) } } fn dap_config_to_scenario( &mut self, config: DebugConfig, ) -> Result { Ok(DebugScenario { adapter: "lldb".to_string(), config: json!({ "program": config.program, "args": config.args, "cwd": config.cwd, "env": config.env, }), build: None, tcp_connection: None, }) } } ``` -------------------------------- ### Get Label for Completion (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/trait.Extension.html Generates a displayable label for a given code completion item. This function is associated with a specific language server and returns an Option containing a CodeLabel. ```rust fn label_for_completion(&self, _language_server_id: &LanguageServerId, _completion: Completion) -> Option ``` -------------------------------- ### Get LanguageSettings for a worktree in Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/settings/struct.LanguageSettings.html Implements the for_worktree method for LanguageSettings. This function retrieves the language settings for a given language and worktree, returning a Result. ```rust pub fn for_worktree(language: Option<&str>, worktree: &Worktree) -> Result ``` -------------------------------- ### Get Label for Symbol (Rust) Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/trait.Extension.html Creates a displayable label for a given code symbol. This function is tied to a language server and returns an Option containing a CodeLabel, suitable for UI representation. ```rust fn label_for_symbol(&self, _language_server_id: &LanguageServerId, _symbol: Symbol) -> Option ``` -------------------------------- ### CloneToUninit API Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.TcpArguments.html Documentation for the `clone_to_uninit` method, which performs copy-assignment from self to a destination pointer. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit ### Description Performs copy-assignment from `self` to `dest`. ### Method `unsafe fn` ### Endpoint N/A (Rust method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (requires nightly Rust) // let mut buffer = [0u8; 10]; // let data_to_clone = [1, 2, 3]; // data_to_clone.clone_to_uninit(buffer.as_mut_ptr()); ``` ### Response #### Success Response (200) N/A (Rust method) #### Response Example None ``` -------------------------------- ### Get ContextServerSettings for Project in Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/settings/struct.ContextServerSettings.html A function to retrieve ContextServerSettings for a specific context server ID and project. It returns a Result which may contain the settings or an error. ```rust pub fn for_project(context_server_id: &str, project: &Project) -> Result ``` -------------------------------- ### Redirect to npm_install_package using JavaScript Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/wit/zed/extension/nodejs/fn.npm_install_package.html This snippet uses `location.replace()` to redirect the user to the `npm_install_package` function within the Zed Extension API. It preserves the current query parameters and hash. This is a common client-side navigation technique. ```javascript location.replace("../../../../../zed_extension_api/fn.npm_install_package.html" + location.search + location.hash); ``` -------------------------------- ### CloneToUninit API Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.LanguageServerId.html Provides an unsafe method for cloning data into uninitialized memory. ```APIDOC ## POST /mrtomatepng/zed_extension_api/clone_to_uninit ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method POST ### Endpoint /mrtomatepng/zed_extension_api/clone_to_uninit ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **dest** (*mut u8) - Required - A mutable pointer to the destination memory. ### Request Example ```json { "dest": "*mut u8" } ``` ### Response #### Success Response (200) None #### Response Example ```json { "example": "No response body" } ``` ``` -------------------------------- ### Get Project Worktree IDs in Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.Project.html Retrieves the unique identifiers for all worktrees associated with a Zed project. This method is part of the Project struct and returns a vector of u64. ```rust pub fn worktree_ids(&self) -> Vec ``` -------------------------------- ### CloneToUninit API Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.SlashCommandOutput.html Provides functionality to clone data into an uninitialized memory location. This is a nightly-only experimental API. ```APIDOC ## POST /mrtomatepng/zed_extension_api/clone_to_uninit ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method POST ### Endpoint /mrtomatepng/zed_extension_api/clone_to_uninit ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **dest** (*mut u8) - Required - The destination pointer to copy data into. ### Request Example ```json { "dest": "0x..." } ``` ### Response #### Success Response (200) Indicates successful cloning. No specific data is returned. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### TryFrom and TryInto Conversions Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.SlashCommandOutput.html Documentation for `TryFrom` and `TryInto` traits, enabling fallible type conversions. ```APIDOC ## Fallible Conversion APIs (TryFrom/TryInto) ### Description These APIs provide fallible type conversions. `TryFrom for T` attempts to convert from type `U` to type `T`, returning a `Result`. `TryInto for T` is the inverse, attempting conversion from `T` to `U`. ### Method POST ### Endpoint /mrtomatepng/zed_extension_api/try_convert ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **value** (U) - Required - The value to attempt conversion from. - **target_type** (string) - Required - The target type for conversion (e.g., "T"). ### Request Example ```json { "value": "data_to_convert", "target_type": "TargetType" } ``` ### Response #### Success Response (200) - **converted_value** (T) - The successfully converted value. #### Error Response (400) - **error** (string) - A message describing the conversion error. #### Response Example ```json { "converted_value": "converted_data" } ``` #### Error Response Example ```json { "error": "Conversion failed: invalid input format." } ``` ``` -------------------------------- ### Set HTTP Method for HttpRequestBuilder in Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/http_client/struct.HttpRequestBuilder.html Sets the HTTP method (e.g., GET, POST) for the outgoing request. This method consumes the builder and returns it with the method set. ```Rust pub fn method(self, method: HttpMethod) -> Self ``` -------------------------------- ### Implement Any trait for generic type T Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/http_client/struct.HttpResponseStream.html This blanket implementation allows any type T that is 'static and Sized to implement the Any trait. The type_id method can be called on such types to get their unique TypeId. ```Rust impl Any for T where T: 'static + ?Sized ``` -------------------------------- ### Redirect to Project Struct Page with Query and Hash Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/wit/struct.Project.html This JavaScript code snippet demonstrates how to redirect the current page to the 'Project' struct documentation page. It preserves any existing query parameters and hash fragments from the current URL, ensuring a seamless navigation experience. This is useful for dynamically linking to specific API documentation sections. ```javascript location.replace("../../zed_extension_api/struct.Project.html" + location.search + location.hash); ``` -------------------------------- ### Get Node Binary Path - Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/fn.node_binary_path.html Returns the path to the Node binary used by Zed. This function is part of the zed_extension_api and is useful for extensions that need to interact with Node.js. ```Rust pub fn node_binary_path() -> Result ``` -------------------------------- ### Implement AI Assistant Slash Commands (Rust) Source: https://context7.com/mrtomatepng/zed_extension_api/llms.txt Shows how to integrate custom slash commands into Zed's AI Assistant. This involves implementing `complete_slash_command_argument` for argument suggestions and `run_slash_command` to execute the command's logic, potentially fetching dynamic content or external data. ```rust use zed_extension_api::{ Extension, SlashCommand, SlashCommandOutput, SlashCommandOutputSection, SlashCommandArgumentCompletion, Worktree, Result, }; struct DocsExtension; impl Extension for DocsExtension { fn new() -> Self { DocsExtension } fn complete_slash_command_argument( &self, command: SlashCommand, args: Vec, ) -> Result, String> { if command.name == "docs" { Ok(vec![ SlashCommandArgumentCompletion { label: "rust".to_string(), new_text: "rust".to_string(), run_command: true, }, SlashCommandArgumentCompletion { label: "typescript".to_string(), new_text: "typescript".to_string(), run_command: true, }, ]) } else { Ok(vec![]) } } fn run_slash_command( &self, command: SlashCommand, args: Vec, worktree: Option<&Worktree>, ) -> Result { let topic = args.first().cloned().unwrap_or_default(); let content = match topic.as_str() { "rust" => "# Rust Documentation\n\nRust is a systems programming language...".to_string(), "typescript" => "# TypeScript Documentation\n\nTypeScript is a typed superset of JavaScript...".to_string(), _ => format!("Documentation for '{}' not found.", topic), }; Ok(SlashCommandOutput { sections: vec![SlashCommandOutputSection { range: (0..content.len()).into(), label: format!("Docs: {}", topic), }], text: content, }) } } ``` -------------------------------- ### Command Struct API Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/process/struct.Command.html Documentation for the Command struct, which represents an executable command with its arguments and environment variables. ```APIDOC ## Struct Command ### Description A command that can be executed. ### Fields - **command** (String) - The command to execute. - **args** (Vec) - The arguments to pass to the command. - **env** (Vec<(String, String)>) - The environment variables to set for the command. ### Methods #### new - **Description**: Creates a new Command instance with the specified program. - **Signature**: `pub fn new(program: impl Into) -> Self` #### arg - **Description**: Adds a single argument to the command. - **Signature**: `pub fn arg(self, arg: impl Into) -> Self` #### args - **Description**: Adds multiple arguments to the command. - **Signature**: `pub fn args(self, args: impl IntoIterator>) -> Self` #### env - **Description**: Adds a single environment variable to the command. - **Signature**: `pub fn env(self, key: impl Into, value: impl Into) -> Self` #### envs - **Description**: Adds multiple environment variables to the command. - **Signature**: `pub fn envs(self, envs: impl IntoIterator, impl Into)>) -> Self` #### output - **Description**: Executes the command and returns its output. - **Signature**: `pub async fn output(self) -> Result` ### Request Example ```json { "command": "echo", "args": ["hello", "world"], "env": [["MY_VAR", "my_value"]] } ``` ### Response #### Success Response (200) - **Output** (struct) - Contains stdout, stderr, and exit status of the command. #### Response Example ```json { "stdout": "hello world\n", "stderr": "", "status": { "success": true, "code": 0 } } ``` ``` -------------------------------- ### Get Worktree ID - Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.Worktree.html Retrieves the unique identifier for a Zed worktree. This method takes no arguments and returns a u64 representing the worktree's ID. ```rust impl Worktree { /// Returns the ID of the worktree. pub fn id(&self) -> u64 { // ... implementation details ... } } ``` -------------------------------- ### Make File Executable Source: https://context7.com/mrtomatepng/zed_extension_api/llms.txt Sets execute permissions on a downloaded file, which is crucial for running binary files on Unix-like systems. This function is typically used after downloading a binary using `download_file`. ```rust use zed_extension_api::{download_file, make_file_executable, DownloadedFileType}; fn setup_binary() -> Result<(), String> { // Download the binary download_file( "https://example.com/my-server", "my-server", DownloadedFileType::Uncompressed, )?; // Make it executable make_file_executable("my-server")?; Ok(()) } ``` -------------------------------- ### Rust: Get Owned Type Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/http_client/enum.HttpMethod.html Defines the associated `Owned` type, which represents the owned version of a type. This is commonly used with the `ToOwned` trait for creating owned copies. ```rust type Owned = T; ``` -------------------------------- ### HTTP Client Module Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/http_client/index.html Overview of the HTTP client module, including its structs, enums, and functions. ```APIDOC ## HTTP Client Module ### Description This module provides functionality for making HTTP requests. ### Structs * **HttpRequest**: Represents an HTTP request. * **HttpRequestBuilder**: A builder for creating `HttpRequest` instances. * **HttpResponse**: Represents an HTTP response. * **HttpResponseStream**: Represents a stream of an HTTP response. ### Enums * **HttpMethod**: Defines the possible HTTP methods (e.g., GET, POST). * **RedirectPolicy**: Specifies how to handle HTTP redirects. ### Functions * **fetch**: Performs an HTTP request and returns the complete response. * **fetch_stream**: Performs an HTTP request and returns a response as a stream. ``` -------------------------------- ### CloneToUninit API Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/http_client/struct.HttpResponse.html Provides a method to clone data into an uninitialized memory location. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method `unsafe fn` ### Endpoint N/A (Method within a trait) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **dest** (*mut u8) - Required - A mutable pointer to the destination memory location. ### Request Example ```rust // Example usage (requires nightly Rust) // let mut data = [0u8; 10]; // let source_data = vec![1, 2, 3]; // unsafe { source_data.as_ptr().copy_to_uninit(data.as_mut_ptr(), source_data.len()); } ``` ### Response #### Success Response (200) N/A (This is a method that modifies memory in place) #### Response Example None ``` -------------------------------- ### Get Worktree Root Path - Rust Source: https://github.com/mrtomatepng/zed_extension_api/blob/master/struct.Worktree.html Retrieves the absolute path to the root directory of the Zed worktree. This method takes no arguments and returns a String representing the root path. ```rust impl Worktree { /// Returns the root path of the worktree. pub fn root_path(&self) -> String { // ... implementation details ... } } ```