rust.rs

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