Debian Codegraph @

helix-core/src/syntax/config.rs

raw symbols SCIP
1 use crate::{auto_pairs::AutoPairs, diagnostic::Severity, Language};
2
3 use helix_stdx::rope;
4 use serde::{ser::SerializeSeq as _, Deserialize, Serialize};
5 use serde_json::Value;
6
7 use std::{
8 collections::{HashMap, HashSet},
9 fmt::{self, Display},
10 num::NonZeroU8,
11 path::PathBuf,
12 str::FromStr,
13 };
14
15 #[derive(Debug, Serialize, Deserialize)]
16 #[serde(rename_all = "kebab-case")]
17 pub struct Configuration {
18 pub language: Vec<LanguageConfiguration>,
19 #[serde(default)]
20 pub language_server: HashMap<String, LanguageServerConfiguration>,
21 }
22
23 #[derive(Debug, Serialize, Deserialize)]
24 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
25 pub struct LanguageConfiguration {
26 #[serde(skip)]
27 pub(super) language: Option<Language>,
28
29 #[serde(rename = "name")]
30 pub language_id: String, // c-sharp, rust, tsx
31 #[serde(rename = "language-id")]
32 // see the table under https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentItem
33 pub language_server_language_id: Option<String>, // csharp, rust, typescriptreact, for the language-server
34 pub scope: String, // source.rust
35 pub file_types: Vec<FileType>, // filename extension or ends_with? <Gemfile, rb, etc>
36 #[serde(default)]
37 pub shebangs: Vec<String>, // interpreter(s) associated with language
38 #[serde(default)]
39 pub roots: RootMarkers, // these indicate project roots <.git, Cargo.toml>
40 #[serde(
41 default,
42 skip_serializing,
43 deserialize_with = "from_comment_tokens",
44 alias = "comment-token"
45 )]
46 pub comment_tokens: Option<Vec<String>>,
47 #[serde(
48 default,
49 skip_serializing,
50 deserialize_with = "from_block_comment_tokens"
51 )]
52 pub block_comment_tokens: Option<Vec<BlockCommentToken>>,
53 pub text_width: Option<usize>,
54 pub soft_wrap: Option<SoftWrap>,
55
56 #[serde(default)]
57 pub auto_format: bool,
58
59 #[serde(default)]
60 pub code_actions_on_save: Option<Vec<String>>,
61
62 #[serde(skip_serializing_if = "Option::is_none")]
63 pub formatter: Option<FormatterConfiguration>,
64
65 /// If set, overrides `editor.path-completion`.
66 pub path_completion: Option<bool>,
67 /// If set, overrides `editor.word-completion`.
68 pub word_completion: Option<WordCompletion>,
69
70 #[serde(default)]
71 pub diagnostic_severity: Severity,
72
73 pub grammar: Option<String>, // tree-sitter grammar name, defaults to language_id
74
75 // content_regex
76 #[serde(default, skip_serializing, deserialize_with = "deserialize_regex")]
77 pub injection_regex: Option<rope::Regex>,
78 // first_line_regex
79 //
80 #[serde(
81 default,
82 skip_serializing_if = "Vec::is_empty",
83 serialize_with = "serialize_lang_features",
84 deserialize_with = "deserialize_lang_features"
85 )]
86 pub language_servers: Vec<LanguageServerFeatures>,
87 #[serde(skip_serializing_if = "Option::is_none")]
88 pub indent: Option<IndentationConfiguration>,
89
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub debugger: Option<DebugAdapterConfig>,
92
93 /// Automatic insertion of pairs to parentheses, brackets,
94 /// etc. Defaults to true. Optionally, this can be a list of 2-tuples
95 /// to specify a list of characters to pair. This overrides the
96 /// global setting.
97 #[serde(default, skip_serializing, deserialize_with = "deserialize_auto_pairs")]
98 pub auto_pairs: Option<AutoPairs>,
99
100 pub rulers: Option<Vec<u16>>, // if set, override editor's rulers
101
102 /// Hardcoded LSP root directories relative to the workspace root, like `examples` or `tools/fuzz`.
103 /// Falling back to the current working directory if none are configured.
104 pub workspace_lsp_roots: Option<Vec<PathBuf>>,
105 #[serde(default)]
106 pub persistent_diagnostic_sources: Vec<String>,
107 /// Overrides the `editor.rainbow-brackets` config key for the language.
108 pub rainbow_brackets: Option<bool>,
109 }
110
111 impl LanguageConfiguration {
112 pub fn language(&self) -> Language {
113 // This value must be set by `super::Loader::new`.
114 self.language.unwrap()
115 }
116 }
117
118 pub type RootMarkers = GlobSet;
119
120 /// A wrapper around `globset::GlobSet` which implements `Serialize` and `Deserialize`.
121 #[derive(Default, Debug)]
122 pub struct GlobSet {
123 inner: globset::GlobSet,
124 /// Glob patterns as-is before building. This is only used for `Serialize`.
125 patterns: Vec<String>,
126 }
127
128 impl GlobSet {
129 pub fn is_match<P: AsRef<std::path::Path>>(&self, path: P) -> bool {
130 self.inner.is_match(path)
131 }
132 }
133
134 impl Serialize for GlobSet {
135 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
136 where
137 S: serde::Serializer,
138 {
139 let mut patterns = serializer.serialize_seq(Some(self.patterns.len()))?;
140 for pattern in &self.patterns {
141 patterns.serialize_element(pattern)?;
142 }
143 patterns.end()
144 }
145 }
146
147 impl<'de> Deserialize<'de> for GlobSet {
148 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
149 where
150 D: serde::Deserializer<'de>,
151 {
152 let patterns: Vec<String> = Deserialize::deserialize(deserializer)?;
153 let mut builder = globset::GlobSetBuilder::new();
154 for pattern in &patterns {
155 let glob = globset::Glob::new(pattern).map_err(serde::de::Error::custom)?;
156 builder.add(glob);
157 }
158 let inner = builder.build().map_err(serde::de::Error::custom)?;
159 Ok(Self { inner, patterns })
160 }
161 }
162
163 #[derive(Debug, PartialEq, Eq, Hash)]
164 pub enum FileType {
165 /// The extension of the file, either the `Path::extension` or the full
166 /// filename if the file does not have an extension.
167 Extension(String),
168 /// A Unix-style path glob. This is compared to the file's absolute path, so
169 /// it can be used to detect files based on their directories. If the glob
170 /// is not an absolute path and does not already start with a glob pattern,
171 /// a glob pattern will be prepended to it.
172 Glob(globset::Glob),
173 }
174
175 impl Serialize for FileType {
176 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
177 where
178 S: serde::Serializer,
179 {
180 use serde::ser::SerializeMap;
181
182 match self {
183 FileType::Extension(extension) => serializer.serialize_str(extension),
184 FileType::Glob(glob) => {
185 let mut map = serializer.serialize_map(Some(1))?;
186 map.serialize_entry("glob", glob.glob())?;
187 map.end()
188 }
189 }
190 }
191 }
192
193 impl<'de> Deserialize<'de> for FileType {
194 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
195 where
196 D: serde::de::Deserializer<'de>,
197 {
198 struct FileTypeVisitor;
199
200 impl<'de> serde::de::Visitor<'de> for FileTypeVisitor {
201 type Value = FileType;
202
203 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
204 formatter.write_str("string or table")
205 }
206
207 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
208 where
209 E: serde::de::Error,
210 {
211 Ok(FileType::Extension(value.to_string()))
212 }
213
214 fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
215 where
216 M: serde::de::MapAccess<'de>,
217 {
218 match map.next_entry::<String, String>()? {
219 Some((key, mut glob)) if key == "glob" => {
220 // If the glob isn't an absolute path or already starts
221 // with a glob pattern, add a leading glob so we
222 // properly match relative paths.
223 if !glob.starts_with('/') && !glob.starts_with("*/") {
224 glob.insert_str(0, "*/");
225 }
226
227 globset::Glob::new(glob.as_str())
228 .map(FileType::Glob)
229 .map_err(|err| {
230 serde::de::Error::custom(format!("invalid `glob` pattern: {}", err))
231 })
232 }
233 Some((key, _value)) => Err(serde::de::Error::custom(format!(
234 "unknown key in `file-types` list: {}",
235 key
236 ))),
237 None => Err(serde::de::Error::custom(
238 "expected a `suffix` key in the `file-types` entry",
239 )),
240 }
241 }
242 }
243
244 deserializer.deserialize_any(FileTypeVisitor)
245 }
246 }
247
248 fn from_comment_tokens<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
249 where
250 D: serde::Deserializer<'de>,
251 {
252 #[derive(Deserialize)]
253 #[serde(untagged)]
254 enum CommentTokens {
255 Multiple(Vec<String>),
256 Single(String),
257 }
258 Ok(
259 Option::<CommentTokens>::deserialize(deserializer)?.map(|tokens| match tokens {
260 CommentTokens::Single(val) => vec![val],
261 CommentTokens::Multiple(vals) => vals,
262 }),
263 )
264 }
265
266 #[derive(Clone, Debug, Serialize, Deserialize)]
267 pub struct BlockCommentToken {
268 pub start: String,
269 pub end: String,
270 }
271
272 impl Default for BlockCommentToken {
273 fn default() -> Self {
274 BlockCommentToken {
275 start: "/*".to_string(),
276 end: "*/".to_string(),
277 }
278 }
279 }
280
281 fn from_block_comment_tokens<'de, D>(
282 deserializer: D,
283 ) -> Result<Option<Vec<BlockCommentToken>>, D::Error>
284 where
285 D: serde::Deserializer<'de>,
286 {
287 #[derive(Deserialize)]
288 #[serde(untagged)]
289 enum BlockCommentTokens {
290 Multiple(Vec<BlockCommentToken>),
291 Single(BlockCommentToken),
292 }
293 Ok(
294 Option::<BlockCommentTokens>::deserialize(deserializer)?.map(|tokens| match tokens {
295 BlockCommentTokens::Single(val) => vec![val],
296 BlockCommentTokens::Multiple(vals) => vals,
297 }),
298 )
299 }
300
301 #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
302 #[serde(rename_all = "kebab-case")]
303 pub enum LanguageServerFeature {
304 Format,
305 GotoDeclaration,
306 GotoDefinition,
307 GotoTypeDefinition,
308 GotoReference,
309 GotoImplementation,
310 // Goto, use bitflags, combining previous Goto members?
311 SignatureHelp,
312 Hover,
313 DocumentHighlight,
314 Completion,
315 CodeAction,
316 DocumentLinks,
317 WorkspaceCommand,
318 DocumentSymbols,
319 WorkspaceSymbols,
320 // Symbols, use bitflags, see above?
321 Diagnostics,
322 PullDiagnostics,
323 RenameSymbol,
324 InlayHints,
325 DocumentColors,
326 CallHierarchy,
327 }
328
329 impl Display for LanguageServerFeature {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 use LanguageServerFeature::*;
332 let feature = match self {
333 Format => "format",
334 GotoDeclaration => "goto-declaration",
335 GotoDefinition => "goto-definition",
336 GotoTypeDefinition => "goto-type-definition",
337 GotoReference => "goto-reference",
338 GotoImplementation => "goto-implementation",
339 SignatureHelp => "signature-help",
340 Hover => "hover",
341 DocumentHighlight => "document-highlight",
342 Completion => "completion",
343 CodeAction => "code-action",
344 DocumentLinks => "document-links",
345 WorkspaceCommand => "workspace-command",
346 DocumentSymbols => "document-symbols",
347 WorkspaceSymbols => "workspace-symbols",
348 Diagnostics => "diagnostics",
349 PullDiagnostics => "pull-diagnostics",
350 RenameSymbol => "rename-symbol",
351 InlayHints => "inlay-hints",
352 DocumentColors => "document-colors",
353 CallHierarchy => "call-hierarchy",
354 };
355 write!(f, "{feature}",)
356 }
357 }
358
359 #[derive(Debug, Serialize, Deserialize)]
360 #[serde(untagged, rename_all = "kebab-case", deny_unknown_fields)]
361 enum LanguageServerFeatureConfiguration {
362 #[serde(rename_all = "kebab-case")]
363 Features {
364 #[serde(default, skip_serializing_if = "HashSet::is_empty")]
365 only_features: HashSet<LanguageServerFeature>,
366 #[serde(default, skip_serializing_if = "HashSet::is_empty")]
367 except_features: HashSet<LanguageServerFeature>,
368 name: String,
369 },
370 Simple(String),
371 }
372
373 #[derive(Debug, Default)]
374 pub struct LanguageServerFeatures {
375 pub name: String,
376 pub only: HashSet<LanguageServerFeature>,
377 pub excluded: HashSet<LanguageServerFeature>,
378 }
379
380 impl LanguageServerFeatures {
381 pub fn has_feature(&self, feature: LanguageServerFeature) -> bool {
382 (self.only.is_empty() || self.only.contains(&feature)) && !self.excluded.contains(&feature)
383 }
384 }
385
386 fn deserialize_lang_features<'de, D>(
387 deserializer: D,
388 ) -> Result<Vec<LanguageServerFeatures>, D::Error>
389 where
390 D: serde::Deserializer<'de>,
391 {
392 let raw: Vec<LanguageServerFeatureConfiguration> = Deserialize::deserialize(deserializer)?;
393 let res = raw
394 .into_iter()
395 .map(|config| match config {
396 LanguageServerFeatureConfiguration::Simple(name) => LanguageServerFeatures {
397 name,
398 ..Default::default()
399 },
400 LanguageServerFeatureConfiguration::Features {
401 only_features,
402 except_features,
403 name,
404 } => LanguageServerFeatures {
405 name,
406 only: only_features,
407 excluded: except_features,
408 },
409 })
410 .collect();
411 Ok(res)
412 }
413 fn serialize_lang_features<S>(
414 map: &Vec<LanguageServerFeatures>,
415 serializer: S,
416 ) -> Result<S::Ok, S::Error>
417 where
418 S: serde::Serializer,
419 {
420 let mut serializer = serializer.serialize_seq(Some(map.len()))?;
421 for features in map {
422 let features = if features.only.is_empty() && features.excluded.is_empty() {
423 LanguageServerFeatureConfiguration::Simple(features.name.to_owned())
424 } else {
425 LanguageServerFeatureConfiguration::Features {
426 only_features: features.only.clone(),
427 except_features: features.excluded.clone(),
428 name: features.name.to_owned(),
429 }
430 };
431 serializer.serialize_element(&features)?;
432 }
433 serializer.end()
434 }
435
436 #[derive(Debug, Serialize, Deserialize)]
437 #[serde(rename_all = "kebab-case")]
438 pub struct LanguageServerConfiguration {
439 pub command: String,
440 #[serde(default)]
441 #[serde(skip_serializing_if = "Vec::is_empty")]
442 pub args: Vec<String>,
443 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
444 pub environment: HashMap<String, String>,
445 #[serde(default, skip_serializing, deserialize_with = "deserialize_lsp_config")]
446 pub config: Option<serde_json::Value>,
447 #[serde(default = "default_timeout")]
448 pub timeout: u64,
449 #[serde(default)]
450 pub required_root_patterns: Option<GlobSet>,
451 }
452
453 #[derive(Debug, Clone, Serialize, Deserialize)]
454 #[serde(rename_all = "kebab-case")]
455 pub struct FormatterConfiguration {
456 pub command: String,
457 #[serde(default)]
458 #[serde(skip_serializing_if = "Vec::is_empty")]
459 pub args: Vec<String>,
460 }
461
462 #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
463 #[serde(rename_all = "kebab-case")]
464 pub struct AdvancedCompletion {
465 pub name: Option<String>,
466 pub completion: Option<String>,
467 pub default: Option<String>,
468 }
469
470 #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
471 #[serde(rename_all = "kebab-case", untagged)]
472 pub enum DebugConfigCompletion {
473 Named(String),
474 Advanced(AdvancedCompletion),
475 }
476
477 #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
478 #[serde(rename_all = "kebab-case")]
479 pub struct DebugTemplate {
480 pub name: String,
481 pub request: String,
482 #[serde(default)]
483 pub completion: Vec<DebugConfigCompletion>,
484 pub args: HashMap<String, Value>,
485 }
486
487 #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
488 #[serde(rename_all = "kebab-case")]
489 pub struct DebugAdapterConfig {
490 pub name: String,
491 pub transport: String,
492 #[serde(default)]
493 pub command: String,
494 #[serde(default)]
495 pub args: Vec<String>,
496 pub port_arg: Option<String>,
497 pub templates: Vec<DebugTemplate>,
498 #[serde(default)]
499 pub quirks: DebuggerQuirks,
500 }
501
502 // Different workarounds for adapters' differences
503 #[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)]
504 pub struct DebuggerQuirks {
505 #[serde(default)]
506 pub absolute_paths: bool,
507 }
508
509 #[derive(Debug, Serialize, Deserialize)]
510 #[serde(rename_all = "kebab-case")]
511 pub struct IndentationConfiguration {
512 #[serde(deserialize_with = "deserialize_tab_width")]
513 pub tab_width: usize,
514 pub unit: String,
515 }
516
517 /// How the indentation for a newly inserted line should be determined.
518 /// If the selected heuristic is not available (e.g. because the current
519 /// language has no tree-sitter indent queries), a simpler one will be used.
520 #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
521 #[serde(rename_all = "kebab-case")]
522 pub enum IndentationHeuristic {
523 /// Just copy the indentation of the line that the cursor is currently on.
524 Simple,
525 /// Use tree-sitter indent queries to compute the expected absolute indentation level of the new line.
526 TreeSitter,
527 /// Use tree-sitter indent queries to compute the expected difference in indentation between the new line
528 /// and the line before. Add this to the actual indentation level of the line before.
529 #[default]
530 Hybrid,
531 }
532
533 /// Configuration for auto pairs
534 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
535 #[serde(rename_all = "kebab-case", deny_unknown_fields, untagged)]
536 pub enum AutoPairConfig {
537 /// Enables or disables auto pairing. False means disabled. True means to use the default pairs.
538 Enable(bool),
539
540 /// The mappings of pairs.
541 Pairs(HashMap<char, char>),
542 }
543
544 impl Default for AutoPairConfig {
545 fn default() -> Self {
546 AutoPairConfig::Enable(true)
547 }
548 }
549
550 impl From<&AutoPairConfig> for Option<AutoPairs> {
551 fn from(auto_pair_config: &AutoPairConfig) -> Self {
552 match auto_pair_config {
553 AutoPairConfig::Enable(false) => None,
554 AutoPairConfig::Enable(true) => Some(AutoPairs::default()),
555 AutoPairConfig::Pairs(pairs) => Some(AutoPairs::new(pairs.iter())),
556 }
557 }
558 }
559
560 impl From<AutoPairConfig> for Option<AutoPairs> {
561 fn from(auto_pairs_config: AutoPairConfig) -> Self {
562 (&auto_pairs_config).into()
563 }
564 }
565
566 impl FromStr for AutoPairConfig {
567 type Err = std::str::ParseBoolError;
568
569 // only do bool parsing for runtime setting
570 fn from_str(s: &str) -> Result<Self, Self::Err> {
571 let enable: bool = s.parse()?;
572 Ok(AutoPairConfig::Enable(enable))
573 }
574 }
575
576 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
577 #[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
578 pub struct SoftWrap {
579 /// Soft wrap lines that exceed viewport width. Default to off
580 // NOTE: Option on purpose because the struct is shared between language config and global config.
581 // By default the option is None so that the language config falls back to the global config unless explicitly set.
582 pub enable: Option<bool>,
583 /// Maximum space left free at the end of the line.
584 /// This space is used to wrap text at word boundaries. If that is not possible within this limit
585 /// the word is simply split at the end of the line.
586 ///
587 /// This is automatically hard-limited to a quarter of the viewport to ensure correct display on small views.
588 ///
589 /// Default to 20
590 pub max_wrap: Option<u16>,
591 /// Maximum number of indentation that can be carried over from the previous line when softwrapping.
592 /// If a line is indented further then this limit it is rendered at the start of the viewport instead.
593 ///
594 /// This is automatically hard-limited to a quarter of the viewport to ensure correct display on small views.
595 ///
596 /// Default to 40
597 pub max_indent_retain: Option<u16>,
598 /// Indicator placed at the beginning of softwrapped lines
599 ///
600 /// Defaults to ↪
601 pub wrap_indicator: Option<String>,
602 /// Softwrap at `text_width` instead of viewport width if it is shorter
603 pub wrap_at_text_width: Option<bool>,
604 }
605
606 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
607 #[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
608 pub struct WordCompletion {
609 pub enable: Option<bool>,
610 pub trigger_length: Option<NonZeroU8>,
611 }
612
613 fn deserialize_regex<'de, D>(deserializer: D) -> Result<Option<rope::Regex>, D::Error>
614 where
615 D: serde::Deserializer<'de>,
616 {
617 Option::<String>::deserialize(deserializer)?
618 .map(|buf| rope::Regex::new(&buf).map_err(serde::de::Error::custom))
619 .transpose()
620 }
621
622 fn deserialize_lsp_config<'de, D>(deserializer: D) -> Result<Option<serde_json::Value>, D::Error>
623 where
624 D: serde::Deserializer<'de>,
625 {
626 Option::<toml::Value>::deserialize(deserializer)?
627 .map(|toml| toml.try_into().map_err(serde::de::Error::custom))
628 .transpose()
629 }
630
631 fn deserialize_tab_width<'de, D>(deserializer: D) -> Result<usize, D::Error>
632 where
633 D: serde::Deserializer<'de>,
634 {
635 usize::deserialize(deserializer).and_then(|n| {
636 if n > 0 && n <= 16 {
637 Ok(n)
638 } else {
639 Err(serde::de::Error::custom(
640 "tab width must be a value from 1 to 16 inclusive",
641 ))
642 }
643 })
644 }
645
646 pub fn deserialize_auto_pairs<'de, D>(deserializer: D) -> Result<Option<AutoPairs>, D::Error>
647 where
648 D: serde::Deserializer<'de>,
649 {
650 Ok(Option::<AutoPairConfig>::deserialize(deserializer)?.and_then(AutoPairConfig::into))
651 }
652
653 fn default_timeout() -> u64 {
654 20
655 }