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