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