rust.rs

  1use anyhow::{anyhow, bail, Context, Result};
  2use async_compression::futures::bufread::GzipDecoder;
  3use async_trait::async_trait;
  4use futures::{io::BufReader, StreamExt};
  5use gpui::AsyncAppContext;
  6use http::github::{latest_github_release, GitHubLspBinaryVersion};
  7pub use language::*;
  8use lazy_static::lazy_static;
  9use lsp::LanguageServerBinary;
 10use project::project_settings::ProjectSettings;
 11use regex::Regex;
 12use settings::Settings;
 13use smol::fs::{self, File};
 14use std::{
 15    any::Any,
 16    borrow::Cow,
 17    env::consts,
 18    path::{Path, PathBuf},
 19    sync::Arc,
 20};
 21use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
 22use util::{fs::remove_matching, maybe, ResultExt};
 23
 24pub struct RustLspAdapter;
 25
 26impl RustLspAdapter {
 27    const SERVER_NAME: &'static str = "rust-analyzer";
 28}
 29
 30#[async_trait(?Send)]
 31impl LspAdapter for RustLspAdapter {
 32    fn name(&self) -> LanguageServerName {
 33        LanguageServerName(Self::SERVER_NAME.into())
 34    }
 35
 36    async fn check_if_user_installed(
 37        &self,
 38        _delegate: &dyn LspAdapterDelegate,
 39        cx: &AsyncAppContext,
 40    ) -> Option<LanguageServerBinary> {
 41        let binary = cx
 42            .update(|cx| {
 43                ProjectSettings::get_global(cx)
 44                    .lsp
 45                    .get(Self::SERVER_NAME)
 46                    .and_then(|s| s.binary.clone())
 47            })
 48            .ok()??;
 49
 50        let path = binary.path?;
 51        Some(LanguageServerBinary {
 52            path: path.into(),
 53            arguments: binary
 54                .arguments
 55                .unwrap_or_default()
 56                .iter()
 57                .map(|arg| arg.into())
 58                .collect(),
 59            env: None,
 60        })
 61    }
 62
 63    async fn fetch_latest_server_version(
 64        &self,
 65        delegate: &dyn LspAdapterDelegate,
 66    ) -> Result<Box<dyn 'static + Send + Any>> {
 67        let release = latest_github_release(
 68            "rust-lang/rust-analyzer",
 69            true,
 70            false,
 71            delegate.http_client(),
 72        )
 73        .await?;
 74        let os = match consts::OS {
 75            "macos" => "apple-darwin",
 76            "linux" => "unknown-linux-gnu",
 77            "windows" => "pc-windows-msvc",
 78            other => bail!("Running on unsupported os: {other}"),
 79        };
 80        let asset_name = format!("rust-analyzer-{}-{os}.gz", consts::ARCH);
 81        let asset = release
 82            .assets
 83            .iter()
 84            .find(|asset| asset.name == asset_name)
 85            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
 86        Ok(Box::new(GitHubLspBinaryVersion {
 87            name: release.tag_name,
 88            url: asset.browser_download_url.clone(),
 89        }))
 90    }
 91
 92    async fn fetch_server_binary(
 93        &self,
 94        version: Box<dyn 'static + Send + Any>,
 95        container_dir: PathBuf,
 96        delegate: &dyn LspAdapterDelegate,
 97    ) -> Result<LanguageServerBinary> {
 98        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
 99        let destination_path = container_dir.join(format!("rust-analyzer-{}", version.name));
100
101        if fs::metadata(&destination_path).await.is_err() {
102            let mut response = delegate
103                .http_client()
104                .get(&version.url, Default::default(), true)
105                .await
106                .map_err(|err| anyhow!("error downloading release: {}", err))?;
107            let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
108            let mut file = File::create(&destination_path).await?;
109            futures::io::copy(decompressed_bytes, &mut file).await?;
110            // todo("windows")
111            #[cfg(not(windows))]
112            {
113                fs::set_permissions(
114                    &destination_path,
115                    <fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
116                )
117                .await?;
118            }
119
120            remove_matching(&container_dir, |entry| entry != destination_path).await;
121        }
122
123        Ok(LanguageServerBinary {
124            path: destination_path,
125            env: None,
126            arguments: Default::default(),
127        })
128    }
129
130    async fn cached_server_binary(
131        &self,
132        container_dir: PathBuf,
133        _: &dyn LspAdapterDelegate,
134    ) -> Option<LanguageServerBinary> {
135        get_cached_server_binary(container_dir).await
136    }
137
138    async fn installation_test_binary(
139        &self,
140        container_dir: PathBuf,
141    ) -> Option<LanguageServerBinary> {
142        get_cached_server_binary(container_dir)
143            .await
144            .map(|mut binary| {
145                binary.arguments = vec!["--help".into()];
146                binary
147            })
148    }
149
150    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
151        vec!["rustc".into()]
152    }
153
154    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
155        Some("rust-analyzer/flycheck".into())
156    }
157
158    fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
159        lazy_static! {
160            static ref REGEX: Regex = Regex::new("(?m)`([^`]+)\n`$").unwrap();
161        }
162
163        for diagnostic in &mut params.diagnostics {
164            for message in diagnostic
165                .related_information
166                .iter_mut()
167                .flatten()
168                .map(|info| &mut info.message)
169                .chain([&mut diagnostic.message])
170            {
171                if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
172                    *message = sanitized;
173                }
174            }
175        }
176    }
177
178    async fn label_for_completion(
179        &self,
180        completion: &lsp::CompletionItem,
181        language: &Arc<Language>,
182    ) -> Option<CodeLabel> {
183        match completion.kind {
184            Some(lsp::CompletionItemKind::FIELD) if completion.detail.is_some() => {
185                let detail = completion.detail.as_ref().unwrap();
186                let name = &completion.label;
187                let text = format!("{}: {}", name, detail);
188                let source = Rope::from(format!("struct S {{ {} }}", text).as_str());
189                let runs = language.highlight_text(&source, 11..11 + text.len());
190                return Some(CodeLabel {
191                    text,
192                    runs,
193                    filter_range: 0..name.len(),
194                });
195            }
196            Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE)
197                if completion.detail.is_some()
198                    && completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) =>
199            {
200                let detail = completion.detail.as_ref().unwrap();
201                let name = &completion.label;
202                let text = format!("{}: {}", name, detail);
203                let source = Rope::from(format!("let {} = ();", text).as_str());
204                let runs = language.highlight_text(&source, 4..4 + text.len());
205                return Some(CodeLabel {
206                    text,
207                    runs,
208                    filter_range: 0..name.len(),
209                });
210            }
211            Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD)
212                if completion.detail.is_some() =>
213            {
214                lazy_static! {
215                    static ref REGEX: Regex = Regex::new("\\(…?\\)").unwrap();
216                }
217                let detail = completion.detail.as_ref().unwrap();
218                const FUNCTION_PREFIXES: [&'static str; 2] = ["async fn", "fn"];
219                let prefix = FUNCTION_PREFIXES
220                    .iter()
221                    .find_map(|prefix| detail.strip_prefix(*prefix).map(|suffix| (prefix, suffix)));
222                // fn keyword should be followed by opening parenthesis.
223                if let Some((prefix, suffix)) = prefix {
224                    if suffix.starts_with('(') {
225                        let text = REGEX.replace(&completion.label, suffix).to_string();
226                        let source = Rope::from(format!("{prefix} {} {{}}", text).as_str());
227                        let run_start = prefix.len() + 1;
228                        let runs =
229                            language.highlight_text(&source, run_start..run_start + text.len());
230                        return Some(CodeLabel {
231                            filter_range: 0..completion.label.find('(').unwrap_or(text.len()),
232                            text,
233                            runs,
234                        });
235                    }
236                }
237            }
238            Some(kind) => {
239                let highlight_name = match kind {
240                    lsp::CompletionItemKind::STRUCT
241                    | lsp::CompletionItemKind::INTERFACE
242                    | lsp::CompletionItemKind::ENUM => Some("type"),
243                    lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
244                    lsp::CompletionItemKind::KEYWORD => Some("keyword"),
245                    lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
246                        Some("constant")
247                    }
248                    _ => None,
249                };
250                let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name?)?;
251                let mut label = CodeLabel::plain(completion.label.clone(), None);
252                label.runs.push((
253                    0..label.text.rfind('(').unwrap_or(label.text.len()),
254                    highlight_id,
255                ));
256                return Some(label);
257            }
258            _ => {}
259        }
260        None
261    }
262
263    async fn label_for_symbol(
264        &self,
265        name: &str,
266        kind: lsp::SymbolKind,
267        language: &Arc<Language>,
268    ) -> Option<CodeLabel> {
269        let (text, filter_range, display_range) = match kind {
270            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
271                let text = format!("fn {} () {{}}", name);
272                let filter_range = 3..3 + name.len();
273                let display_range = 0..filter_range.end;
274                (text, filter_range, display_range)
275            }
276            lsp::SymbolKind::STRUCT => {
277                let text = format!("struct {} {{}}", name);
278                let filter_range = 7..7 + name.len();
279                let display_range = 0..filter_range.end;
280                (text, filter_range, display_range)
281            }
282            lsp::SymbolKind::ENUM => {
283                let text = format!("enum {} {{}}", name);
284                let filter_range = 5..5 + name.len();
285                let display_range = 0..filter_range.end;
286                (text, filter_range, display_range)
287            }
288            lsp::SymbolKind::INTERFACE => {
289                let text = format!("trait {} {{}}", name);
290                let filter_range = 6..6 + name.len();
291                let display_range = 0..filter_range.end;
292                (text, filter_range, display_range)
293            }
294            lsp::SymbolKind::CONSTANT => {
295                let text = format!("const {}: () = ();", name);
296                let filter_range = 6..6 + name.len();
297                let display_range = 0..filter_range.end;
298                (text, filter_range, display_range)
299            }
300            lsp::SymbolKind::MODULE => {
301                let text = format!("mod {} {{}}", name);
302                let filter_range = 4..4 + name.len();
303                let display_range = 0..filter_range.end;
304                (text, filter_range, display_range)
305            }
306            lsp::SymbolKind::TYPE_PARAMETER => {
307                let text = format!("type {} {{}}", name);
308                let filter_range = 5..5 + name.len();
309                let display_range = 0..filter_range.end;
310                (text, filter_range, display_range)
311            }
312            _ => return None,
313        };
314
315        Some(CodeLabel {
316            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
317            text: text[display_range].to_string(),
318            filter_range,
319        })
320    }
321}
322
323pub(crate) struct RustContextProvider;
324
325const RUST_PACKAGE_TASK_VARIABLE: VariableName =
326    VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
327
328impl ContextProvider for RustContextProvider {
329    fn build_context(
330        &self,
331        _: &TaskVariables,
332        location: &Location,
333        cx: &mut gpui::AppContext,
334    ) -> Result<TaskVariables> {
335        let local_abs_path = location
336            .buffer
337            .read(cx)
338            .file()
339            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
340        Ok(
341            if let Some(package_name) = local_abs_path
342                .as_deref()
343                .and_then(|local_abs_path| local_abs_path.parent())
344                .and_then(human_readable_package_name)
345            {
346                TaskVariables::from_iter(Some((RUST_PACKAGE_TASK_VARIABLE.clone(), package_name)))
347            } else {
348                TaskVariables::default()
349            },
350        )
351    }
352
353    fn associated_tasks(&self) -> Option<TaskTemplates> {
354        Some(TaskTemplates(vec![
355            TaskTemplate {
356                label: format!(
357                    "cargo check -p {}",
358                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
359                ),
360                command: "cargo".into(),
361                args: vec![
362                    "check".into(),
363                    "-p".into(),
364                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
365                ],
366                ..TaskTemplate::default()
367            },
368            TaskTemplate {
369                label: "cargo check --workspace --all-targets".into(),
370                command: "cargo".into(),
371                args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
372                ..TaskTemplate::default()
373            },
374            TaskTemplate {
375                label: format!(
376                    "cargo test -p {} {} -- --nocapture",
377                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
378                    VariableName::Symbol.template_value(),
379                ),
380                command: "cargo".into(),
381                args: vec![
382                    "test".into(),
383                    "-p".into(),
384                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
385                    VariableName::Symbol.template_value(),
386                    "--".into(),
387                    "--nocapture".into(),
388                ],
389                tags: vec!["rust-test".to_owned()],
390                ..TaskTemplate::default()
391            },
392            TaskTemplate {
393                label: format!(
394                    "cargo test -p {} {}",
395                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
396                    VariableName::Stem.template_value(),
397                ),
398                command: "cargo".into(),
399                args: vec![
400                    "test".into(),
401                    "-p".into(),
402                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
403                    VariableName::Stem.template_value(),
404                ],
405                tags: vec!["rust-mod-test".to_owned()],
406                ..TaskTemplate::default()
407            },
408            TaskTemplate {
409                label: format!(
410                    "cargo test -p {}",
411                    RUST_PACKAGE_TASK_VARIABLE.template_value()
412                ),
413                command: "cargo".into(),
414                args: vec![
415                    "test".into(),
416                    "-p".into(),
417                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
418                ],
419                ..TaskTemplate::default()
420            },
421            TaskTemplate {
422                label: "cargo run".into(),
423                command: "cargo".into(),
424                args: vec!["run".into()],
425                ..TaskTemplate::default()
426            },
427            TaskTemplate {
428                label: "cargo clean".into(),
429                command: "cargo".into(),
430                args: vec!["clean".into()],
431                ..TaskTemplate::default()
432            },
433        ]))
434    }
435}
436
437fn human_readable_package_name(package_directory: &Path) -> Option<String> {
438    let pkgid = String::from_utf8(
439        std::process::Command::new("cargo")
440            .current_dir(package_directory)
441            .arg("pkgid")
442            .output()
443            .log_err()?
444            .stdout,
445    )
446    .ok()?;
447    Some(package_name_from_pkgid(&pkgid)?.to_owned())
448}
449
450// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
451// Output example in the root of Zed project:
452// ```bash
453// ❯ cargo pkgid zed
454// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
455// ```
456// Another variant, if a project has a custom package name or hyphen in the name:
457// ```
458// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
459// ```
460//
461// Extracts the package name from the output according to the spec:
462// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
463fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
464    fn split_off_suffix(input: &str, suffix_start: char) -> &str {
465        match input.rsplit_once(suffix_start) {
466            Some((without_suffix, _)) => without_suffix,
467            None => input,
468        }
469    }
470
471    let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
472    let package_name = match version_suffix.rsplit_once('@') {
473        Some((custom_package_name, _version)) => custom_package_name,
474        None => {
475            let host_and_path = split_off_suffix(version_prefix, '?');
476            let (_, package_name) = host_and_path.rsplit_once('/')?;
477            package_name
478        }
479    };
480    Some(package_name)
481}
482
483async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
484    maybe!(async {
485        let mut last = None;
486        let mut entries = fs::read_dir(&container_dir).await?;
487        while let Some(entry) = entries.next().await {
488            last = Some(entry?.path());
489        }
490
491        anyhow::Ok(LanguageServerBinary {
492            path: last.ok_or_else(|| anyhow!("no cached binary"))?,
493            env: None,
494            arguments: Default::default(),
495        })
496    })
497    .await
498    .log_err()
499}
500
501#[cfg(test)]
502mod tests {
503    use std::num::NonZeroU32;
504
505    use super::*;
506    use crate::language;
507    use gpui::{BorrowAppContext, Context, Hsla, TestAppContext};
508    use language::language_settings::AllLanguageSettings;
509    use settings::SettingsStore;
510    use theme::SyntaxTheme;
511
512    #[gpui::test]
513    async fn test_process_rust_diagnostics() {
514        let mut params = lsp::PublishDiagnosticsParams {
515            uri: lsp::Url::from_file_path("/a").unwrap(),
516            version: None,
517            diagnostics: vec![
518                // no newlines
519                lsp::Diagnostic {
520                    message: "use of moved value `a`".to_string(),
521                    ..Default::default()
522                },
523                // newline at the end of a code span
524                lsp::Diagnostic {
525                    message: "consider importing this struct: `use b::c;\n`".to_string(),
526                    ..Default::default()
527                },
528                // code span starting right after a newline
529                lsp::Diagnostic {
530                    message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
531                        .to_string(),
532                    ..Default::default()
533                },
534            ],
535        };
536        RustLspAdapter.process_diagnostics(&mut params);
537
538        assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
539
540        // remove trailing newline from code span
541        assert_eq!(
542            params.diagnostics[1].message,
543            "consider importing this struct: `use b::c;`"
544        );
545
546        // do not remove newline before the start of code span
547        assert_eq!(
548            params.diagnostics[2].message,
549            "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
550        );
551    }
552
553    #[gpui::test]
554    async fn test_rust_label_for_completion() {
555        let adapter = Arc::new(RustLspAdapter);
556        let language = language("rust", tree_sitter_rust::language());
557        let grammar = language.grammar().unwrap();
558        let theme = SyntaxTheme::new_test([
559            ("type", Hsla::default()),
560            ("keyword", Hsla::default()),
561            ("function", Hsla::default()),
562            ("property", Hsla::default()),
563        ]);
564
565        language.set_theme(&theme);
566
567        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
568        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
569        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
570        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
571
572        assert_eq!(
573            adapter
574                .label_for_completion(
575                    &lsp::CompletionItem {
576                        kind: Some(lsp::CompletionItemKind::FUNCTION),
577                        label: "hello(…)".to_string(),
578                        detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
579                        ..Default::default()
580                    },
581                    &language
582                )
583                .await,
584            Some(CodeLabel {
585                text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
586                filter_range: 0..5,
587                runs: vec![
588                    (0..5, highlight_function),
589                    (7..10, highlight_keyword),
590                    (11..17, highlight_type),
591                    (18..19, highlight_type),
592                    (25..28, highlight_type),
593                    (29..30, highlight_type),
594                ],
595            })
596        );
597        assert_eq!(
598            adapter
599                .label_for_completion(
600                    &lsp::CompletionItem {
601                        kind: Some(lsp::CompletionItemKind::FUNCTION),
602                        label: "hello(…)".to_string(),
603                        detail: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
604                        ..Default::default()
605                    },
606                    &language
607                )
608                .await,
609            Some(CodeLabel {
610                text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
611                filter_range: 0..5,
612                runs: vec![
613                    (0..5, highlight_function),
614                    (7..10, highlight_keyword),
615                    (11..17, highlight_type),
616                    (18..19, highlight_type),
617                    (25..28, highlight_type),
618                    (29..30, highlight_type),
619                ],
620            })
621        );
622        assert_eq!(
623            adapter
624                .label_for_completion(
625                    &lsp::CompletionItem {
626                        kind: Some(lsp::CompletionItemKind::FIELD),
627                        label: "len".to_string(),
628                        detail: Some("usize".to_string()),
629                        ..Default::default()
630                    },
631                    &language
632                )
633                .await,
634            Some(CodeLabel {
635                text: "len: usize".to_string(),
636                filter_range: 0..3,
637                runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
638            })
639        );
640
641        assert_eq!(
642            adapter
643                .label_for_completion(
644                    &lsp::CompletionItem {
645                        kind: Some(lsp::CompletionItemKind::FUNCTION),
646                        label: "hello(…)".to_string(),
647                        detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
648                        ..Default::default()
649                    },
650                    &language
651                )
652                .await,
653            Some(CodeLabel {
654                text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
655                filter_range: 0..5,
656                runs: vec![
657                    (0..5, highlight_function),
658                    (7..10, highlight_keyword),
659                    (11..17, highlight_type),
660                    (18..19, highlight_type),
661                    (25..28, highlight_type),
662                    (29..30, highlight_type),
663                ],
664            })
665        );
666    }
667
668    #[gpui::test]
669    async fn test_rust_label_for_symbol() {
670        let adapter = Arc::new(RustLspAdapter);
671        let language = language("rust", tree_sitter_rust::language());
672        let grammar = language.grammar().unwrap();
673        let theme = SyntaxTheme::new_test([
674            ("type", Hsla::default()),
675            ("keyword", Hsla::default()),
676            ("function", Hsla::default()),
677            ("property", Hsla::default()),
678        ]);
679
680        language.set_theme(&theme);
681
682        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
683        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
684        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
685
686        assert_eq!(
687            adapter
688                .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
689                .await,
690            Some(CodeLabel {
691                text: "fn hello".to_string(),
692                filter_range: 3..8,
693                runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
694            })
695        );
696
697        assert_eq!(
698            adapter
699                .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
700                .await,
701            Some(CodeLabel {
702                text: "type World".to_string(),
703                filter_range: 5..10,
704                runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
705            })
706        );
707    }
708
709    #[gpui::test]
710    async fn test_rust_autoindent(cx: &mut TestAppContext) {
711        // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
712        cx.update(|cx| {
713            let test_settings = SettingsStore::test(cx);
714            cx.set_global(test_settings);
715            language::init(cx);
716            cx.update_global::<SettingsStore, _>(|store, cx| {
717                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
718                    s.defaults.tab_size = NonZeroU32::new(2);
719                });
720            });
721        });
722
723        let language = crate::language("rust", tree_sitter_rust::language());
724
725        cx.new_model(|cx| {
726            let mut buffer = Buffer::local("", cx).with_language(language, cx);
727
728            // indent between braces
729            buffer.set_text("fn a() {}", cx);
730            let ix = buffer.len() - 1;
731            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
732            assert_eq!(buffer.text(), "fn a() {\n  \n}");
733
734            // indent between braces, even after empty lines
735            buffer.set_text("fn a() {\n\n\n}", cx);
736            let ix = buffer.len() - 2;
737            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
738            assert_eq!(buffer.text(), "fn a() {\n\n\n  \n}");
739
740            // indent a line that continues a field expression
741            buffer.set_text("fn a() {\n  \n}", cx);
742            let ix = buffer.len() - 2;
743            buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
744            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n}");
745
746            // indent further lines that continue the field expression, even after empty lines
747            let ix = buffer.len() - 2;
748            buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
749            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n    \n    .d\n}");
750
751            // dedent the line after the field expression
752            let ix = buffer.len() - 2;
753            buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
754            assert_eq!(
755                buffer.text(),
756                "fn a() {\n  b\n    .c\n    \n    .d;\n  e\n}"
757            );
758
759            // indent inside a struct within a call
760            buffer.set_text("const a: B = c(D {});", cx);
761            let ix = buffer.len() - 3;
762            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
763            assert_eq!(buffer.text(), "const a: B = c(D {\n  \n});");
764
765            // indent further inside a nested call
766            let ix = buffer.len() - 4;
767            buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
768            assert_eq!(buffer.text(), "const a: B = c(D {\n  e: f(\n    \n  )\n});");
769
770            // keep that indent after an empty line
771            let ix = buffer.len() - 8;
772            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
773            assert_eq!(
774                buffer.text(),
775                "const a: B = c(D {\n  e: f(\n    \n    \n  )\n});"
776            );
777
778            buffer
779        });
780    }
781
782    #[test]
783    fn test_package_name_from_pkgid() {
784        for (input, expected) in [
785            (
786                "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
787                "zed",
788            ),
789            (
790                "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
791                "my-custom-package",
792            ),
793        ] {
794            assert_eq!(package_name_from_pkgid(input), Some(expected));
795        }
796    }
797}