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