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