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