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 tags: vec!["rust-test".to_owned()],
393 ..TaskTemplate::default()
394 },
395 TaskTemplate {
396 label: format!(
397 "cargo test -p {}",
398 RUST_PACKAGE_TASK_VARIABLE.template_value()
399 ),
400 command: "cargo".into(),
401 args: vec![
402 "test".into(),
403 "-p".into(),
404 RUST_PACKAGE_TASK_VARIABLE.template_value(),
405 ],
406 ..TaskTemplate::default()
407 },
408 TaskTemplate {
409 label: "cargo run".into(),
410 command: "cargo".into(),
411 args: vec!["run".into()],
412 ..TaskTemplate::default()
413 },
414 TaskTemplate {
415 label: "cargo clean".into(),
416 command: "cargo".into(),
417 args: vec!["clean".into()],
418 ..TaskTemplate::default()
419 },
420 ]))
421 }
422}
423
424fn human_readable_package_name(package_directory: &Path) -> Option<String> {
425 let pkgid = String::from_utf8(
426 std::process::Command::new("cargo")
427 .current_dir(package_directory)
428 .arg("pkgid")
429 .output()
430 .log_err()?
431 .stdout,
432 )
433 .ok()?;
434 Some(package_name_from_pkgid(&pkgid)?.to_owned())
435}
436
437// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
438// Output example in the root of Zed project:
439// ```bash
440// ❯ cargo pkgid zed
441// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
442// ```
443// Another variant, if a project has a custom package name or hyphen in the name:
444// ```
445// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
446// ```
447//
448// Extracts the package name from the output according to the spec:
449// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
450fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
451 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
452 match input.rsplit_once(suffix_start) {
453 Some((without_suffix, _)) => without_suffix,
454 None => input,
455 }
456 }
457
458 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
459 let package_name = match version_suffix.rsplit_once('@') {
460 Some((custom_package_name, _version)) => custom_package_name,
461 None => {
462 let host_and_path = split_off_suffix(version_prefix, '?');
463 let (_, package_name) = host_and_path.rsplit_once('/')?;
464 package_name
465 }
466 };
467 Some(package_name)
468}
469
470async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
471 maybe!(async {
472 let mut last = None;
473 let mut entries = fs::read_dir(&container_dir).await?;
474 while let Some(entry) = entries.next().await {
475 last = Some(entry?.path());
476 }
477
478 anyhow::Ok(LanguageServerBinary {
479 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
480 env: None,
481 arguments: Default::default(),
482 })
483 })
484 .await
485 .log_err()
486}
487
488#[cfg(test)]
489mod tests {
490 use std::num::NonZeroU32;
491
492 use super::*;
493 use crate::language;
494 use gpui::{BorrowAppContext, Context, Hsla, TestAppContext};
495 use language::language_settings::AllLanguageSettings;
496 use settings::SettingsStore;
497 use theme::SyntaxTheme;
498
499 #[gpui::test]
500 async fn test_process_rust_diagnostics() {
501 let mut params = lsp::PublishDiagnosticsParams {
502 uri: lsp::Url::from_file_path("/a").unwrap(),
503 version: None,
504 diagnostics: vec![
505 // no newlines
506 lsp::Diagnostic {
507 message: "use of moved value `a`".to_string(),
508 ..Default::default()
509 },
510 // newline at the end of a code span
511 lsp::Diagnostic {
512 message: "consider importing this struct: `use b::c;\n`".to_string(),
513 ..Default::default()
514 },
515 // code span starting right after a newline
516 lsp::Diagnostic {
517 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
518 .to_string(),
519 ..Default::default()
520 },
521 ],
522 };
523 RustLspAdapter.process_diagnostics(&mut params);
524
525 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
526
527 // remove trailing newline from code span
528 assert_eq!(
529 params.diagnostics[1].message,
530 "consider importing this struct: `use b::c;`"
531 );
532
533 // do not remove newline before the start of code span
534 assert_eq!(
535 params.diagnostics[2].message,
536 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
537 );
538 }
539
540 #[gpui::test]
541 async fn test_rust_label_for_completion() {
542 let adapter = Arc::new(RustLspAdapter);
543 let language = language("rust", tree_sitter_rust::language());
544 let grammar = language.grammar().unwrap();
545 let theme = SyntaxTheme::new_test([
546 ("type", Hsla::default()),
547 ("keyword", Hsla::default()),
548 ("function", Hsla::default()),
549 ("property", Hsla::default()),
550 ]);
551
552 language.set_theme(&theme);
553
554 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
555 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
556 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
557 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
558
559 assert_eq!(
560 adapter
561 .label_for_completion(
562 &lsp::CompletionItem {
563 kind: Some(lsp::CompletionItemKind::FUNCTION),
564 label: "hello(…)".to_string(),
565 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
566 ..Default::default()
567 },
568 &language
569 )
570 .await,
571 Some(CodeLabel {
572 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
573 filter_range: 0..5,
574 runs: vec![
575 (0..5, highlight_function),
576 (7..10, highlight_keyword),
577 (11..17, highlight_type),
578 (18..19, highlight_type),
579 (25..28, highlight_type),
580 (29..30, highlight_type),
581 ],
582 })
583 );
584 assert_eq!(
585 adapter
586 .label_for_completion(
587 &lsp::CompletionItem {
588 kind: Some(lsp::CompletionItemKind::FUNCTION),
589 label: "hello(…)".to_string(),
590 detail: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
591 ..Default::default()
592 },
593 &language
594 )
595 .await,
596 Some(CodeLabel {
597 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
598 filter_range: 0..5,
599 runs: vec![
600 (0..5, highlight_function),
601 (7..10, highlight_keyword),
602 (11..17, highlight_type),
603 (18..19, highlight_type),
604 (25..28, highlight_type),
605 (29..30, highlight_type),
606 ],
607 })
608 );
609 assert_eq!(
610 adapter
611 .label_for_completion(
612 &lsp::CompletionItem {
613 kind: Some(lsp::CompletionItemKind::FIELD),
614 label: "len".to_string(),
615 detail: Some("usize".to_string()),
616 ..Default::default()
617 },
618 &language
619 )
620 .await,
621 Some(CodeLabel {
622 text: "len: usize".to_string(),
623 filter_range: 0..3,
624 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
625 })
626 );
627
628 assert_eq!(
629 adapter
630 .label_for_completion(
631 &lsp::CompletionItem {
632 kind: Some(lsp::CompletionItemKind::FUNCTION),
633 label: "hello(…)".to_string(),
634 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
635 ..Default::default()
636 },
637 &language
638 )
639 .await,
640 Some(CodeLabel {
641 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
642 filter_range: 0..5,
643 runs: vec![
644 (0..5, highlight_function),
645 (7..10, highlight_keyword),
646 (11..17, highlight_type),
647 (18..19, highlight_type),
648 (25..28, highlight_type),
649 (29..30, highlight_type),
650 ],
651 })
652 );
653 }
654
655 #[gpui::test]
656 async fn test_rust_label_for_symbol() {
657 let adapter = Arc::new(RustLspAdapter);
658 let language = language("rust", tree_sitter_rust::language());
659 let grammar = language.grammar().unwrap();
660 let theme = SyntaxTheme::new_test([
661 ("type", Hsla::default()),
662 ("keyword", Hsla::default()),
663 ("function", Hsla::default()),
664 ("property", Hsla::default()),
665 ]);
666
667 language.set_theme(&theme);
668
669 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
670 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
671 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
672
673 assert_eq!(
674 adapter
675 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
676 .await,
677 Some(CodeLabel {
678 text: "fn hello".to_string(),
679 filter_range: 3..8,
680 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
681 })
682 );
683
684 assert_eq!(
685 adapter
686 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
687 .await,
688 Some(CodeLabel {
689 text: "type World".to_string(),
690 filter_range: 5..10,
691 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
692 })
693 );
694 }
695
696 #[gpui::test]
697 async fn test_rust_autoindent(cx: &mut TestAppContext) {
698 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
699 cx.update(|cx| {
700 let test_settings = SettingsStore::test(cx);
701 cx.set_global(test_settings);
702 language::init(cx);
703 cx.update_global::<SettingsStore, _>(|store, cx| {
704 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
705 s.defaults.tab_size = NonZeroU32::new(2);
706 });
707 });
708 });
709
710 let language = crate::language("rust", tree_sitter_rust::language());
711
712 cx.new_model(|cx| {
713 let mut buffer = Buffer::local("", cx).with_language(language, cx);
714
715 // indent between braces
716 buffer.set_text("fn a() {}", cx);
717 let ix = buffer.len() - 1;
718 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
719 assert_eq!(buffer.text(), "fn a() {\n \n}");
720
721 // indent between braces, even after empty lines
722 buffer.set_text("fn a() {\n\n\n}", cx);
723 let ix = buffer.len() - 2;
724 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
725 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
726
727 // indent a line that continues a field expression
728 buffer.set_text("fn a() {\n \n}", cx);
729 let ix = buffer.len() - 2;
730 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
731 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
732
733 // indent further lines that continue the field expression, even after empty lines
734 let ix = buffer.len() - 2;
735 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
736 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
737
738 // dedent the line after the field expression
739 let ix = buffer.len() - 2;
740 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
741 assert_eq!(
742 buffer.text(),
743 "fn a() {\n b\n .c\n \n .d;\n e\n}"
744 );
745
746 // indent inside a struct within a call
747 buffer.set_text("const a: B = c(D {});", cx);
748 let ix = buffer.len() - 3;
749 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
750 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
751
752 // indent further inside a nested call
753 let ix = buffer.len() - 4;
754 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
755 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
756
757 // keep that indent after an empty line
758 let ix = buffer.len() - 8;
759 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
760 assert_eq!(
761 buffer.text(),
762 "const a: B = c(D {\n e: f(\n \n \n )\n});"
763 );
764
765 buffer
766 });
767 }
768
769 #[test]
770 fn test_package_name_from_pkgid() {
771 for (input, expected) in [
772 (
773 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
774 "zed",
775 ),
776 (
777 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
778 "my-custom-package",
779 ),
780 ] {
781 assert_eq!(package_name_from_pkgid(input), Some(expected));
782 }
783 }
784}