gleam.rs

  1mod hexdocs;
  2
  3use std::fs;
  4use zed::lsp::CompletionKind;
  5use zed::{
  6    CodeLabel, CodeLabelSpan, HttpRequest, KeyValueStore, LanguageServerId, SlashCommand,
  7    SlashCommandOutput, SlashCommandOutputSection,
  8};
  9use zed_extension_api::{self as zed, Result};
 10
 11use crate::hexdocs::convert_hexdocs_to_markdown;
 12
 13struct GleamExtension {
 14    cached_binary_path: Option<String>,
 15}
 16
 17impl GleamExtension {
 18    fn language_server_binary_path(
 19        &mut self,
 20        language_server_id: &LanguageServerId,
 21        worktree: &zed::Worktree,
 22    ) -> Result<String> {
 23        if let Some(path) = worktree.which("gleam") {
 24            return Ok(path);
 25        }
 26
 27        if let Some(path) = &self.cached_binary_path {
 28            if fs::metadata(path).map_or(false, |stat| stat.is_file()) {
 29                return Ok(path.clone());
 30            }
 31        }
 32
 33        zed::set_language_server_installation_status(
 34            &language_server_id,
 35            &zed::LanguageServerInstallationStatus::CheckingForUpdate,
 36        );
 37        let release = zed::latest_github_release(
 38            "gleam-lang/gleam",
 39            zed::GithubReleaseOptions {
 40                require_assets: true,
 41                pre_release: false,
 42            },
 43        )?;
 44
 45        let (platform, arch) = zed::current_platform();
 46        let asset_name = format!(
 47            "gleam-{version}-{arch}-{os}.tar.gz",
 48            version = release.version,
 49            arch = match arch {
 50                zed::Architecture::Aarch64 => "aarch64",
 51                zed::Architecture::X86 => "x86",
 52                zed::Architecture::X8664 => "x86_64",
 53            },
 54            os = match platform {
 55                zed::Os::Mac => "apple-darwin",
 56                zed::Os::Linux => "unknown-linux-musl",
 57                zed::Os::Windows => "pc-windows-msvc",
 58            },
 59        );
 60
 61        let asset = release
 62            .assets
 63            .iter()
 64            .find(|asset| asset.name == asset_name)
 65            .ok_or_else(|| format!("no asset found matching {:?}", asset_name))?;
 66
 67        let version_dir = format!("gleam-{}", release.version);
 68        let binary_path = format!("{version_dir}/gleam");
 69
 70        if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
 71            zed::set_language_server_installation_status(
 72                &language_server_id,
 73                &zed::LanguageServerInstallationStatus::Downloading,
 74            );
 75
 76            zed::download_file(
 77                &asset.download_url,
 78                &version_dir,
 79                zed::DownloadedFileType::GzipTar,
 80            )
 81            .map_err(|e| format!("failed to download file: {e}"))?;
 82
 83            let entries =
 84                fs::read_dir(".").map_err(|e| format!("failed to list working directory {e}"))?;
 85            for entry in entries {
 86                let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
 87                if entry.file_name().to_str() != Some(&version_dir) {
 88                    fs::remove_dir_all(&entry.path()).ok();
 89                }
 90            }
 91        }
 92
 93        self.cached_binary_path = Some(binary_path.clone());
 94        Ok(binary_path)
 95    }
 96}
 97
 98impl zed::Extension for GleamExtension {
 99    fn new() -> Self {
100        Self {
101            cached_binary_path: None,
102        }
103    }
104
105    fn language_server_command(
106        &mut self,
107        language_server_id: &LanguageServerId,
108        worktree: &zed::Worktree,
109    ) -> Result<zed::Command> {
110        Ok(zed::Command {
111            command: self.language_server_binary_path(language_server_id, worktree)?,
112            args: vec!["lsp".to_string()],
113            env: Default::default(),
114        })
115    }
116
117    fn label_for_completion(
118        &self,
119        _language_server_id: &LanguageServerId,
120        completion: zed::lsp::Completion,
121    ) -> Option<zed::CodeLabel> {
122        let name = &completion.label;
123        let ty = strip_newlines_from_detail(&completion.detail?);
124        let let_binding = "let a";
125        let colon = ": ";
126        let assignment = " = ";
127        let call = match completion.kind? {
128            CompletionKind::Function | CompletionKind::Constructor => "()",
129            _ => "",
130        };
131        let code = format!("{let_binding}{colon}{ty}{assignment}{name}{call}");
132
133        Some(CodeLabel {
134            spans: vec![
135                CodeLabelSpan::code_range({
136                    let start = let_binding.len() + colon.len() + ty.len() + assignment.len();
137                    start..start + name.len()
138                }),
139                CodeLabelSpan::code_range({
140                    let start = let_binding.len();
141                    start..start + colon.len()
142                }),
143                CodeLabelSpan::code_range({
144                    let start = let_binding.len() + colon.len();
145                    start..start + ty.len()
146                }),
147            ],
148            filter_range: (0..name.len()).into(),
149            code,
150        })
151    }
152
153    fn complete_slash_command_argument(
154        &self,
155        command: SlashCommand,
156        _query: String,
157    ) -> Result<Vec<String>, String> {
158        match command.name.as_str() {
159            "gleam-project" => Ok(vec![
160                "apple".to_string(),
161                "banana".to_string(),
162                "cherry".to_string(),
163            ]),
164            _ => Ok(Vec::new()),
165        }
166    }
167
168    fn run_slash_command(
169        &self,
170        command: SlashCommand,
171        argument: Option<String>,
172        worktree: &zed::Worktree,
173    ) -> Result<SlashCommandOutput, String> {
174        match command.name.as_str() {
175            "gleam-docs" => {
176                let argument = argument.ok_or_else(|| "missing argument".to_string())?;
177
178                let mut components = argument.split('/');
179                let package_name = components
180                    .next()
181                    .ok_or_else(|| "missing package name".to_string())?;
182                let module_path = components.map(ToString::to_string).collect::<Vec<_>>();
183
184                let response = zed::fetch(&HttpRequest {
185                    url: format!(
186                        "https://hexdocs.pm/{package_name}{maybe_path}",
187                        maybe_path = if !module_path.is_empty() {
188                            format!("/{}.html", module_path.join("/"))
189                        } else {
190                            String::new()
191                        }
192                    ),
193                })?;
194
195                let (markdown, _modules) = convert_hexdocs_to_markdown(response.body.as_bytes())?;
196
197                let mut text = String::new();
198                text.push_str(&markdown);
199
200                Ok(SlashCommandOutput {
201                    sections: vec![SlashCommandOutputSection {
202                        range: (0..text.len()).into(),
203                        label: format!("gleam-docs: {package_name} {}", module_path.join("/")),
204                    }],
205                    text,
206                })
207            }
208            "gleam-project" => {
209                let mut text = String::new();
210                text.push_str("You are in a Gleam project.\n");
211
212                if let Some(gleam_toml) = worktree.read_text_file("gleam.toml").ok() {
213                    text.push_str("The `gleam.toml` is as follows:\n");
214                    text.push_str(&gleam_toml);
215                }
216
217                Ok(SlashCommandOutput {
218                    sections: vec![SlashCommandOutputSection {
219                        range: (0..text.len()).into(),
220                        label: "gleam-project".to_string(),
221                    }],
222                    text,
223                })
224            }
225            command => Err(format!("unknown slash command: \"{command}\"")),
226        }
227    }
228
229    fn index_docs(
230        &self,
231        provider: String,
232        package: String,
233        database: &KeyValueStore,
234    ) -> Result<(), String> {
235        match provider.as_str() {
236            "gleam-hexdocs" => hexdocs::index(package, database),
237            _ => Ok(()),
238        }
239    }
240}
241
242zed::register_extension!(GleamExtension);
243
244/// Removes newlines from the completion detail.
245///
246/// The Gleam LSP can return types containing newlines, which causes formatting
247/// issues within the Zed completions menu.
248fn strip_newlines_from_detail(detail: &str) -> String {
249    let without_newlines = detail
250        .replace("->\n  ", "-> ")
251        .replace("\n  ", "")
252        .replace(",\n", "");
253
254    let comma_delimited_parts = without_newlines.split(',');
255    comma_delimited_parts
256        .map(|part| part.trim())
257        .collect::<Vec<_>>()
258        .join(", ")
259}
260
261#[cfg(test)]
262mod tests {
263    use crate::strip_newlines_from_detail;
264
265    #[test]
266    fn test_strip_newlines_from_detail() {
267        let detail = "fn(\n  Selector(a),\n  b,\n  fn(Dynamic, Dynamic, Dynamic, Dynamic, Dynamic, Dynamic, Dynamic) -> a,\n) -> Selector(a)";
268        let expected = "fn(Selector(a), b, fn(Dynamic, Dynamic, Dynamic, Dynamic, Dynamic, Dynamic, Dynamic) -> a) -> Selector(a)";
269        assert_eq!(strip_newlines_from_detail(detail), expected);
270
271        let detail = "fn(Selector(a), b, fn(Dynamic, Dynamic, Dynamic, Dynamic, Dynamic, Dynamic) -> a) ->\n  Selector(a)";
272        let expected = "fn(Selector(a), b, fn(Dynamic, Dynamic, Dynamic, Dynamic, Dynamic, Dynamic) -> a) -> Selector(a)";
273        assert_eq!(strip_newlines_from_detail(detail), expected);
274
275        let detail = "fn(\n  Method,\n  List(#(String, String)),\n  a,\n  Scheme,\n  String,\n  Option(Int),\n  String,\n  Option(String),\n) -> Request(a)";
276        let expected = "fn(Method, List(#(String, String)), a, Scheme, String, Option(Int), String, Option(String)) -> Request(a)";
277        assert_eq!(strip_newlines_from_detail(&detail), expected);
278    }
279}