]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/config.rs
Merge #10648
[rust.git] / crates / rust-analyzer / src / config.rs
1 //! Config used by the language server.
2 //!
3 //! We currently get this config from `initialize` LSP request, which is not the
4 //! best way to do it, but was the simplest thing we could implement.
5 //!
6 //! Of particular interest is the `feature_flags` hash map: while other fields
7 //! configure the server itself, feature flags are passed into analysis, and
8 //! tweak things like automatic insertion of `()` in completions.
9
10 use std::{ffi::OsString, iter, path::PathBuf};
11
12 use flycheck::FlycheckConfig;
13 use ide::{
14     AssistConfig, CompletionConfig, DiagnosticsConfig, HighlightRelatedConfig, HoverConfig,
15     HoverDocFormat, InlayHintsConfig, JoinLinesConfig, Snippet, SnippetScope,
16 };
17 use ide_db::helpers::{
18     insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
19     SnippetCap,
20 };
21 use lsp_types::{ClientCapabilities, MarkupKind};
22 use project_model::{
23     CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest, RustcSource, UnsetTestCrates,
24 };
25 use rustc_hash::{FxHashMap, FxHashSet};
26 use serde::{de::DeserializeOwned, Deserialize};
27 use vfs::AbsPathBuf;
28
29 use crate::{
30     caps::completion_item_edit_resolve,
31     diagnostics::DiagnosticsMapConfig,
32     line_index::OffsetEncoding,
33     lsp_ext::supports_utf8,
34     lsp_ext::WorkspaceSymbolSearchScope,
35     lsp_ext::{self, WorkspaceSymbolSearchKind},
36 };
37
38 // Defines the server-side configuration of the rust-analyzer. We generate
39 // *parts* of VS Code's `package.json` config from this.
40 //
41 // However, editor specific config, which the server doesn't know about, should
42 // be specified directly in `package.json`.
43 //
44 // To deprecate an option by replacing it with another name use `new_name | `old_name` so that we keep
45 // parsing the old name.
46 config_data! {
47     struct ConfigData {
48         /// How imports should be grouped into use statements.
49         assist_importGranularity |
50         assist_importMergeBehavior |
51         assist_importMergeBehaviour: ImportGranularityDef  = "\"crate\"",
52         /// Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file.
53         assist_importEnforceGranularity: bool              = "false",
54         /// The path structure for newly inserted paths to use.
55         assist_importPrefix: ImportPrefixDef               = "\"plain\"",
56         /// Group inserted imports by the https://rust-analyzer.github.io/manual.html#auto-import[following order]. Groups are separated by newlines.
57         assist_importGroup: bool                           = "true",
58         /// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.
59         assist_allowMergingIntoGlobImports: bool           = "true",
60
61         /// Show function name and docs in parameter hints.
62         callInfo_full: bool                                = "true",
63
64         /// Automatically refresh project info via `cargo metadata` on
65         /// `Cargo.toml` changes.
66         cargo_autoreload: bool           = "true",
67         /// Activate all available features (`--all-features`).
68         cargo_allFeatures: bool          = "false",
69         /// Unsets `#[cfg(test)]` for the specified crates.
70         cargo_unsetTest: Vec<String>   = "[\"core\"]",
71         /// List of features to activate.
72         cargo_features: Vec<String>      = "[]",
73         /// Run build scripts (`build.rs`) for more precise code analysis.
74         cargo_runBuildScripts |
75         cargo_loadOutDirsFromCheck: bool = "true",
76         /// Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to
77         /// avoid compiling unnecessary things.
78         cargo_useRustcWrapperForBuildScripts: bool = "true",
79         /// Do not activate the `default` feature.
80         cargo_noDefaultFeatures: bool    = "false",
81         /// Compilation target (target triple).
82         cargo_target: Option<String>     = "null",
83         /// Internal config for debugging, disables loading of sysroot crates.
84         cargo_noSysroot: bool            = "false",
85
86         /// Run specified `cargo check` command for diagnostics on save.
87         checkOnSave_enable: bool                         = "true",
88         /// Check with all features (`--all-features`).
89         /// Defaults to `#rust-analyzer.cargo.allFeatures#`.
90         checkOnSave_allFeatures: Option<bool>            = "null",
91         /// Check all targets and tests (`--all-targets`).
92         checkOnSave_allTargets: bool                     = "true",
93         /// Cargo command to use for `cargo check`.
94         checkOnSave_command: String                      = "\"check\"",
95         /// Do not activate the `default` feature.
96         checkOnSave_noDefaultFeatures: Option<bool>      = "null",
97         /// Check for a specific target. Defaults to
98         /// `#rust-analyzer.cargo.target#`.
99         checkOnSave_target: Option<String>               = "null",
100         /// Extra arguments for `cargo check`.
101         checkOnSave_extraArgs: Vec<String>               = "[]",
102         /// List of features to activate. Defaults to
103         /// `#rust-analyzer.cargo.features#`.
104         checkOnSave_features: Option<Vec<String>>        = "null",
105         /// Advanced option, fully override the command rust-analyzer uses for
106         /// checking. The command should include `--message-format=json` or
107         /// similar option.
108         checkOnSave_overrideCommand: Option<Vec<String>> = "null",
109
110         /// Whether to add argument snippets when completing functions.
111         /// Only applies when `#rust-analyzer.completion.addCallParenthesis#` is set.
112         completion_addCallArgumentSnippets: bool = "true",
113         /// Whether to add parenthesis when completing functions.
114         completion_addCallParenthesis: bool      = "true",
115         /// Custom completion snippets.
116         completion_snippets: FxHashMap<String, SnippetDef> = "{}",
117         /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
118         completion_postfix_enable: bool          = "true",
119         /// Toggles the additional completions that automatically add imports when completed.
120         /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
121         completion_autoimport_enable: bool       = "true",
122         /// Toggles the additional completions that automatically show method calls and field accesses
123         /// with `self` prefixed to them when inside a method.
124         completion_autoself_enable: bool       = "true",
125
126         /// Whether to show native rust-analyzer diagnostics.
127         diagnostics_enable: bool                = "true",
128         /// Whether to show experimental rust-analyzer diagnostics that might
129         /// have more false positives than usual.
130         diagnostics_enableExperimental: bool    = "true",
131         /// List of rust-analyzer diagnostics to disable.
132         diagnostics_disabled: FxHashSet<String> = "[]",
133         /// Map of prefixes to be substituted when parsing diagnostic file paths.
134         /// This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.
135         diagnostics_remapPrefix: FxHashMap<String, String> = "{}",
136         /// List of warnings that should be displayed with hint severity.
137         ///
138         /// The warnings will be indicated by faded text or three dots in code
139         /// and will not show up in the `Problems Panel`.
140         diagnostics_warningsAsHint: Vec<String> = "[]",
141         /// List of warnings that should be displayed with info severity.
142         ///
143         /// The warnings will be indicated by a blue squiggly underline in code
144         /// and a blue icon in the `Problems Panel`.
145         diagnostics_warningsAsInfo: Vec<String> = "[]",
146
147         /// Expand attribute macros.
148         experimental_procAttrMacros: bool = "true",
149
150         /// Controls file watching implementation.
151         files_watcher: String = "\"client\"",
152         /// These directories will be ignored by rust-analyzer. They are
153         /// relative to the workspace root, and globs are not supported. You may
154         /// also need to add the folders to Code's `files.watcherExclude`.
155         files_excludeDirs: Vec<PathBuf> = "[]",
156
157         /// Enables highlighting of related references while hovering your mouse above any identifier.
158         highlightRelated_references: bool = "true",
159         /// Enables highlighting of all exit points while hovering your mouse above any `return`, `?`, or return type arrow (`->`).
160         highlightRelated_exitPoints: bool = "true",
161         /// Enables highlighting of related references while hovering your mouse `break`, `loop`, `while`, or `for` keywords.
162         highlightRelated_breakPoints: bool = "true",
163         /// Enables highlighting of all break points for a loop or block context while hovering your mouse above any `async` or `await` keywords.
164         highlightRelated_yieldPoints: bool = "true",
165
166         /// Use semantic tokens for strings.
167         ///
168         /// In some editors (e.g. vscode) semantic tokens override other highlighting grammars.
169         /// By disabling semantic tokens for strings, other grammars can be used to highlight
170         /// their contents.
171         highlighting_strings: bool = "true",
172
173         /// Whether to show documentation on hover.
174         hover_documentation: bool       = "true",
175         /// Use markdown syntax for links in hover.
176         hover_linksInHover |
177         hoverActions_linksInHover: bool = "true",
178
179         /// Whether to show `Debug` action. Only applies when
180         /// `#rust-analyzer.hoverActions.enable#` is set.
181         hoverActions_debug: bool           = "true",
182         /// Whether to show HoverActions in Rust files.
183         hoverActions_enable: bool          = "true",
184         /// Whether to show `Go to Type Definition` action. Only applies when
185         /// `#rust-analyzer.hoverActions.enable#` is set.
186         hoverActions_gotoTypeDef: bool     = "true",
187         /// Whether to show `Implementations` action. Only applies when
188         /// `#rust-analyzer.hoverActions.enable#` is set.
189         hoverActions_implementations: bool = "true",
190         /// Whether to show `References` action. Only applies when
191         /// `#rust-analyzer.hoverActions.enable#` is set.
192         hoverActions_references: bool      = "false",
193         /// Whether to show `Run` action. Only applies when
194         /// `#rust-analyzer.hoverActions.enable#` is set.
195         hoverActions_run: bool             = "true",
196
197         /// Whether to show inlay type hints for method chains.
198         inlayHints_chainingHints: bool      = "true",
199         /// Maximum length for inlay hints. Set to null to have an unlimited length.
200         inlayHints_maxLength: Option<usize> = "25",
201         /// Whether to show function parameter name inlay hints at the call
202         /// site.
203         inlayHints_parameterHints: bool     = "true",
204         /// Whether to show inlay type hints for variables.
205         inlayHints_typeHints: bool          = "true",
206
207         /// Join lines inserts else between consecutive ifs.
208         joinLines_joinElseIf: bool = "true",
209         /// Join lines removes trailing commas.
210         joinLines_removeTrailingComma: bool = "true",
211         /// Join lines unwraps trivial blocks.
212         joinLines_unwrapTrivialBlock: bool = "true",
213         /// Join lines merges consecutive declaration and initialization of an assignment.
214         joinLines_joinAssignments: bool = "true",
215
216         /// Whether to show `Debug` lens. Only applies when
217         /// `#rust-analyzer.lens.enable#` is set.
218         lens_debug: bool            = "true",
219         /// Whether to show CodeLens in Rust files.
220         lens_enable: bool           = "true",
221         /// Whether to show `Implementations` lens. Only applies when
222         /// `#rust-analyzer.lens.enable#` is set.
223         lens_implementations: bool  = "true",
224         /// Whether to show `Run` lens. Only applies when
225         /// `#rust-analyzer.lens.enable#` is set.
226         lens_run: bool              = "true",
227         /// Whether to show `Method References` lens. Only applies when
228         /// `#rust-analyzer.lens.enable#` is set.
229         lens_methodReferences: bool = "false",
230         /// Whether to show `References` lens for Struct, Enum, Union and Trait.
231         /// Only applies when `#rust-analyzer.lens.enable#` is set.
232         lens_references: bool = "false",
233         /// Whether to show `References` lens for Enum Variants.
234         /// Only applies when `#rust-analyzer.lens.enable#` is set.
235         lens_enumVariantReferences: bool = "false",
236         /// Internal config: use custom client-side commands even when the
237         /// client doesn't set the corresponding capability.
238         lens_forceCustomCommands: bool = "true",
239
240         /// Disable project auto-discovery in favor of explicitly specified set
241         /// of projects.
242         ///
243         /// Elements must be paths pointing to `Cargo.toml`,
244         /// `rust-project.json`, or JSON objects in `rust-project.json` format.
245         linkedProjects: Vec<ManifestOrProjectJson> = "[]",
246
247         /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
248         lruCapacity: Option<usize>                 = "null",
249
250         /// Whether to show `can't find Cargo.toml` error message.
251         notifications_cargoTomlNotFound: bool      = "true",
252
253         /// Enable support for procedural macros, implies `#rust-analyzer.cargo.runBuildScripts#`.
254         procMacro_enable: bool                     = "true",
255         /// Internal config, path to proc-macro server executable (typically,
256         /// this is rust-analyzer itself, but we override this in tests).
257         procMacro_server: Option<PathBuf>          = "null",
258
259         /// Command to be executed instead of 'cargo' for runnables.
260         runnables_overrideCargo: Option<String> = "null",
261         /// Additional arguments to be passed to cargo for runnables such as
262         /// tests or binaries. For example, it may be `--release`.
263         runnables_cargoExtraArgs: Vec<String>   = "[]",
264
265         /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
266         /// projects, or "discover" to try to automatically find it if the `rustc-dev` component
267         /// is installed.
268         ///
269         /// Any project which uses rust-analyzer with the rustcPrivate
270         /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
271         ///
272         /// This option does not take effect until rust-analyzer is restarted.
273         rustcSource: Option<String> = "null",
274
275         /// Additional arguments to `rustfmt`.
276         rustfmt_extraArgs: Vec<String>               = "[]",
277         /// Advanced option, fully override the command rust-analyzer uses for
278         /// formatting.
279         rustfmt_overrideCommand: Option<Vec<String>> = "null",
280         /// Enables the use of rustfmt's unstable range formatting command for the
281         /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
282         /// available on a nightly build.
283         rustfmt_enableRangeFormatting: bool = "false",
284
285         /// Workspace symbol search scope.
286         workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = "\"workspace\"",
287         /// Workspace symbol search kind.
288         workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = "\"only_types\"",
289     }
290 }
291
292 impl Default for ConfigData {
293     fn default() -> Self {
294         ConfigData::from_json(serde_json::Value::Null)
295     }
296 }
297
298 #[derive(Debug, Clone)]
299 pub struct Config {
300     pub caps: lsp_types::ClientCapabilities,
301     data: ConfigData,
302     detached_files: Vec<AbsPathBuf>,
303     pub discovered_projects: Option<Vec<ProjectManifest>>,
304     pub root_path: AbsPathBuf,
305     snippets: Vec<Snippet>,
306 }
307
308 #[derive(Debug, Clone, Eq, PartialEq)]
309 pub enum LinkedProject {
310     ProjectManifest(ProjectManifest),
311     InlineJsonProject(ProjectJson),
312 }
313
314 impl From<ProjectManifest> for LinkedProject {
315     fn from(v: ProjectManifest) -> Self {
316         LinkedProject::ProjectManifest(v)
317     }
318 }
319
320 impl From<ProjectJson> for LinkedProject {
321     fn from(v: ProjectJson) -> Self {
322         LinkedProject::InlineJsonProject(v)
323     }
324 }
325
326 #[derive(Clone, Debug, PartialEq, Eq)]
327 pub struct LensConfig {
328     pub run: bool,
329     pub debug: bool,
330     pub implementations: bool,
331     pub method_refs: bool,
332     pub refs: bool, // for Struct, Enum, Union and Trait
333     pub enum_variant_refs: bool,
334 }
335
336 impl LensConfig {
337     pub fn any(&self) -> bool {
338         self.implementations || self.runnable() || self.references()
339     }
340
341     pub fn none(&self) -> bool {
342         !self.any()
343     }
344
345     pub fn runnable(&self) -> bool {
346         self.run || self.debug
347     }
348
349     pub fn references(&self) -> bool {
350         self.method_refs || self.refs || self.enum_variant_refs
351     }
352 }
353
354 #[derive(Clone, Debug, PartialEq, Eq)]
355 pub struct HoverActionsConfig {
356     pub implementations: bool,
357     pub references: bool,
358     pub run: bool,
359     pub debug: bool,
360     pub goto_type_def: bool,
361 }
362
363 impl HoverActionsConfig {
364     pub const NO_ACTIONS: Self = Self {
365         implementations: false,
366         references: false,
367         run: false,
368         debug: false,
369         goto_type_def: false,
370     };
371
372     pub fn any(&self) -> bool {
373         self.implementations || self.references || self.runnable() || self.goto_type_def
374     }
375
376     pub fn none(&self) -> bool {
377         !self.any()
378     }
379
380     pub fn runnable(&self) -> bool {
381         self.run || self.debug
382     }
383 }
384
385 #[derive(Debug, Clone)]
386 pub struct FilesConfig {
387     pub watcher: FilesWatcher,
388     pub exclude: Vec<AbsPathBuf>,
389 }
390
391 #[derive(Debug, Clone)]
392 pub enum FilesWatcher {
393     Client,
394     Notify,
395 }
396
397 #[derive(Debug, Clone)]
398 pub struct NotificationsConfig {
399     pub cargo_toml_not_found: bool,
400 }
401
402 #[derive(Debug, Clone)]
403 pub enum RustfmtConfig {
404     Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
405     CustomCommand { command: String, args: Vec<String> },
406 }
407
408 /// Configuration for runnable items, such as `main` function or tests.
409 #[derive(Debug, Clone)]
410 pub struct RunnablesConfig {
411     /// Custom command to be executed instead of `cargo` for runnables.
412     pub override_cargo: Option<String>,
413     /// Additional arguments for the `cargo`, e.g. `--release`.
414     pub cargo_extra_args: Vec<String>,
415 }
416
417 /// Configuration for workspace symbol search requests.
418 #[derive(Debug, Clone)]
419 pub struct WorkspaceSymbolConfig {
420     /// In what scope should the symbol be searched in.
421     pub search_scope: WorkspaceSymbolSearchScope,
422     /// What kind of symbol is being search for.
423     pub search_kind: WorkspaceSymbolSearchKind,
424 }
425
426 pub struct ClientCommandsConfig {
427     pub run_single: bool,
428     pub debug_single: bool,
429     pub show_reference: bool,
430     pub goto_location: bool,
431     pub trigger_parameter_hints: bool,
432 }
433
434 impl Config {
435     pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
436         Config {
437             caps,
438             data: ConfigData::default(),
439             detached_files: Vec::new(),
440             discovered_projects: None,
441             root_path,
442             snippets: Default::default(),
443         }
444     }
445     pub fn update(&mut self, mut json: serde_json::Value) {
446         tracing::info!("updating config from JSON: {:#}", json);
447         if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
448             return;
449         }
450         self.detached_files = get_field::<Vec<PathBuf>>(&mut json, "detachedFiles", None, "[]")
451             .into_iter()
452             .map(AbsPathBuf::assert)
453             .collect();
454         self.data = ConfigData::from_json(json);
455         self.snippets.clear();
456         for (name, def) in self.data.completion_snippets.iter() {
457             if def.prefix.is_empty() && def.postfix.is_empty() {
458                 continue;
459             }
460             let scope = match def.scope {
461                 SnippetScopeDef::Expr => SnippetScope::Expr,
462                 SnippetScopeDef::Type => SnippetScope::Type,
463                 SnippetScopeDef::Item => SnippetScope::Item,
464             };
465             match Snippet::new(
466                 &def.prefix,
467                 &def.postfix,
468                 &def.body,
469                 def.description.as_ref().unwrap_or(name),
470                 &def.requires,
471                 scope,
472             ) {
473                 Some(snippet) => self.snippets.push(snippet),
474                 None => tracing::info!("Invalid snippet {}", name),
475             }
476         }
477     }
478
479     pub fn json_schema() -> serde_json::Value {
480         ConfigData::json_schema()
481     }
482 }
483
484 macro_rules! try_ {
485     ($expr:expr) => {
486         || -> _ { Some($expr) }()
487     };
488 }
489 macro_rules! try_or {
490     ($expr:expr, $or:expr) => {
491         try_!($expr).unwrap_or($or)
492     };
493 }
494
495 impl Config {
496     pub fn linked_projects(&self) -> Vec<LinkedProject> {
497         if self.data.linkedProjects.is_empty() {
498             self.discovered_projects
499                 .as_ref()
500                 .into_iter()
501                 .flatten()
502                 .cloned()
503                 .map(LinkedProject::from)
504                 .collect()
505         } else {
506             self.data
507                 .linkedProjects
508                 .iter()
509                 .filter_map(|linked_project| {
510                     let res = match linked_project {
511                         ManifestOrProjectJson::Manifest(it) => {
512                             let path = self.root_path.join(it);
513                             ProjectManifest::from_manifest_file(path)
514                                 .map_err(|e| {
515                                     tracing::error!("failed to load linked project: {}", e)
516                                 })
517                                 .ok()?
518                                 .into()
519                         }
520                         ManifestOrProjectJson::ProjectJson(it) => {
521                             ProjectJson::new(&self.root_path, it.clone()).into()
522                         }
523                     };
524                     Some(res)
525                 })
526                 .collect()
527         }
528     }
529
530     pub fn detached_files(&self) -> &[AbsPathBuf] {
531         &self.detached_files
532     }
533
534     pub fn did_save_text_document_dynamic_registration(&self) -> bool {
535         let caps =
536             try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
537         caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
538     }
539     pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
540         try_or!(
541             self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
542             false
543         )
544     }
545
546     pub fn location_link(&self) -> bool {
547         try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
548     }
549     pub fn line_folding_only(&self) -> bool {
550         try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
551     }
552     pub fn hierarchical_symbols(&self) -> bool {
553         try_or!(
554             self.caps
555                 .text_document
556                 .as_ref()?
557                 .document_symbol
558                 .as_ref()?
559                 .hierarchical_document_symbol_support?,
560             false
561         )
562     }
563     pub fn code_action_literals(&self) -> bool {
564         try_!(self
565             .caps
566             .text_document
567             .as_ref()?
568             .code_action
569             .as_ref()?
570             .code_action_literal_support
571             .as_ref()?)
572         .is_some()
573     }
574     pub fn work_done_progress(&self) -> bool {
575         try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
576     }
577     pub fn will_rename(&self) -> bool {
578         try_or!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?, false)
579     }
580     pub fn change_annotation_support(&self) -> bool {
581         try_!(self
582             .caps
583             .workspace
584             .as_ref()?
585             .workspace_edit
586             .as_ref()?
587             .change_annotation_support
588             .as_ref()?)
589         .is_some()
590     }
591     pub fn code_action_resolve(&self) -> bool {
592         try_or!(
593             self.caps
594                 .text_document
595                 .as_ref()?
596                 .code_action
597                 .as_ref()?
598                 .resolve_support
599                 .as_ref()?
600                 .properties
601                 .as_slice(),
602             &[]
603         )
604         .iter()
605         .any(|it| it == "edit")
606     }
607     pub fn signature_help_label_offsets(&self) -> bool {
608         try_or!(
609             self.caps
610                 .text_document
611                 .as_ref()?
612                 .signature_help
613                 .as_ref()?
614                 .signature_information
615                 .as_ref()?
616                 .parameter_information
617                 .as_ref()?
618                 .label_offset_support?,
619             false
620         )
621     }
622     pub fn offset_encoding(&self) -> OffsetEncoding {
623         if supports_utf8(&self.caps) {
624             OffsetEncoding::Utf8
625         } else {
626             OffsetEncoding::Utf16
627         }
628     }
629
630     fn experimental(&self, index: &'static str) -> bool {
631         try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
632     }
633     pub fn code_action_group(&self) -> bool {
634         self.experimental("codeActionGroup")
635     }
636     pub fn server_status_notification(&self) -> bool {
637         self.experimental("serverStatusNotification")
638     }
639
640     pub fn publish_diagnostics(&self) -> bool {
641         self.data.diagnostics_enable
642     }
643     pub fn diagnostics(&self) -> DiagnosticsConfig {
644         DiagnosticsConfig {
645             disable_experimental: !self.data.diagnostics_enableExperimental,
646             disabled: self.data.diagnostics_disabled.clone(),
647         }
648     }
649     pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
650         DiagnosticsMapConfig {
651             remap_prefix: self.data.diagnostics_remapPrefix.clone(),
652             warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
653             warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
654         }
655     }
656     pub fn lru_capacity(&self) -> Option<usize> {
657         self.data.lruCapacity
658     }
659     pub fn proc_macro_srv(&self) -> Option<(AbsPathBuf, Vec<OsString>)> {
660         if !self.data.procMacro_enable {
661             return None;
662         }
663         let path = match &self.data.procMacro_server {
664             Some(it) => self.root_path.join(it),
665             None => AbsPathBuf::assert(std::env::current_exe().ok()?),
666         };
667         Some((path, vec!["proc-macro".into()]))
668     }
669     pub fn expand_proc_attr_macros(&self) -> bool {
670         self.data.experimental_procAttrMacros
671     }
672     pub fn files(&self) -> FilesConfig {
673         FilesConfig {
674             watcher: match self.data.files_watcher.as_str() {
675                 "notify" => FilesWatcher::Notify,
676                 "client" | _ => FilesWatcher::Client,
677             },
678             exclude: self.data.files_excludeDirs.iter().map(|it| self.root_path.join(it)).collect(),
679         }
680     }
681     pub fn notifications(&self) -> NotificationsConfig {
682         NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
683     }
684     pub fn cargo_autoreload(&self) -> bool {
685         self.data.cargo_autoreload
686     }
687     pub fn run_build_scripts(&self) -> bool {
688         self.data.cargo_runBuildScripts || self.data.procMacro_enable
689     }
690     pub fn cargo(&self) -> CargoConfig {
691         let rustc_source = self.data.rustcSource.as_ref().map(|rustc_src| {
692             if rustc_src == "discover" {
693                 RustcSource::Discover
694             } else {
695                 RustcSource::Path(self.root_path.join(rustc_src))
696             }
697         });
698
699         CargoConfig {
700             no_default_features: self.data.cargo_noDefaultFeatures,
701             all_features: self.data.cargo_allFeatures,
702             features: self.data.cargo_features.clone(),
703             target: self.data.cargo_target.clone(),
704             no_sysroot: self.data.cargo_noSysroot,
705             rustc_source,
706             unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()),
707             wrap_rustc_in_build_scripts: self.data.cargo_useRustcWrapperForBuildScripts,
708         }
709     }
710
711     pub fn rustfmt(&self) -> RustfmtConfig {
712         match &self.data.rustfmt_overrideCommand {
713             Some(args) if !args.is_empty() => {
714                 let mut args = args.clone();
715                 let command = args.remove(0);
716                 RustfmtConfig::CustomCommand { command, args }
717             }
718             Some(_) | None => RustfmtConfig::Rustfmt {
719                 extra_args: self.data.rustfmt_extraArgs.clone(),
720                 enable_range_formatting: self.data.rustfmt_enableRangeFormatting,
721             },
722         }
723     }
724     pub fn flycheck(&self) -> Option<FlycheckConfig> {
725         if !self.data.checkOnSave_enable {
726             return None;
727         }
728         let flycheck_config = match &self.data.checkOnSave_overrideCommand {
729             Some(args) if !args.is_empty() => {
730                 let mut args = args.clone();
731                 let command = args.remove(0);
732                 FlycheckConfig::CustomCommand { command, args }
733             }
734             Some(_) | None => FlycheckConfig::CargoCommand {
735                 command: self.data.checkOnSave_command.clone(),
736                 target_triple: self
737                     .data
738                     .checkOnSave_target
739                     .clone()
740                     .or_else(|| self.data.cargo_target.clone()),
741                 all_targets: self.data.checkOnSave_allTargets,
742                 no_default_features: self
743                     .data
744                     .checkOnSave_noDefaultFeatures
745                     .unwrap_or(self.data.cargo_noDefaultFeatures),
746                 all_features: self
747                     .data
748                     .checkOnSave_allFeatures
749                     .unwrap_or(self.data.cargo_allFeatures),
750                 features: self
751                     .data
752                     .checkOnSave_features
753                     .clone()
754                     .unwrap_or_else(|| self.data.cargo_features.clone()),
755                 extra_args: self.data.checkOnSave_extraArgs.clone(),
756             },
757         };
758         Some(flycheck_config)
759     }
760     pub fn runnables(&self) -> RunnablesConfig {
761         RunnablesConfig {
762             override_cargo: self.data.runnables_overrideCargo.clone(),
763             cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
764         }
765     }
766     pub fn inlay_hints(&self) -> InlayHintsConfig {
767         InlayHintsConfig {
768             type_hints: self.data.inlayHints_typeHints,
769             parameter_hints: self.data.inlayHints_parameterHints,
770             chaining_hints: self.data.inlayHints_chainingHints,
771             max_length: self.data.inlayHints_maxLength,
772         }
773     }
774     fn insert_use_config(&self) -> InsertUseConfig {
775         InsertUseConfig {
776             granularity: match self.data.assist_importGranularity {
777                 ImportGranularityDef::Preserve => ImportGranularity::Preserve,
778                 ImportGranularityDef::Item => ImportGranularity::Item,
779                 ImportGranularityDef::Crate => ImportGranularity::Crate,
780                 ImportGranularityDef::Module => ImportGranularity::Module,
781             },
782             enforce_granularity: self.data.assist_importEnforceGranularity,
783             prefix_kind: match self.data.assist_importPrefix {
784                 ImportPrefixDef::Plain => PrefixKind::Plain,
785                 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
786                 ImportPrefixDef::BySelf => PrefixKind::BySelf,
787             },
788             group: self.data.assist_importGroup,
789             skip_glob_imports: !self.data.assist_allowMergingIntoGlobImports,
790         }
791     }
792     pub fn completion(&self) -> CompletionConfig {
793         CompletionConfig {
794             enable_postfix_completions: self.data.completion_postfix_enable,
795             enable_imports_on_the_fly: self.data.completion_autoimport_enable
796                 && completion_item_edit_resolve(&self.caps),
797             enable_self_on_the_fly: self.data.completion_autoself_enable,
798             add_call_parenthesis: self.data.completion_addCallParenthesis,
799             add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
800             insert_use: self.insert_use_config(),
801             snippet_cap: SnippetCap::new(try_or!(
802                 self.caps
803                     .text_document
804                     .as_ref()?
805                     .completion
806                     .as_ref()?
807                     .completion_item
808                     .as_ref()?
809                     .snippet_support?,
810                 false
811             )),
812             snippets: self.snippets.clone(),
813         }
814     }
815     pub fn assist(&self) -> AssistConfig {
816         AssistConfig {
817             snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
818             allowed: None,
819             insert_use: self.insert_use_config(),
820         }
821     }
822     pub fn join_lines(&self) -> JoinLinesConfig {
823         JoinLinesConfig {
824             join_else_if: self.data.joinLines_joinElseIf,
825             remove_trailing_comma: self.data.joinLines_removeTrailingComma,
826             unwrap_trivial_blocks: self.data.joinLines_unwrapTrivialBlock,
827             join_assignments: self.data.joinLines_joinAssignments,
828         }
829     }
830     pub fn call_info_full(&self) -> bool {
831         self.data.callInfo_full
832     }
833     pub fn lens(&self) -> LensConfig {
834         LensConfig {
835             run: self.data.lens_enable && self.data.lens_run,
836             debug: self.data.lens_enable && self.data.lens_debug,
837             implementations: self.data.lens_enable && self.data.lens_implementations,
838             method_refs: self.data.lens_enable && self.data.lens_methodReferences,
839             refs: self.data.lens_enable && self.data.lens_references,
840             enum_variant_refs: self.data.lens_enable && self.data.lens_enumVariantReferences,
841         }
842     }
843     pub fn hover_actions(&self) -> HoverActionsConfig {
844         let enable = self.experimental("hoverActions") && self.data.hoverActions_enable;
845         HoverActionsConfig {
846             implementations: enable && self.data.hoverActions_implementations,
847             references: enable && self.data.hoverActions_references,
848             run: enable && self.data.hoverActions_run,
849             debug: enable && self.data.hoverActions_debug,
850             goto_type_def: enable && self.data.hoverActions_gotoTypeDef,
851         }
852     }
853     pub fn highlighting_strings(&self) -> bool {
854         self.data.highlighting_strings
855     }
856     pub fn hover(&self) -> HoverConfig {
857         HoverConfig {
858             links_in_hover: self.data.hover_linksInHover,
859             documentation: self.data.hover_documentation.then(|| {
860                 let is_markdown = try_or!(
861                     self.caps
862                         .text_document
863                         .as_ref()?
864                         .hover
865                         .as_ref()?
866                         .content_format
867                         .as_ref()?
868                         .as_slice(),
869                     &[]
870                 )
871                 .contains(&MarkupKind::Markdown);
872                 if is_markdown {
873                     HoverDocFormat::Markdown
874                 } else {
875                     HoverDocFormat::PlainText
876                 }
877             }),
878         }
879     }
880
881     pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
882         WorkspaceSymbolConfig {
883             search_scope: match self.data.workspace_symbol_search_scope {
884                 WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
885                 WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
886                     WorkspaceSymbolSearchScope::WorkspaceAndDependencies
887                 }
888             },
889             search_kind: match self.data.workspace_symbol_search_kind {
890                 WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
891                 WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
892             },
893         }
894     }
895
896     pub fn semantic_tokens_refresh(&self) -> bool {
897         try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
898     }
899     pub fn code_lens_refresh(&self) -> bool {
900         try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
901     }
902     pub fn insert_replace_support(&self) -> bool {
903         try_or!(
904             self.caps
905                 .text_document
906                 .as_ref()?
907                 .completion
908                 .as_ref()?
909                 .completion_item
910                 .as_ref()?
911                 .insert_replace_support?,
912             false
913         )
914     }
915     pub fn client_commands(&self) -> ClientCommandsConfig {
916         let commands =
917             try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
918         let commands: Option<lsp_ext::ClientCommandOptions> =
919             serde_json::from_value(commands.clone()).ok();
920         let force = commands.is_none() && self.data.lens_forceCustomCommands;
921         let commands = commands.map(|it| it.commands).unwrap_or_default();
922
923         let get = |name: &str| commands.iter().any(|it| it == name) || force;
924
925         ClientCommandsConfig {
926             run_single: get("rust-analyzer.runSingle"),
927             debug_single: get("rust-analyzer.debugSingle"),
928             show_reference: get("rust-analyzer.showReferences"),
929             goto_location: get("rust-analyzer.gotoLocation"),
930             trigger_parameter_hints: get("editor.action.triggerParameterHints"),
931         }
932     }
933
934     pub fn highlight_related(&self) -> HighlightRelatedConfig {
935         HighlightRelatedConfig {
936             references: self.data.highlightRelated_references,
937             break_points: self.data.highlightRelated_breakPoints,
938             exit_points: self.data.highlightRelated_exitPoints,
939             yield_points: self.data.highlightRelated_yieldPoints,
940         }
941     }
942 }
943
944 #[derive(Deserialize, Debug, Clone, Copy)]
945 #[serde(rename_all = "snake_case")]
946 enum SnippetScopeDef {
947     Expr,
948     Item,
949     Type,
950 }
951
952 impl Default for SnippetScopeDef {
953     fn default() -> Self {
954         SnippetScopeDef::Expr
955     }
956 }
957
958 #[derive(Deserialize, Debug, Clone, Default)]
959 #[serde(default)]
960 struct SnippetDef {
961     #[serde(deserialize_with = "single_or_array")]
962     prefix: Vec<String>,
963     #[serde(deserialize_with = "single_or_array")]
964     postfix: Vec<String>,
965     description: Option<String>,
966     #[serde(deserialize_with = "single_or_array")]
967     body: Vec<String>,
968     #[serde(deserialize_with = "single_or_array")]
969     requires: Vec<String>,
970     scope: SnippetScopeDef,
971 }
972
973 fn single_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
974 where
975     D: serde::Deserializer<'de>,
976 {
977     struct SingleOrVec;
978
979     impl<'de> serde::de::Visitor<'de> for SingleOrVec {
980         type Value = Vec<String>;
981
982         fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
983             formatter.write_str("string or array of strings")
984         }
985
986         fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
987         where
988             E: serde::de::Error,
989         {
990             Ok(vec![value.to_owned()])
991         }
992
993         fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
994         where
995             A: serde::de::SeqAccess<'de>,
996         {
997             Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
998         }
999     }
1000
1001     deserializer.deserialize_any(SingleOrVec)
1002 }
1003
1004 #[derive(Deserialize, Debug, Clone)]
1005 #[serde(untagged)]
1006 enum ManifestOrProjectJson {
1007     Manifest(PathBuf),
1008     ProjectJson(ProjectJsonData),
1009 }
1010
1011 #[derive(Deserialize, Debug, Clone)]
1012 #[serde(rename_all = "snake_case")]
1013 enum ImportGranularityDef {
1014     Preserve,
1015     #[serde(alias = "none")]
1016     Item,
1017     #[serde(alias = "full")]
1018     Crate,
1019     #[serde(alias = "last")]
1020     Module,
1021 }
1022
1023 #[derive(Deserialize, Debug, Clone)]
1024 #[serde(rename_all = "snake_case")]
1025 enum ImportPrefixDef {
1026     Plain,
1027     #[serde(alias = "self")]
1028     BySelf,
1029     #[serde(alias = "crate")]
1030     ByCrate,
1031 }
1032
1033 #[derive(Deserialize, Debug, Clone)]
1034 #[serde(rename_all = "snake_case")]
1035 enum WorkspaceSymbolSearchScopeDef {
1036     Workspace,
1037     WorkspaceAndDependencies,
1038 }
1039
1040 #[derive(Deserialize, Debug, Clone)]
1041 #[serde(rename_all = "snake_case")]
1042 enum WorkspaceSymbolSearchKindDef {
1043     OnlyTypes,
1044     AllSymbols,
1045 }
1046
1047 macro_rules! _config_data {
1048     (struct $name:ident {
1049         $(
1050             $(#[doc=$doc:literal])*
1051             $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
1052         )*
1053     }) => {
1054         #[allow(non_snake_case)]
1055         #[derive(Debug, Clone)]
1056         struct $name { $($field: $ty,)* }
1057         impl $name {
1058             fn from_json(mut json: serde_json::Value) -> $name {
1059                 $name {$(
1060                     $field: get_field(
1061                         &mut json,
1062                         stringify!($field),
1063                         None$(.or(Some(stringify!($alias))))*,
1064                         $default,
1065                     ),
1066                 )*}
1067             }
1068
1069             fn json_schema() -> serde_json::Value {
1070                 schema(&[
1071                     $({
1072                         let field = stringify!($field);
1073                         let ty = stringify!($ty);
1074
1075                         (field, ty, &[$($doc),*], $default)
1076                     },)*
1077                 ])
1078             }
1079
1080             #[cfg(test)]
1081             fn manual() -> String {
1082                 manual(&[
1083                     $({
1084                         let field = stringify!($field);
1085                         let ty = stringify!($ty);
1086
1087                         (field, ty, &[$($doc),*], $default)
1088                     },)*
1089                 ])
1090             }
1091         }
1092     };
1093 }
1094 use _config_data as config_data;
1095
1096 fn get_field<T: DeserializeOwned>(
1097     json: &mut serde_json::Value,
1098     field: &'static str,
1099     alias: Option<&'static str>,
1100     default: &str,
1101 ) -> T {
1102     let default = serde_json::from_str(default).unwrap();
1103
1104     // XXX: check alias first, to work-around the VS Code where it pre-fills the
1105     // defaults instead of sending an empty object.
1106     alias
1107         .into_iter()
1108         .chain(iter::once(field))
1109         .find_map(move |field| {
1110             let mut pointer = field.replace('_', "/");
1111             pointer.insert(0, '/');
1112             json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
1113         })
1114         .unwrap_or(default)
1115 }
1116
1117 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
1118     for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
1119         fn key(f: &str) -> &str {
1120             f.splitn(2, '_').next().unwrap()
1121         }
1122         assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
1123     }
1124
1125     let map = fields
1126         .iter()
1127         .map(|(field, ty, doc, default)| {
1128             let name = field.replace("_", ".");
1129             let name = format!("rust-analyzer.{}", name);
1130             let props = field_props(field, ty, doc, default);
1131             (name, props)
1132         })
1133         .collect::<serde_json::Map<_, _>>();
1134     map.into()
1135 }
1136
1137 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
1138     let doc = doc_comment_to_string(doc);
1139     let doc = doc.trim_end_matches('\n');
1140     assert!(
1141         doc.ends_with('.') && doc.starts_with(char::is_uppercase),
1142         "bad docs for {}: {:?}",
1143         field,
1144         doc
1145     );
1146     let default = default.parse::<serde_json::Value>().unwrap();
1147
1148     let mut map = serde_json::Map::default();
1149     macro_rules! set {
1150         ($($key:literal: $value:tt),*$(,)?) => {{$(
1151             map.insert($key.into(), serde_json::json!($value));
1152         )*}};
1153     }
1154     set!("markdownDescription": doc);
1155     set!("default": default);
1156
1157     match ty {
1158         "bool" => set!("type": "boolean"),
1159         "String" => set!("type": "string"),
1160         "Vec<String>" => set! {
1161             "type": "array",
1162             "items": { "type": "string" },
1163         },
1164         "Vec<PathBuf>" => set! {
1165             "type": "array",
1166             "items": { "type": "string" },
1167         },
1168         "FxHashSet<String>" => set! {
1169             "type": "array",
1170             "items": { "type": "string" },
1171             "uniqueItems": true,
1172         },
1173         "FxHashMap<String, SnippetDef>" => set! {
1174             "type": "object",
1175         },
1176         "FxHashMap<String, String>" => set! {
1177             "type": "object",
1178         },
1179         "Option<usize>" => set! {
1180             "type": ["null", "integer"],
1181             "minimum": 0,
1182         },
1183         "Option<String>" => set! {
1184             "type": ["null", "string"],
1185         },
1186         "Option<PathBuf>" => set! {
1187             "type": ["null", "string"],
1188         },
1189         "Option<bool>" => set! {
1190             "type": ["null", "boolean"],
1191         },
1192         "Option<Vec<String>>" => set! {
1193             "type": ["null", "array"],
1194             "items": { "type": "string" },
1195         },
1196         "MergeBehaviorDef" => set! {
1197             "type": "string",
1198             "enum": ["none", "crate", "module"],
1199             "enumDescriptions": [
1200                 "Do not merge imports at all.",
1201                 "Merge imports from the same crate into a single `use` statement.",
1202                 "Merge imports from the same module into a single `use` statement."
1203             ],
1204         },
1205         "ImportGranularityDef" => set! {
1206             "type": "string",
1207             "enum": ["preserve", "crate", "module", "item"],
1208             "enumDescriptions": [
1209                 "Do not change the granularity of any imports and preserve the original structure written by the developer.",
1210                 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
1211                 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
1212                 "Flatten imports so that each has its own use statement."
1213             ],
1214         },
1215         "ImportPrefixDef" => set! {
1216             "type": "string",
1217             "enum": [
1218                 "plain",
1219                 "self",
1220                 "crate"
1221             ],
1222             "enumDescriptions": [
1223                 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
1224                 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item. Prefixes `self` in front of the path if it starts with a module.",
1225                 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
1226             ],
1227         },
1228         "Vec<ManifestOrProjectJson>" => set! {
1229             "type": "array",
1230             "items": { "type": ["string", "object"] },
1231         },
1232         "WorkspaceSymbolSearchScopeDef" => set! {
1233             "type": "string",
1234             "enum": ["workspace", "workspace_and_dependencies"],
1235             "enumDescriptions": [
1236                 "Search in current workspace only",
1237                 "Search in current workspace and dependencies"
1238             ],
1239         },
1240         "WorkspaceSymbolSearchKindDef" => set! {
1241             "type": "string",
1242             "enum": ["only_types", "all_symbols"],
1243             "enumDescriptions": [
1244                 "Search for types only",
1245                 "Search for all symbols kinds"
1246             ],
1247         },
1248         _ => panic!("{}: {}", ty, default),
1249     }
1250
1251     map.into()
1252 }
1253
1254 #[cfg(test)]
1255 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
1256     fields
1257         .iter()
1258         .map(|(field, _ty, doc, default)| {
1259             let name = format!("rust-analyzer.{}", field.replace("_", "."));
1260             let doc = doc_comment_to_string(*doc);
1261             format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
1262         })
1263         .collect::<String>()
1264 }
1265
1266 fn doc_comment_to_string(doc: &[&str]) -> String {
1267     doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
1268 }
1269
1270 #[cfg(test)]
1271 mod tests {
1272     use std::fs;
1273
1274     use test_utils::{ensure_file_contents, project_root};
1275
1276     use super::*;
1277
1278     #[test]
1279     fn generate_package_json_config() {
1280         let s = Config::json_schema();
1281         let schema = format!("{:#}", s);
1282         let mut schema = schema
1283             .trim_start_matches('{')
1284             .trim_end_matches('}')
1285             .replace("  ", "    ")
1286             .replace("\n", "\n            ")
1287             .trim_start_matches('\n')
1288             .trim_end()
1289             .to_string();
1290         schema.push_str(",\n");
1291
1292         // Transform the asciidoc form link to markdown style.
1293         //
1294         // https://link[text] => [text](https://link)
1295         let url_matches = schema.match_indices("https://");
1296         let mut url_offsets = url_matches.map(|(idx, _)| idx).collect::<Vec<usize>>();
1297         url_offsets.reverse();
1298         for idx in url_offsets {
1299             let link = &schema[idx..];
1300             // matching on whitespace to ignore normal links
1301             if let Some(link_end) = link.find(|c| c == ' ' || c == '[') {
1302                 if link.chars().nth(link_end) == Some('[') {
1303                     if let Some(link_text_end) = link.find(']') {
1304                         let link_text = link[link_end..(link_text_end + 1)].to_string();
1305
1306                         schema.replace_range((idx + link_end)..(idx + link_text_end + 1), "");
1307                         schema.insert(idx, '(');
1308                         schema.insert(idx + link_end + 1, ')');
1309                         schema.insert_str(idx, &link_text);
1310                     }
1311                 }
1312             }
1313         }
1314
1315         let package_json_path = project_root().join("editors/code/package.json");
1316         let mut package_json = fs::read_to_string(&package_json_path).unwrap();
1317
1318         let start_marker = "                \"$generated-start\": {},\n";
1319         let end_marker = "                \"$generated-end\": {}\n";
1320
1321         let start = package_json.find(start_marker).unwrap() + start_marker.len();
1322         let end = package_json.find(end_marker).unwrap();
1323
1324         let p = remove_ws(&package_json[start..end]);
1325         let s = remove_ws(&schema);
1326         if !p.contains(&s) {
1327             package_json.replace_range(start..end, &schema);
1328             ensure_file_contents(&package_json_path, &package_json)
1329         }
1330     }
1331
1332     #[test]
1333     fn generate_config_documentation() {
1334         let docs_path = project_root().join("docs/user/generated_config.adoc");
1335         let expected = ConfigData::manual();
1336         ensure_file_contents(&docs_path, &expected);
1337     }
1338
1339     fn remove_ws(text: &str) -> String {
1340         text.replace(char::is_whitespace, "")
1341     }
1342 }