1use anyhow::{Context as _, Result};
2use collections::{BTreeMap, HashMap, btree_map, hash_map};
3use ec4rs::{ConfigParser, PropertiesSource, Section};
4use fs::Fs;
5use futures::{FutureExt, StreamExt, channel::mpsc, future::LocalBoxFuture};
6use gpui::{App, AsyncApp, BorrowAppContext, Global, Task, UpdateGlobal};
7
8use paths::{EDITORCONFIG_NAME, local_settings_file_relative_path, task_file_name};
9use schemars::{JsonSchema, r#gen::SchemaGenerator, schema::RootSchema};
10use serde::{Deserialize, Serialize, de::DeserializeOwned};
11use serde_json::Value;
12use smallvec::SmallVec;
13use std::{
14 any::{Any, TypeId, type_name},
15 fmt::Debug,
16 ops::Range,
17 path::{Path, PathBuf},
18 str::{self, FromStr},
19 sync::{Arc, LazyLock},
20};
21use streaming_iterator::StreamingIterator;
22use tree_sitter::Query;
23use util::RangeExt;
24
25use util::{ResultExt as _, merge_non_null_json_value_into};
26
27pub type EditorconfigProperties = ec4rs::Properties;
28
29use crate::{SettingsJsonSchemaParams, VsCodeSettings, WorktreeId};
30
31/// A value that can be defined as a user setting.
32///
33/// Settings can be loaded from a combination of multiple JSON files.
34pub trait Settings: 'static + Send + Sync {
35 /// The name of a key within the JSON file from which this setting should
36 /// be deserialized. If this is `None`, then the setting will be deserialized
37 /// from the root object.
38 const KEY: Option<&'static str>;
39
40 const FALLBACK_KEY: Option<&'static str> = None;
41
42 /// The name of the keys in the [`FileContent`](Self::FileContent) that should
43 /// always be written to a settings file, even if their value matches the default
44 /// value.
45 ///
46 /// This is useful for tagged [`FileContent`](Self::FileContent)s where the tag
47 /// is a "version" field that should always be persisted, even if the current
48 /// user settings match the current version of the settings.
49 const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
50
51 /// The type that is stored in an individual JSON file.
52 type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
53
54 /// The logic for combining together values from one or more JSON files into the
55 /// final value for this setting.
56 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut App) -> Result<Self>
57 where
58 Self: Sized;
59
60 fn json_schema(
61 generator: &mut SchemaGenerator,
62 _: &SettingsJsonSchemaParams,
63 _: &App,
64 ) -> RootSchema {
65 generator.root_schema_for::<Self::FileContent>()
66 }
67
68 fn missing_default() -> anyhow::Error {
69 anyhow::anyhow!("missing default")
70 }
71
72 /// Use [the helpers in the vscode_import module](crate::vscode_import) to apply known
73 /// equivalent settings from a vscode config to our config
74 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent);
75
76 #[track_caller]
77 fn register(cx: &mut App)
78 where
79 Self: Sized,
80 {
81 SettingsStore::update_global(cx, |store, cx| {
82 store.register_setting::<Self>(cx);
83 });
84 }
85
86 #[track_caller]
87 fn get<'a>(path: Option<SettingsLocation>, cx: &'a App) -> &'a Self
88 where
89 Self: Sized,
90 {
91 cx.global::<SettingsStore>().get(path)
92 }
93
94 #[track_caller]
95 fn get_global(cx: &App) -> &Self
96 where
97 Self: Sized,
98 {
99 cx.global::<SettingsStore>().get(None)
100 }
101
102 #[track_caller]
103 fn try_read_global<R>(cx: &AsyncApp, f: impl FnOnce(&Self) -> R) -> Option<R>
104 where
105 Self: Sized,
106 {
107 cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
108 }
109
110 #[track_caller]
111 fn override_global(settings: Self, cx: &mut App)
112 where
113 Self: Sized,
114 {
115 cx.global_mut::<SettingsStore>().override_global(settings)
116 }
117}
118
119#[derive(Clone, Copy, Debug)]
120pub struct SettingsSources<'a, T> {
121 /// The default Zed settings.
122 pub default: &'a T,
123 /// Global settings (loaded before user settings).
124 pub global: Option<&'a T>,
125 /// Settings provided by extensions.
126 pub extensions: Option<&'a T>,
127 /// The user settings.
128 pub user: Option<&'a T>,
129 /// The user settings for the current release channel.
130 pub release_channel: Option<&'a T>,
131 /// The server's settings.
132 pub server: Option<&'a T>,
133 /// The project settings, ordered from least specific to most specific.
134 pub project: &'a [&'a T],
135}
136
137impl<'a, T: Serialize> SettingsSources<'a, T> {
138 /// Returns an iterator over the default settings as well as all settings customizations.
139 pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
140 [self.default].into_iter().chain(self.customizations())
141 }
142
143 /// Returns an iterator over all of the settings customizations.
144 pub fn customizations(&self) -> impl Iterator<Item = &T> {
145 self.global
146 .into_iter()
147 .chain(self.extensions)
148 .chain(self.user)
149 .chain(self.release_channel)
150 .chain(self.server)
151 .chain(self.project.iter().copied())
152 }
153
154 /// Returns the settings after performing a JSON merge of the provided customizations.
155 ///
156 /// Customizations later in the iterator win out over the earlier ones.
157 pub fn json_merge_with<O: DeserializeOwned>(
158 customizations: impl Iterator<Item = &'a T>,
159 ) -> Result<O> {
160 let mut merged = Value::Null;
161 for value in customizations {
162 merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
163 }
164 Ok(serde_json::from_value(merged)?)
165 }
166
167 /// Returns the settings after performing a JSON merge of the customizations into the
168 /// default settings.
169 ///
170 /// More-specific customizations win out over the less-specific ones.
171 pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
172 Self::json_merge_with(self.defaults_and_customizations())
173 }
174}
175
176#[derive(Clone, Copy, Debug)]
177pub struct SettingsLocation<'a> {
178 pub worktree_id: WorktreeId,
179 pub path: &'a Path,
180}
181
182/// A set of strongly-typed setting values defined via multiple config files.
183pub struct SettingsStore {
184 setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
185 raw_default_settings: Value,
186 raw_global_settings: Option<Value>,
187 raw_user_settings: Value,
188 raw_server_settings: Option<Value>,
189 raw_extension_settings: Value,
190 raw_local_settings: BTreeMap<(WorktreeId, Arc<Path>), Value>,
191 raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<Path>), (String, Option<Editorconfig>)>,
192 tab_size_callback: Option<(
193 TypeId,
194 Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
195 )>,
196 _setting_file_updates: Task<()>,
197 setting_file_updates_tx:
198 mpsc::UnboundedSender<Box<dyn FnOnce(AsyncApp) -> LocalBoxFuture<'static, Result<()>>>>,
199}
200
201#[derive(Clone)]
202pub struct Editorconfig {
203 pub is_root: bool,
204 pub sections: SmallVec<[Section; 5]>,
205}
206
207impl FromStr for Editorconfig {
208 type Err = anyhow::Error;
209
210 fn from_str(contents: &str) -> Result<Self, Self::Err> {
211 let parser = ConfigParser::new_buffered(contents.as_bytes())
212 .context("creating editorconfig parser")?;
213 let is_root = parser.is_root;
214 let sections = parser
215 .collect::<Result<SmallVec<_>, _>>()
216 .context("parsing editorconfig sections")?;
217 Ok(Self { is_root, sections })
218 }
219}
220
221#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
222pub enum LocalSettingsKind {
223 Settings,
224 Tasks,
225 Editorconfig,
226 Debug,
227}
228
229impl Global for SettingsStore {}
230
231#[derive(Debug)]
232struct SettingValue<T> {
233 global_value: Option<T>,
234 local_values: Vec<(WorktreeId, Arc<Path>, T)>,
235}
236
237trait AnySettingValue: 'static + Send + Sync {
238 fn key(&self) -> Option<&'static str>;
239 fn setting_type_name(&self) -> &'static str;
240 fn deserialize_setting(&self, json: &Value) -> Result<DeserializedSetting> {
241 self.deserialize_setting_with_key(json).1
242 }
243 fn deserialize_setting_with_key(
244 &self,
245 json: &Value,
246 ) -> (Option<&'static str>, Result<DeserializedSetting>);
247 fn load_setting(
248 &self,
249 sources: SettingsSources<DeserializedSetting>,
250 cx: &mut App,
251 ) -> Result<Box<dyn Any>>;
252 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
253 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)>;
254 fn set_global_value(&mut self, value: Box<dyn Any>);
255 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>);
256 fn json_schema(
257 &self,
258 generator: &mut SchemaGenerator,
259 _: &SettingsJsonSchemaParams,
260 cx: &App,
261 ) -> RootSchema;
262 fn edits_for_update(
263 &self,
264 raw_settings: &serde_json::Value,
265 tab_size: usize,
266 vscode_settings: &VsCodeSettings,
267 text: &mut String,
268 edits: &mut Vec<(Range<usize>, String)>,
269 );
270}
271
272struct DeserializedSetting(Box<dyn Any>);
273
274impl SettingsStore {
275 pub fn new(cx: &App) -> Self {
276 let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
277 Self {
278 setting_values: Default::default(),
279 raw_default_settings: serde_json::json!({}),
280 raw_global_settings: None,
281 raw_user_settings: serde_json::json!({}),
282 raw_server_settings: None,
283 raw_extension_settings: serde_json::json!({}),
284 raw_local_settings: Default::default(),
285 raw_editorconfig_settings: BTreeMap::default(),
286 tab_size_callback: Default::default(),
287 setting_file_updates_tx,
288 _setting_file_updates: cx.spawn(async move |cx| {
289 while let Some(setting_file_update) = setting_file_updates_rx.next().await {
290 (setting_file_update)(cx.clone()).await.log_err();
291 }
292 }),
293 }
294 }
295
296 pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
297 where
298 C: BorrowAppContext,
299 {
300 cx.update_global(f)
301 }
302
303 /// Add a new type of setting to the store.
304 pub fn register_setting<T: Settings>(&mut self, cx: &mut App) {
305 let setting_type_id = TypeId::of::<T>();
306 let entry = self.setting_values.entry(setting_type_id);
307
308 if matches!(entry, hash_map::Entry::Occupied(_)) {
309 return;
310 }
311
312 let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
313 global_value: None,
314 local_values: Vec::new(),
315 }));
316
317 if let Some(default_settings) = setting_value
318 .deserialize_setting(&self.raw_default_settings)
319 .log_err()
320 {
321 let user_value = setting_value
322 .deserialize_setting(&self.raw_user_settings)
323 .log_err();
324
325 let mut release_channel_value = None;
326 if let Some(release_settings) = &self
327 .raw_user_settings
328 .get(release_channel::RELEASE_CHANNEL.dev_name())
329 {
330 release_channel_value = setting_value
331 .deserialize_setting(release_settings)
332 .log_err();
333 }
334
335 let server_value = self
336 .raw_server_settings
337 .as_ref()
338 .and_then(|server_setting| {
339 setting_value.deserialize_setting(server_setting).log_err()
340 });
341
342 let extension_value = setting_value
343 .deserialize_setting(&self.raw_extension_settings)
344 .log_err();
345
346 if let Some(setting) = setting_value
347 .load_setting(
348 SettingsSources {
349 default: &default_settings,
350 global: None,
351 extensions: extension_value.as_ref(),
352 user: user_value.as_ref(),
353 release_channel: release_channel_value.as_ref(),
354 server: server_value.as_ref(),
355 project: &[],
356 },
357 cx,
358 )
359 .context("A default setting must be added to the `default.json` file")
360 .log_err()
361 {
362 setting_value.set_global_value(setting);
363 }
364 }
365 }
366
367 /// Get the value of a setting.
368 ///
369 /// Panics if the given setting type has not been registered, or if there is no
370 /// value for this setting.
371 pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
372 self.setting_values
373 .get(&TypeId::of::<T>())
374 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
375 .value_for_path(path)
376 .downcast_ref::<T>()
377 .expect("no default value for setting type")
378 }
379
380 /// Get all values from project specific settings
381 pub fn get_all_locals<T: Settings>(&self) -> Vec<(WorktreeId, Arc<Path>, &T)> {
382 self.setting_values
383 .get(&TypeId::of::<T>())
384 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
385 .all_local_values()
386 .into_iter()
387 .map(|(id, path, any)| {
388 (
389 id,
390 path,
391 any.downcast_ref::<T>()
392 .expect("wrong value type for setting"),
393 )
394 })
395 .collect()
396 }
397
398 /// Override the global value for a setting.
399 ///
400 /// The given value will be overwritten if the user settings file changes.
401 pub fn override_global<T: Settings>(&mut self, value: T) {
402 self.setting_values
403 .get_mut(&TypeId::of::<T>())
404 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
405 .set_global_value(Box::new(value))
406 }
407
408 /// Get the user's settings as a raw JSON value.
409 ///
410 /// For user-facing functionality use the typed setting interface.
411 /// (e.g. ProjectSettings::get_global(cx))
412 pub fn raw_user_settings(&self) -> &Value {
413 &self.raw_user_settings
414 }
415
416 /// Access the raw JSON value of the global settings.
417 pub fn raw_global_settings(&self) -> Option<&Value> {
418 self.raw_global_settings.as_ref()
419 }
420
421 #[cfg(any(test, feature = "test-support"))]
422 pub fn test(cx: &mut App) -> Self {
423 let mut this = Self::new(cx);
424 this.set_default_settings(&crate::test_settings(), cx)
425 .unwrap();
426 this.set_user_settings("{}", cx).unwrap();
427 this
428 }
429
430 /// Updates the value of a setting in the user's global configuration.
431 ///
432 /// This is only for tests. Normally, settings are only loaded from
433 /// JSON files.
434 #[cfg(any(test, feature = "test-support"))]
435 pub fn update_user_settings<T: Settings>(
436 &mut self,
437 cx: &mut App,
438 update: impl FnOnce(&mut T::FileContent),
439 ) {
440 let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
441 let new_text = self.new_text_for_update::<T>(old_text, update);
442 self.set_user_settings(&new_text, cx).unwrap();
443 }
444
445 pub async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
446 match fs.load(paths::settings_file()).await {
447 result @ Ok(_) => result,
448 Err(err) => {
449 if let Some(e) = err.downcast_ref::<std::io::Error>() {
450 if e.kind() == std::io::ErrorKind::NotFound {
451 return Ok(crate::initial_user_settings_content().to_string());
452 }
453 }
454 Err(err)
455 }
456 }
457 }
458
459 pub async fn load_global_settings(fs: &Arc<dyn Fs>) -> Result<String> {
460 match fs.load(paths::global_settings_file()).await {
461 result @ Ok(_) => result,
462 Err(err) => {
463 if let Some(e) = err.downcast_ref::<std::io::Error>() {
464 if e.kind() == std::io::ErrorKind::NotFound {
465 return Ok("{}".to_string());
466 }
467 }
468 Err(err)
469 }
470 }
471 }
472
473 pub fn update_settings_file<T: Settings>(
474 &self,
475 fs: Arc<dyn Fs>,
476 update: impl 'static + Send + FnOnce(&mut T::FileContent, &App),
477 ) {
478 self.setting_file_updates_tx
479 .unbounded_send(Box::new(move |cx: AsyncApp| {
480 async move {
481 let old_text = Self::load_settings(&fs).await?;
482 let new_text = cx.read_global(|store: &SettingsStore, cx| {
483 store.new_text_for_update::<T>(old_text, |content| update(content, cx))
484 })?;
485 let settings_path = paths::settings_file().as_path();
486 if fs.is_file(settings_path).await {
487 let resolved_path =
488 fs.canonicalize(settings_path).await.with_context(|| {
489 format!("Failed to canonicalize settings path {:?}", settings_path)
490 })?;
491
492 fs.atomic_write(resolved_path.clone(), new_text)
493 .await
494 .with_context(|| {
495 format!("Failed to write settings to file {:?}", resolved_path)
496 })?;
497 } else {
498 fs.atomic_write(settings_path.to_path_buf(), new_text)
499 .await
500 .with_context(|| {
501 format!("Failed to write settings to file {:?}", settings_path)
502 })?;
503 }
504
505 anyhow::Ok(())
506 }
507 .boxed_local()
508 }))
509 .ok();
510 }
511
512 pub fn import_vscode_settings(&self, fs: Arc<dyn Fs>, vscode_settings: VsCodeSettings) {
513 self.setting_file_updates_tx
514 .unbounded_send(Box::new(move |cx: AsyncApp| {
515 async move {
516 let old_text = Self::load_settings(&fs).await?;
517 let new_text = cx.read_global(|store: &SettingsStore, _cx| {
518 store.get_vscode_edits(old_text, &vscode_settings)
519 })?;
520 let settings_path = paths::settings_file().as_path();
521 if fs.is_file(settings_path).await {
522 let resolved_path =
523 fs.canonicalize(settings_path).await.with_context(|| {
524 format!("Failed to canonicalize settings path {:?}", settings_path)
525 })?;
526
527 fs.atomic_write(resolved_path.clone(), new_text)
528 .await
529 .with_context(|| {
530 format!("Failed to write settings to file {:?}", resolved_path)
531 })?;
532 } else {
533 fs.atomic_write(settings_path.to_path_buf(), new_text)
534 .await
535 .with_context(|| {
536 format!("Failed to write settings to file {:?}", settings_path)
537 })?;
538 }
539
540 anyhow::Ok(())
541 }
542 .boxed_local()
543 }))
544 .ok();
545 }
546
547 /// Updates the value of a setting in a JSON file, returning the new text
548 /// for that JSON file.
549 pub fn new_text_for_update<T: Settings>(
550 &self,
551 old_text: String,
552 update: impl FnOnce(&mut T::FileContent),
553 ) -> String {
554 let edits = self.edits_for_update::<T>(&old_text, update);
555 let mut new_text = old_text;
556 for (range, replacement) in edits.into_iter() {
557 new_text.replace_range(range, &replacement);
558 }
559 new_text
560 }
561
562 pub fn get_vscode_edits(&self, mut old_text: String, vscode: &VsCodeSettings) -> String {
563 let mut new_text = old_text.clone();
564 let mut edits: Vec<(Range<usize>, String)> = Vec::new();
565 let raw_settings = parse_json_with_comments::<Value>(&old_text).unwrap_or_default();
566 let tab_size = self.json_tab_size();
567 for v in self.setting_values.values() {
568 v.edits_for_update(&raw_settings, tab_size, vscode, &mut old_text, &mut edits);
569 }
570 for (range, replacement) in edits.into_iter() {
571 new_text.replace_range(range, &replacement);
572 }
573 new_text
574 }
575
576 /// Updates the value of a setting in a JSON file, returning a list
577 /// of edits to apply to the JSON file.
578 pub fn edits_for_update<T: Settings>(
579 &self,
580 text: &str,
581 update: impl FnOnce(&mut T::FileContent),
582 ) -> Vec<(Range<usize>, String)> {
583 let setting_type_id = TypeId::of::<T>();
584
585 let preserved_keys = T::PRESERVED_KEYS.unwrap_or_default();
586
587 let setting = self
588 .setting_values
589 .get(&setting_type_id)
590 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
591 let raw_settings = parse_json_with_comments::<Value>(text).unwrap_or_default();
592 let (key, deserialized_setting) = setting.deserialize_setting_with_key(&raw_settings);
593 let old_content = match deserialized_setting {
594 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
595 Err(_) => Box::<<T as Settings>::FileContent>::default(),
596 };
597 let mut new_content = old_content.clone();
598 update(&mut new_content);
599
600 let old_value = serde_json::to_value(&old_content).unwrap();
601 let new_value = serde_json::to_value(new_content).unwrap();
602
603 let mut key_path = Vec::new();
604 if let Some(key) = key {
605 key_path.push(key);
606 }
607
608 let mut edits = Vec::new();
609 let tab_size = self.json_tab_size();
610 let mut text = text.to_string();
611 update_value_in_json_text(
612 &mut text,
613 &mut key_path,
614 tab_size,
615 &old_value,
616 &new_value,
617 preserved_keys,
618 &mut edits,
619 );
620 edits
621 }
622
623 /// Configure the tab sized when updating JSON files.
624 pub fn set_json_tab_size_callback<T: Settings>(
625 &mut self,
626 get_tab_size: fn(&T) -> Option<usize>,
627 ) {
628 self.tab_size_callback = Some((
629 TypeId::of::<T>(),
630 Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
631 ));
632 }
633
634 fn json_tab_size(&self) -> usize {
635 const DEFAULT_JSON_TAB_SIZE: usize = 2;
636
637 if let Some((setting_type_id, callback)) = &self.tab_size_callback {
638 let setting_value = self.setting_values.get(setting_type_id).unwrap();
639 let value = setting_value.value_for_path(None);
640 if let Some(value) = callback(value) {
641 return value;
642 }
643 }
644
645 DEFAULT_JSON_TAB_SIZE
646 }
647
648 /// Sets the default settings via a JSON string.
649 ///
650 /// The string should contain a JSON object with a default value for every setting.
651 pub fn set_default_settings(
652 &mut self,
653 default_settings_content: &str,
654 cx: &mut App,
655 ) -> Result<()> {
656 let settings: Value = parse_json_with_comments(default_settings_content)?;
657 anyhow::ensure!(settings.is_object(), "settings must be an object");
658 self.raw_default_settings = settings;
659 self.recompute_values(None, cx)?;
660 Ok(())
661 }
662
663 /// Sets the user settings via a JSON string.
664 pub fn set_user_settings(
665 &mut self,
666 user_settings_content: &str,
667 cx: &mut App,
668 ) -> Result<Value> {
669 let settings: Value = if user_settings_content.is_empty() {
670 parse_json_with_comments("{}")?
671 } else {
672 parse_json_with_comments(user_settings_content)?
673 };
674
675 anyhow::ensure!(settings.is_object(), "settings must be an object");
676 self.raw_user_settings = settings.clone();
677 self.recompute_values(None, cx)?;
678 Ok(settings)
679 }
680
681 /// Sets the global settings via a JSON string.
682 pub fn set_global_settings(
683 &mut self,
684 global_settings_content: &str,
685 cx: &mut App,
686 ) -> Result<Value> {
687 let settings: Value = if global_settings_content.is_empty() {
688 parse_json_with_comments("{}")?
689 } else {
690 parse_json_with_comments(global_settings_content)?
691 };
692
693 anyhow::ensure!(settings.is_object(), "settings must be an object");
694 self.raw_global_settings = Some(settings.clone());
695 self.recompute_values(None, cx)?;
696 Ok(settings)
697 }
698
699 pub fn set_server_settings(
700 &mut self,
701 server_settings_content: &str,
702 cx: &mut App,
703 ) -> Result<()> {
704 let settings: Option<Value> = if server_settings_content.is_empty() {
705 None
706 } else {
707 parse_json_with_comments(server_settings_content)?
708 };
709
710 anyhow::ensure!(
711 settings
712 .as_ref()
713 .map(|value| value.is_object())
714 .unwrap_or(true),
715 "settings must be an object"
716 );
717 self.raw_server_settings = settings;
718 self.recompute_values(None, cx)?;
719 Ok(())
720 }
721
722 /// Add or remove a set of local settings via a JSON string.
723 pub fn set_local_settings(
724 &mut self,
725 root_id: WorktreeId,
726 directory_path: Arc<Path>,
727 kind: LocalSettingsKind,
728 settings_content: Option<&str>,
729 cx: &mut App,
730 ) -> std::result::Result<(), InvalidSettingsError> {
731 let mut zed_settings_changed = false;
732 match (
733 kind,
734 settings_content
735 .map(|content| content.trim())
736 .filter(|content| !content.is_empty()),
737 ) {
738 (LocalSettingsKind::Tasks, _) => {
739 return Err(InvalidSettingsError::Tasks {
740 message: "Attempted to submit tasks into the settings store".to_string(),
741 path: directory_path.join(task_file_name()),
742 });
743 }
744 (LocalSettingsKind::Debug, _) => {
745 return Err(InvalidSettingsError::Debug {
746 message: "Attempted to submit debugger config into the settings store"
747 .to_string(),
748 path: directory_path.join(task_file_name()),
749 });
750 }
751 (LocalSettingsKind::Settings, None) => {
752 zed_settings_changed = self
753 .raw_local_settings
754 .remove(&(root_id, directory_path.clone()))
755 .is_some()
756 }
757 (LocalSettingsKind::Editorconfig, None) => {
758 self.raw_editorconfig_settings
759 .remove(&(root_id, directory_path.clone()));
760 }
761 (LocalSettingsKind::Settings, Some(settings_contents)) => {
762 let new_settings =
763 parse_json_with_comments::<Value>(settings_contents).map_err(|e| {
764 InvalidSettingsError::LocalSettings {
765 path: directory_path.join(local_settings_file_relative_path()),
766 message: e.to_string(),
767 }
768 })?;
769 match self
770 .raw_local_settings
771 .entry((root_id, directory_path.clone()))
772 {
773 btree_map::Entry::Vacant(v) => {
774 v.insert(new_settings);
775 zed_settings_changed = true;
776 }
777 btree_map::Entry::Occupied(mut o) => {
778 if o.get() != &new_settings {
779 o.insert(new_settings);
780 zed_settings_changed = true;
781 }
782 }
783 }
784 }
785 (LocalSettingsKind::Editorconfig, Some(editorconfig_contents)) => {
786 match self
787 .raw_editorconfig_settings
788 .entry((root_id, directory_path.clone()))
789 {
790 btree_map::Entry::Vacant(v) => match editorconfig_contents.parse() {
791 Ok(new_contents) => {
792 v.insert((editorconfig_contents.to_owned(), Some(new_contents)));
793 }
794 Err(e) => {
795 v.insert((editorconfig_contents.to_owned(), None));
796 return Err(InvalidSettingsError::Editorconfig {
797 message: e.to_string(),
798 path: directory_path.join(EDITORCONFIG_NAME),
799 });
800 }
801 },
802 btree_map::Entry::Occupied(mut o) => {
803 if o.get().0 != editorconfig_contents {
804 match editorconfig_contents.parse() {
805 Ok(new_contents) => {
806 o.insert((
807 editorconfig_contents.to_owned(),
808 Some(new_contents),
809 ));
810 }
811 Err(e) => {
812 o.insert((editorconfig_contents.to_owned(), None));
813 return Err(InvalidSettingsError::Editorconfig {
814 message: e.to_string(),
815 path: directory_path.join(EDITORCONFIG_NAME),
816 });
817 }
818 }
819 }
820 }
821 }
822 }
823 };
824
825 if zed_settings_changed {
826 self.recompute_values(Some((root_id, &directory_path)), cx)?;
827 }
828 Ok(())
829 }
830
831 pub fn set_extension_settings<T: Serialize>(&mut self, content: T, cx: &mut App) -> Result<()> {
832 let settings: Value = serde_json::to_value(content)?;
833 anyhow::ensure!(settings.is_object(), "settings must be an object");
834 self.raw_extension_settings = settings;
835 self.recompute_values(None, cx)?;
836 Ok(())
837 }
838
839 /// Add or remove a set of local settings via a JSON string.
840 pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
841 self.raw_local_settings
842 .retain(|(worktree_id, _), _| worktree_id != &root_id);
843 self.recompute_values(Some((root_id, "".as_ref())), cx)?;
844 Ok(())
845 }
846
847 pub fn local_settings(
848 &self,
849 root_id: WorktreeId,
850 ) -> impl '_ + Iterator<Item = (Arc<Path>, String)> {
851 self.raw_local_settings
852 .range(
853 (root_id, Path::new("").into())
854 ..(
855 WorktreeId::from_usize(root_id.to_usize() + 1),
856 Path::new("").into(),
857 ),
858 )
859 .map(|((_, path), content)| (path.clone(), serde_json::to_string(content).unwrap()))
860 }
861
862 pub fn local_editorconfig_settings(
863 &self,
864 root_id: WorktreeId,
865 ) -> impl '_ + Iterator<Item = (Arc<Path>, String, Option<Editorconfig>)> {
866 self.raw_editorconfig_settings
867 .range(
868 (root_id, Path::new("").into())
869 ..(
870 WorktreeId::from_usize(root_id.to_usize() + 1),
871 Path::new("").into(),
872 ),
873 )
874 .map(|((_, path), (content, parsed_content))| {
875 (path.clone(), content.clone(), parsed_content.clone())
876 })
877 }
878
879 pub fn json_schema(&self, schema_params: &SettingsJsonSchemaParams, cx: &App) -> Value {
880 use schemars::{
881 r#gen::SchemaSettings,
882 schema::{Schema, SchemaObject},
883 };
884
885 let settings = SchemaSettings::draft07().with(|settings| {
886 settings.option_add_null_type = true;
887 });
888 let mut generator = SchemaGenerator::new(settings);
889 let mut combined_schema = RootSchema::default();
890
891 for setting_value in self.setting_values.values() {
892 let setting_schema = setting_value.json_schema(&mut generator, schema_params, cx);
893 combined_schema
894 .definitions
895 .extend(setting_schema.definitions);
896
897 let target_schema = if let Some(key) = setting_value.key() {
898 let key_schema = combined_schema
899 .schema
900 .object()
901 .properties
902 .entry(key.to_string())
903 .or_insert_with(|| Schema::Object(SchemaObject::default()));
904 if let Schema::Object(key_schema) = key_schema {
905 key_schema
906 } else {
907 continue;
908 }
909 } else {
910 &mut combined_schema.schema
911 };
912
913 merge_schema(target_schema, setting_schema.schema);
914 }
915
916 fn merge_schema(target: &mut SchemaObject, mut source: SchemaObject) {
917 let source_subschemas = source.subschemas();
918 let target_subschemas = target.subschemas();
919 if let Some(all_of) = source_subschemas.all_of.take() {
920 target_subschemas
921 .all_of
922 .get_or_insert(Vec::new())
923 .extend(all_of);
924 }
925 if let Some(any_of) = source_subschemas.any_of.take() {
926 target_subschemas
927 .any_of
928 .get_or_insert(Vec::new())
929 .extend(any_of);
930 }
931 if let Some(one_of) = source_subschemas.one_of.take() {
932 target_subschemas
933 .one_of
934 .get_or_insert(Vec::new())
935 .extend(one_of);
936 }
937
938 if let Some(source) = source.object {
939 let target_properties = &mut target.object().properties;
940 for (key, value) in source.properties {
941 match target_properties.entry(key) {
942 btree_map::Entry::Vacant(e) => {
943 e.insert(value);
944 }
945 btree_map::Entry::Occupied(e) => {
946 if let (Schema::Object(target), Schema::Object(src)) =
947 (e.into_mut(), value)
948 {
949 merge_schema(target, src);
950 }
951 }
952 }
953 }
954 }
955
956 overwrite(&mut target.instance_type, source.instance_type);
957 overwrite(&mut target.string, source.string);
958 overwrite(&mut target.number, source.number);
959 overwrite(&mut target.reference, source.reference);
960 overwrite(&mut target.array, source.array);
961 overwrite(&mut target.enum_values, source.enum_values);
962
963 fn overwrite<T>(target: &mut Option<T>, source: Option<T>) {
964 if let Some(source) = source {
965 *target = Some(source);
966 }
967 }
968 }
969
970 for release_stage in ["dev", "nightly", "stable", "preview"] {
971 let schema = combined_schema.schema.clone();
972 combined_schema
973 .schema
974 .object()
975 .properties
976 .insert(release_stage.to_string(), schema.into());
977 }
978
979 serde_json::to_value(&combined_schema).unwrap()
980 }
981
982 fn recompute_values(
983 &mut self,
984 changed_local_path: Option<(WorktreeId, &Path)>,
985 cx: &mut App,
986 ) -> std::result::Result<(), InvalidSettingsError> {
987 // Reload the global and local values for every setting.
988 let mut project_settings_stack = Vec::<DeserializedSetting>::new();
989 let mut paths_stack = Vec::<Option<(WorktreeId, &Path)>>::new();
990 for setting_value in self.setting_values.values_mut() {
991 let default_settings = setting_value
992 .deserialize_setting(&self.raw_default_settings)
993 .map_err(|e| InvalidSettingsError::DefaultSettings {
994 message: e.to_string(),
995 })?;
996
997 let global_settings = self
998 .raw_global_settings
999 .as_ref()
1000 .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
1001
1002 let extension_settings = setting_value
1003 .deserialize_setting(&self.raw_extension_settings)
1004 .log_err();
1005
1006 let user_settings = match setting_value.deserialize_setting(&self.raw_user_settings) {
1007 Ok(settings) => Some(settings),
1008 Err(error) => {
1009 return Err(InvalidSettingsError::UserSettings {
1010 message: error.to_string(),
1011 });
1012 }
1013 };
1014
1015 let server_settings = self
1016 .raw_server_settings
1017 .as_ref()
1018 .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
1019
1020 let mut release_channel_settings = None;
1021 if let Some(release_settings) = &self
1022 .raw_user_settings
1023 .get(release_channel::RELEASE_CHANNEL.dev_name())
1024 {
1025 if let Some(release_settings) = setting_value
1026 .deserialize_setting(release_settings)
1027 .log_err()
1028 {
1029 release_channel_settings = Some(release_settings);
1030 }
1031 }
1032
1033 // If the global settings file changed, reload the global value for the field.
1034 if changed_local_path.is_none() {
1035 if let Some(value) = setting_value
1036 .load_setting(
1037 SettingsSources {
1038 default: &default_settings,
1039 global: global_settings.as_ref(),
1040 extensions: extension_settings.as_ref(),
1041 user: user_settings.as_ref(),
1042 release_channel: release_channel_settings.as_ref(),
1043 server: server_settings.as_ref(),
1044 project: &[],
1045 },
1046 cx,
1047 )
1048 .log_err()
1049 {
1050 setting_value.set_global_value(value);
1051 }
1052 }
1053
1054 // Reload the local values for the setting.
1055 paths_stack.clear();
1056 project_settings_stack.clear();
1057 for ((root_id, directory_path), local_settings) in &self.raw_local_settings {
1058 // Build a stack of all of the local values for that setting.
1059 while let Some(prev_entry) = paths_stack.last() {
1060 if let Some((prev_root_id, prev_path)) = prev_entry {
1061 if root_id != prev_root_id || !directory_path.starts_with(prev_path) {
1062 paths_stack.pop();
1063 project_settings_stack.pop();
1064 continue;
1065 }
1066 }
1067 break;
1068 }
1069
1070 match setting_value.deserialize_setting(local_settings) {
1071 Ok(local_settings) => {
1072 paths_stack.push(Some((*root_id, directory_path.as_ref())));
1073 project_settings_stack.push(local_settings);
1074
1075 // If a local settings file changed, then avoid recomputing local
1076 // settings for any path outside of that directory.
1077 if changed_local_path.map_or(
1078 false,
1079 |(changed_root_id, changed_local_path)| {
1080 *root_id != changed_root_id
1081 || !directory_path.starts_with(changed_local_path)
1082 },
1083 ) {
1084 continue;
1085 }
1086
1087 if let Some(value) = setting_value
1088 .load_setting(
1089 SettingsSources {
1090 default: &default_settings,
1091 global: global_settings.as_ref(),
1092 extensions: extension_settings.as_ref(),
1093 user: user_settings.as_ref(),
1094 release_channel: release_channel_settings.as_ref(),
1095 server: server_settings.as_ref(),
1096 project: &project_settings_stack.iter().collect::<Vec<_>>(),
1097 },
1098 cx,
1099 )
1100 .log_err()
1101 {
1102 setting_value.set_local_value(*root_id, directory_path.clone(), value);
1103 }
1104 }
1105 Err(error) => {
1106 return Err(InvalidSettingsError::LocalSettings {
1107 path: directory_path.join(local_settings_file_relative_path()),
1108 message: error.to_string(),
1109 });
1110 }
1111 }
1112 }
1113 }
1114 Ok(())
1115 }
1116
1117 pub fn editorconfig_properties(
1118 &self,
1119 for_worktree: WorktreeId,
1120 for_path: &Path,
1121 ) -> Option<EditorconfigProperties> {
1122 let mut properties = EditorconfigProperties::new();
1123
1124 for (directory_with_config, _, parsed_editorconfig) in
1125 self.local_editorconfig_settings(for_worktree)
1126 {
1127 if !for_path.starts_with(&directory_with_config) {
1128 properties.use_fallbacks();
1129 return Some(properties);
1130 }
1131 let parsed_editorconfig = parsed_editorconfig?;
1132 if parsed_editorconfig.is_root {
1133 properties = EditorconfigProperties::new();
1134 }
1135 for section in parsed_editorconfig.sections {
1136 section.apply_to(&mut properties, for_path).log_err()?;
1137 }
1138 }
1139
1140 properties.use_fallbacks();
1141 Some(properties)
1142 }
1143}
1144
1145#[derive(Debug, Clone, PartialEq)]
1146pub enum InvalidSettingsError {
1147 LocalSettings { path: PathBuf, message: String },
1148 UserSettings { message: String },
1149 ServerSettings { message: String },
1150 DefaultSettings { message: String },
1151 Editorconfig { path: PathBuf, message: String },
1152 Tasks { path: PathBuf, message: String },
1153 Debug { path: PathBuf, message: String },
1154}
1155
1156impl std::fmt::Display for InvalidSettingsError {
1157 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1158 match self {
1159 InvalidSettingsError::LocalSettings { message, .. }
1160 | InvalidSettingsError::UserSettings { message }
1161 | InvalidSettingsError::ServerSettings { message }
1162 | InvalidSettingsError::DefaultSettings { message }
1163 | InvalidSettingsError::Tasks { message, .. }
1164 | InvalidSettingsError::Editorconfig { message, .. }
1165 | InvalidSettingsError::Debug { message, .. } => {
1166 write!(f, "{message}")
1167 }
1168 }
1169 }
1170}
1171impl std::error::Error for InvalidSettingsError {}
1172
1173impl Debug for SettingsStore {
1174 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1175 f.debug_struct("SettingsStore")
1176 .field(
1177 "types",
1178 &self
1179 .setting_values
1180 .values()
1181 .map(|value| value.setting_type_name())
1182 .collect::<Vec<_>>(),
1183 )
1184 .field("default_settings", &self.raw_default_settings)
1185 .field("user_settings", &self.raw_user_settings)
1186 .field("local_settings", &self.raw_local_settings)
1187 .finish_non_exhaustive()
1188 }
1189}
1190
1191impl<T: Settings> AnySettingValue for SettingValue<T> {
1192 fn key(&self) -> Option<&'static str> {
1193 T::KEY
1194 }
1195
1196 fn setting_type_name(&self) -> &'static str {
1197 type_name::<T>()
1198 }
1199
1200 fn load_setting(
1201 &self,
1202 values: SettingsSources<DeserializedSetting>,
1203 cx: &mut App,
1204 ) -> Result<Box<dyn Any>> {
1205 Ok(Box::new(T::load(
1206 SettingsSources {
1207 default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
1208 global: values
1209 .global
1210 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1211 extensions: values
1212 .extensions
1213 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1214 user: values
1215 .user
1216 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1217 release_channel: values
1218 .release_channel
1219 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1220 server: values
1221 .server
1222 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1223 project: values
1224 .project
1225 .iter()
1226 .map(|value| value.0.downcast_ref().unwrap())
1227 .collect::<SmallVec<[_; 3]>>()
1228 .as_slice(),
1229 },
1230 cx,
1231 )?))
1232 }
1233
1234 fn deserialize_setting_with_key(
1235 &self,
1236 mut json: &Value,
1237 ) -> (Option<&'static str>, Result<DeserializedSetting>) {
1238 let mut key = None;
1239 if let Some(k) = T::KEY {
1240 if let Some(value) = json.get(k) {
1241 json = value;
1242 key = Some(k);
1243 } else if let Some((k, value)) = T::FALLBACK_KEY.and_then(|k| Some((k, json.get(k)?))) {
1244 json = value;
1245 key = Some(k);
1246 } else {
1247 let value = T::FileContent::default();
1248 return (T::KEY, Ok(DeserializedSetting(Box::new(value))));
1249 }
1250 }
1251 let value = T::FileContent::deserialize(json)
1252 .map(|value| DeserializedSetting(Box::new(value)))
1253 .map_err(anyhow::Error::from);
1254 (key, value)
1255 }
1256
1257 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)> {
1258 self.local_values
1259 .iter()
1260 .map(|(id, path, value)| (*id, path.clone(), value as _))
1261 .collect()
1262 }
1263
1264 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1265 if let Some(SettingsLocation { worktree_id, path }) = path {
1266 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1267 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1268 return value;
1269 }
1270 }
1271 }
1272 self.global_value
1273 .as_ref()
1274 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1275 }
1276
1277 fn set_global_value(&mut self, value: Box<dyn Any>) {
1278 self.global_value = Some(*value.downcast().unwrap());
1279 }
1280
1281 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>) {
1282 let value = *value.downcast().unwrap();
1283 match self
1284 .local_values
1285 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1286 {
1287 Ok(ix) => self.local_values[ix].2 = value,
1288 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1289 }
1290 }
1291
1292 fn json_schema(
1293 &self,
1294 generator: &mut SchemaGenerator,
1295 params: &SettingsJsonSchemaParams,
1296 cx: &App,
1297 ) -> RootSchema {
1298 T::json_schema(generator, params, cx)
1299 }
1300
1301 fn edits_for_update(
1302 &self,
1303 raw_settings: &serde_json::Value,
1304 tab_size: usize,
1305 vscode_settings: &VsCodeSettings,
1306 text: &mut String,
1307 edits: &mut Vec<(Range<usize>, String)>,
1308 ) {
1309 let (key, deserialized_setting) = self.deserialize_setting_with_key(raw_settings);
1310 let old_content = match deserialized_setting {
1311 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
1312 Err(_) => Box::<<T as Settings>::FileContent>::default(),
1313 };
1314 let mut new_content = old_content.clone();
1315 T::import_from_vscode(vscode_settings, &mut new_content);
1316
1317 let old_value = serde_json::to_value(&old_content).unwrap();
1318 let new_value = serde_json::to_value(new_content).unwrap();
1319
1320 let mut key_path = Vec::new();
1321 if let Some(key) = key {
1322 key_path.push(key);
1323 }
1324
1325 update_value_in_json_text(
1326 text,
1327 &mut key_path,
1328 tab_size,
1329 &old_value,
1330 &new_value,
1331 T::PRESERVED_KEYS.unwrap_or_default(),
1332 edits,
1333 );
1334 }
1335}
1336
1337fn update_value_in_json_text<'a>(
1338 text: &mut String,
1339 key_path: &mut Vec<&'a str>,
1340 tab_size: usize,
1341 old_value: &'a Value,
1342 new_value: &'a Value,
1343 preserved_keys: &[&str],
1344 edits: &mut Vec<(Range<usize>, String)>,
1345) {
1346 // If the old and new values are both objects, then compare them key by key,
1347 // preserving the comments and formatting of the unchanged parts. Otherwise,
1348 // replace the old value with the new value.
1349 if let (Value::Object(old_object), Value::Object(new_object)) = (old_value, new_value) {
1350 for (key, old_sub_value) in old_object.iter() {
1351 key_path.push(key);
1352 let new_sub_value = new_object.get(key).unwrap_or(&Value::Null);
1353 update_value_in_json_text(
1354 text,
1355 key_path,
1356 tab_size,
1357 old_sub_value,
1358 new_sub_value,
1359 preserved_keys,
1360 edits,
1361 );
1362 key_path.pop();
1363 }
1364 for (key, new_sub_value) in new_object.iter() {
1365 key_path.push(key);
1366 if !old_object.contains_key(key) {
1367 update_value_in_json_text(
1368 text,
1369 key_path,
1370 tab_size,
1371 &Value::Null,
1372 new_sub_value,
1373 preserved_keys,
1374 edits,
1375 );
1376 }
1377 key_path.pop();
1378 }
1379 } else if key_path
1380 .last()
1381 .map_or(false, |key| preserved_keys.contains(key))
1382 || old_value != new_value
1383 {
1384 let mut new_value = new_value.clone();
1385 if let Some(new_object) = new_value.as_object_mut() {
1386 new_object.retain(|_, v| !v.is_null());
1387 }
1388 let (range, replacement) = replace_value_in_json_text(text, key_path, tab_size, &new_value);
1389 text.replace_range(range.clone(), &replacement);
1390 edits.push((range, replacement));
1391 }
1392}
1393
1394fn replace_value_in_json_text(
1395 text: &str,
1396 key_path: &[&str],
1397 tab_size: usize,
1398 new_value: &Value,
1399) -> (Range<usize>, String) {
1400 static PAIR_QUERY: LazyLock<Query> = LazyLock::new(|| {
1401 Query::new(
1402 &tree_sitter_json::LANGUAGE.into(),
1403 "(pair key: (string) @key value: (_) @value)",
1404 )
1405 .expect("Failed to create PAIR_QUERY")
1406 });
1407
1408 let mut parser = tree_sitter::Parser::new();
1409 parser
1410 .set_language(&tree_sitter_json::LANGUAGE.into())
1411 .unwrap();
1412 let syntax_tree = parser.parse(text, None).unwrap();
1413
1414 let mut cursor = tree_sitter::QueryCursor::new();
1415
1416 let mut depth = 0;
1417 let mut last_value_range = 0..0;
1418 let mut first_key_start = None;
1419 let mut existing_value_range = 0..text.len();
1420 let mut matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
1421 while let Some(mat) = matches.next() {
1422 if mat.captures.len() != 2 {
1423 continue;
1424 }
1425
1426 let key_range = mat.captures[0].node.byte_range();
1427 let value_range = mat.captures[1].node.byte_range();
1428
1429 // Don't enter sub objects until we find an exact
1430 // match for the current keypath
1431 if last_value_range.contains_inclusive(&value_range) {
1432 continue;
1433 }
1434
1435 last_value_range = value_range.clone();
1436
1437 if key_range.start > existing_value_range.end {
1438 break;
1439 }
1440
1441 first_key_start.get_or_insert(key_range.start);
1442
1443 let found_key = text
1444 .get(key_range.clone())
1445 .map(|key_text| {
1446 depth < key_path.len() && key_text == format!("\"{}\"", key_path[depth])
1447 })
1448 .unwrap_or(false);
1449
1450 if found_key {
1451 existing_value_range = value_range;
1452 // Reset last value range when increasing in depth
1453 last_value_range = existing_value_range.start..existing_value_range.start;
1454 depth += 1;
1455
1456 if depth == key_path.len() {
1457 break;
1458 }
1459
1460 first_key_start = None;
1461 }
1462 }
1463
1464 // We found the exact key we want, insert the new value
1465 if depth == key_path.len() {
1466 let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
1467 (existing_value_range, new_val)
1468 } else {
1469 // We have key paths, construct the sub objects
1470 let new_key = key_path[depth];
1471
1472 // We don't have the key, construct the nested objects
1473 let mut new_value = serde_json::to_value(new_value).unwrap();
1474 for key in key_path[(depth + 1)..].iter().rev() {
1475 new_value = serde_json::json!({ key.to_string(): new_value });
1476 }
1477
1478 if let Some(first_key_start) = first_key_start {
1479 let mut row = 0;
1480 let mut column = 0;
1481 for (ix, char) in text.char_indices() {
1482 if ix == first_key_start {
1483 break;
1484 }
1485 if char == '\n' {
1486 row += 1;
1487 column = 0;
1488 } else {
1489 column += char.len_utf8();
1490 }
1491 }
1492
1493 if row > 0 {
1494 // depth is 0 based, but division needs to be 1 based.
1495 let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
1496 let space = ' ';
1497 let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
1498 (first_key_start..first_key_start, content)
1499 } else {
1500 let new_val = serde_json::to_string(&new_value).unwrap();
1501 let mut content = format!(r#""{new_key}": {new_val},"#);
1502 content.push(' ');
1503 (first_key_start..first_key_start, content)
1504 }
1505 } else {
1506 new_value = serde_json::json!({ new_key.to_string(): new_value });
1507 let indent_prefix_len = 4 * depth;
1508 let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
1509 if depth == 0 {
1510 new_val.push('\n');
1511 }
1512
1513 (existing_value_range, new_val)
1514 }
1515 }
1516}
1517
1518fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
1519 const SPACES: [u8; 32] = [b' '; 32];
1520
1521 debug_assert!(indent_size <= SPACES.len());
1522 debug_assert!(indent_prefix_len <= SPACES.len());
1523
1524 let mut output = Vec::new();
1525 let mut ser = serde_json::Serializer::with_formatter(
1526 &mut output,
1527 serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
1528 );
1529
1530 value.serialize(&mut ser).unwrap();
1531 let text = String::from_utf8(output).unwrap();
1532
1533 let mut adjusted_text = String::new();
1534 for (i, line) in text.split('\n').enumerate() {
1535 if i > 0 {
1536 adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1537 }
1538 adjusted_text.push_str(line);
1539 adjusted_text.push('\n');
1540 }
1541 adjusted_text.pop();
1542 adjusted_text
1543}
1544
1545pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1546 Ok(serde_json_lenient::from_str(content)?)
1547}
1548
1549#[cfg(test)]
1550mod tests {
1551 use crate::VsCodeSettingsSource;
1552
1553 use super::*;
1554 use serde_derive::Deserialize;
1555 use unindent::Unindent;
1556
1557 #[gpui::test]
1558 fn test_settings_store_basic(cx: &mut App) {
1559 let mut store = SettingsStore::new(cx);
1560 store.register_setting::<UserSettings>(cx);
1561 store.register_setting::<TurboSetting>(cx);
1562 store.register_setting::<MultiKeySettings>(cx);
1563 store
1564 .set_default_settings(
1565 r#"{
1566 "turbo": false,
1567 "user": {
1568 "name": "John Doe",
1569 "age": 30,
1570 "staff": false
1571 }
1572 }"#,
1573 cx,
1574 )
1575 .unwrap();
1576
1577 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1578 assert_eq!(
1579 store.get::<UserSettings>(None),
1580 &UserSettings {
1581 name: "John Doe".to_string(),
1582 age: 30,
1583 staff: false,
1584 }
1585 );
1586 assert_eq!(
1587 store.get::<MultiKeySettings>(None),
1588 &MultiKeySettings {
1589 key1: String::new(),
1590 key2: String::new(),
1591 }
1592 );
1593
1594 store
1595 .set_user_settings(
1596 r#"{
1597 "turbo": true,
1598 "user": { "age": 31 },
1599 "key1": "a"
1600 }"#,
1601 cx,
1602 )
1603 .unwrap();
1604
1605 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1606 assert_eq!(
1607 store.get::<UserSettings>(None),
1608 &UserSettings {
1609 name: "John Doe".to_string(),
1610 age: 31,
1611 staff: false
1612 }
1613 );
1614
1615 store
1616 .set_local_settings(
1617 WorktreeId::from_usize(1),
1618 Path::new("/root1").into(),
1619 LocalSettingsKind::Settings,
1620 Some(r#"{ "user": { "staff": true } }"#),
1621 cx,
1622 )
1623 .unwrap();
1624 store
1625 .set_local_settings(
1626 WorktreeId::from_usize(1),
1627 Path::new("/root1/subdir").into(),
1628 LocalSettingsKind::Settings,
1629 Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1630 cx,
1631 )
1632 .unwrap();
1633
1634 store
1635 .set_local_settings(
1636 WorktreeId::from_usize(1),
1637 Path::new("/root2").into(),
1638 LocalSettingsKind::Settings,
1639 Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1640 cx,
1641 )
1642 .unwrap();
1643
1644 assert_eq!(
1645 store.get::<UserSettings>(Some(SettingsLocation {
1646 worktree_id: WorktreeId::from_usize(1),
1647 path: Path::new("/root1/something"),
1648 })),
1649 &UserSettings {
1650 name: "John Doe".to_string(),
1651 age: 31,
1652 staff: true
1653 }
1654 );
1655 assert_eq!(
1656 store.get::<UserSettings>(Some(SettingsLocation {
1657 worktree_id: WorktreeId::from_usize(1),
1658 path: Path::new("/root1/subdir/something")
1659 })),
1660 &UserSettings {
1661 name: "Jane Doe".to_string(),
1662 age: 31,
1663 staff: true
1664 }
1665 );
1666 assert_eq!(
1667 store.get::<UserSettings>(Some(SettingsLocation {
1668 worktree_id: WorktreeId::from_usize(1),
1669 path: Path::new("/root2/something")
1670 })),
1671 &UserSettings {
1672 name: "John Doe".to_string(),
1673 age: 42,
1674 staff: false
1675 }
1676 );
1677 assert_eq!(
1678 store.get::<MultiKeySettings>(Some(SettingsLocation {
1679 worktree_id: WorktreeId::from_usize(1),
1680 path: Path::new("/root2/something")
1681 })),
1682 &MultiKeySettings {
1683 key1: "a".to_string(),
1684 key2: "b".to_string(),
1685 }
1686 );
1687 }
1688
1689 #[gpui::test]
1690 fn test_setting_store_assign_json_before_register(cx: &mut App) {
1691 let mut store = SettingsStore::new(cx);
1692 store
1693 .set_default_settings(
1694 r#"{
1695 "turbo": true,
1696 "user": {
1697 "name": "John Doe",
1698 "age": 30,
1699 "staff": false
1700 },
1701 "key1": "x"
1702 }"#,
1703 cx,
1704 )
1705 .unwrap();
1706 store
1707 .set_user_settings(r#"{ "turbo": false }"#, cx)
1708 .unwrap();
1709 store.register_setting::<UserSettings>(cx);
1710 store.register_setting::<TurboSetting>(cx);
1711
1712 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1713 assert_eq!(
1714 store.get::<UserSettings>(None),
1715 &UserSettings {
1716 name: "John Doe".to_string(),
1717 age: 30,
1718 staff: false,
1719 }
1720 );
1721
1722 store.register_setting::<MultiKeySettings>(cx);
1723 assert_eq!(
1724 store.get::<MultiKeySettings>(None),
1725 &MultiKeySettings {
1726 key1: "x".into(),
1727 key2: String::new(),
1728 }
1729 );
1730 }
1731
1732 #[gpui::test]
1733 fn test_setting_store_update(cx: &mut App) {
1734 let mut store = SettingsStore::new(cx);
1735 store.register_setting::<MultiKeySettings>(cx);
1736 store.register_setting::<UserSettings>(cx);
1737 store.register_setting::<LanguageSettings>(cx);
1738
1739 // entries added and updated
1740 check_settings_update::<LanguageSettings>(
1741 &mut store,
1742 r#"{
1743 "languages": {
1744 "JSON": {
1745 "language_setting_1": true
1746 }
1747 }
1748 }"#
1749 .unindent(),
1750 |settings| {
1751 settings
1752 .languages
1753 .get_mut("JSON")
1754 .unwrap()
1755 .language_setting_1 = Some(false);
1756 settings.languages.insert(
1757 "Rust".into(),
1758 LanguageSettingEntry {
1759 language_setting_2: Some(true),
1760 ..Default::default()
1761 },
1762 );
1763 },
1764 r#"{
1765 "languages": {
1766 "Rust": {
1767 "language_setting_2": true
1768 },
1769 "JSON": {
1770 "language_setting_1": false
1771 }
1772 }
1773 }"#
1774 .unindent(),
1775 cx,
1776 );
1777
1778 // weird formatting
1779 check_settings_update::<UserSettings>(
1780 &mut store,
1781 r#"{
1782 "user": { "age": 36, "name": "Max", "staff": true }
1783 }"#
1784 .unindent(),
1785 |settings| settings.age = Some(37),
1786 r#"{
1787 "user": { "age": 37, "name": "Max", "staff": true }
1788 }"#
1789 .unindent(),
1790 cx,
1791 );
1792
1793 // single-line formatting, other keys
1794 check_settings_update::<MultiKeySettings>(
1795 &mut store,
1796 r#"{ "one": 1, "two": 2 }"#.unindent(),
1797 |settings| settings.key1 = Some("x".into()),
1798 r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1799 cx,
1800 );
1801
1802 // empty object
1803 check_settings_update::<UserSettings>(
1804 &mut store,
1805 r#"{
1806 "user": {}
1807 }"#
1808 .unindent(),
1809 |settings| settings.age = Some(37),
1810 r#"{
1811 "user": {
1812 "age": 37
1813 }
1814 }"#
1815 .unindent(),
1816 cx,
1817 );
1818
1819 // no content
1820 check_settings_update::<UserSettings>(
1821 &mut store,
1822 r#""#.unindent(),
1823 |settings| settings.age = Some(37),
1824 r#"{
1825 "user": {
1826 "age": 37
1827 }
1828 }
1829 "#
1830 .unindent(),
1831 cx,
1832 );
1833
1834 check_settings_update::<UserSettings>(
1835 &mut store,
1836 r#"{
1837 }
1838 "#
1839 .unindent(),
1840 |settings| settings.age = Some(37),
1841 r#"{
1842 "user": {
1843 "age": 37
1844 }
1845 }
1846 "#
1847 .unindent(),
1848 cx,
1849 );
1850 }
1851
1852 #[gpui::test]
1853 fn test_vscode_import(cx: &mut App) {
1854 let mut store = SettingsStore::new(cx);
1855 store.register_setting::<UserSettings>(cx);
1856 store.register_setting::<JournalSettings>(cx);
1857 store.register_setting::<LanguageSettings>(cx);
1858 store.register_setting::<MultiKeySettings>(cx);
1859
1860 // create settings that werent present
1861 check_vscode_import(
1862 &mut store,
1863 r#"{
1864 }
1865 "#
1866 .unindent(),
1867 r#" { "user.age": 37 } "#.to_owned(),
1868 r#"{
1869 "user": {
1870 "age": 37
1871 }
1872 }
1873 "#
1874 .unindent(),
1875 cx,
1876 );
1877
1878 // persist settings that were present
1879 check_vscode_import(
1880 &mut store,
1881 r#"{
1882 "user": {
1883 "staff": true,
1884 "age": 37
1885 }
1886 }
1887 "#
1888 .unindent(),
1889 r#"{ "user.age": 42 }"#.to_owned(),
1890 r#"{
1891 "user": {
1892 "staff": true,
1893 "age": 42
1894 }
1895 }
1896 "#
1897 .unindent(),
1898 cx,
1899 );
1900
1901 // don't clobber settings that aren't present in vscode
1902 check_vscode_import(
1903 &mut store,
1904 r#"{
1905 "user": {
1906 "staff": true,
1907 "age": 37
1908 }
1909 }
1910 "#
1911 .unindent(),
1912 r#"{}"#.to_owned(),
1913 r#"{
1914 "user": {
1915 "staff": true,
1916 "age": 37
1917 }
1918 }
1919 "#
1920 .unindent(),
1921 cx,
1922 );
1923
1924 // custom enum
1925 check_vscode_import(
1926 &mut store,
1927 r#"{
1928 "journal": {
1929 "hour_format": "hour12"
1930 }
1931 }
1932 "#
1933 .unindent(),
1934 r#"{ "time_format": "24" }"#.to_owned(),
1935 r#"{
1936 "journal": {
1937 "hour_format": "hour24"
1938 }
1939 }
1940 "#
1941 .unindent(),
1942 cx,
1943 );
1944
1945 // Multiple keys for one setting
1946 check_vscode_import(
1947 &mut store,
1948 r#"{
1949 "key1": "value"
1950 }
1951 "#
1952 .unindent(),
1953 r#"{
1954 "key_1_first": "hello",
1955 "key_1_second": "world"
1956 }"#
1957 .to_owned(),
1958 r#"{
1959 "key1": "hello world"
1960 }
1961 "#
1962 .unindent(),
1963 cx,
1964 );
1965
1966 // Merging lists together entries added and updated
1967 check_vscode_import(
1968 &mut store,
1969 r#"{
1970 "languages": {
1971 "JSON": {
1972 "language_setting_1": true
1973 },
1974 "Rust": {
1975 "language_setting_2": true
1976 }
1977 }
1978 }"#
1979 .unindent(),
1980 r#"{
1981 "vscode_languages": [
1982 {
1983 "name": "JavaScript",
1984 "language_setting_1": true
1985 },
1986 {
1987 "name": "Rust",
1988 "language_setting_2": false
1989 }
1990 ]
1991 }"#
1992 .to_owned(),
1993 r#"{
1994 "languages": {
1995 "JavaScript": {
1996 "language_setting_1": true
1997 },
1998 "JSON": {
1999 "language_setting_1": true
2000 },
2001 "Rust": {
2002 "language_setting_2": false
2003 }
2004 }
2005 }"#
2006 .unindent(),
2007 cx,
2008 );
2009 }
2010
2011 fn check_settings_update<T: Settings>(
2012 store: &mut SettingsStore,
2013 old_json: String,
2014 update: fn(&mut T::FileContent),
2015 expected_new_json: String,
2016 cx: &mut App,
2017 ) {
2018 store.set_user_settings(&old_json, cx).ok();
2019 let edits = store.edits_for_update::<T>(&old_json, update);
2020 let mut new_json = old_json;
2021 for (range, replacement) in edits.into_iter() {
2022 new_json.replace_range(range, &replacement);
2023 }
2024 pretty_assertions::assert_eq!(new_json, expected_new_json);
2025 }
2026
2027 fn check_vscode_import(
2028 store: &mut SettingsStore,
2029 old: String,
2030 vscode: String,
2031 expected: String,
2032 cx: &mut App,
2033 ) {
2034 store.set_user_settings(&old, cx).ok();
2035 let new = store.get_vscode_edits(
2036 old,
2037 &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
2038 );
2039 pretty_assertions::assert_eq!(new, expected);
2040 }
2041
2042 #[derive(Debug, PartialEq, Deserialize)]
2043 struct UserSettings {
2044 name: String,
2045 age: u32,
2046 staff: bool,
2047 }
2048
2049 #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
2050 #[schemars(deny_unknown_fields)]
2051 struct UserSettingsContent {
2052 name: Option<String>,
2053 age: Option<u32>,
2054 staff: Option<bool>,
2055 }
2056
2057 impl Settings for UserSettings {
2058 const KEY: Option<&'static str> = Some("user");
2059 type FileContent = UserSettingsContent;
2060
2061 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2062 sources.json_merge()
2063 }
2064
2065 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2066 vscode.u32_setting("user.age", &mut current.age);
2067 }
2068 }
2069
2070 #[derive(Debug, Deserialize, PartialEq)]
2071 struct TurboSetting(bool);
2072
2073 impl Settings for TurboSetting {
2074 const KEY: Option<&'static str> = Some("turbo");
2075 type FileContent = Option<bool>;
2076
2077 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2078 sources.json_merge()
2079 }
2080
2081 fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
2082 }
2083
2084 #[derive(Clone, Debug, PartialEq, Deserialize)]
2085 struct MultiKeySettings {
2086 #[serde(default)]
2087 key1: String,
2088 #[serde(default)]
2089 key2: String,
2090 }
2091
2092 #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
2093 #[schemars(deny_unknown_fields)]
2094 struct MultiKeySettingsJson {
2095 key1: Option<String>,
2096 key2: Option<String>,
2097 }
2098
2099 impl Settings for MultiKeySettings {
2100 const KEY: Option<&'static str> = None;
2101
2102 type FileContent = MultiKeySettingsJson;
2103
2104 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2105 sources.json_merge()
2106 }
2107
2108 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2109 let first_value = vscode.read_string("key_1_first");
2110 let second_value = vscode.read_string("key_1_second");
2111
2112 if let Some((first, second)) = first_value.zip(second_value) {
2113 current.key1 = Some(format!("{} {}", first, second));
2114 }
2115 }
2116 }
2117
2118 #[derive(Debug, Deserialize)]
2119 struct JournalSettings {
2120 pub path: String,
2121 pub hour_format: HourFormat,
2122 }
2123
2124 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
2125 #[serde(rename_all = "snake_case")]
2126 enum HourFormat {
2127 Hour12,
2128 Hour24,
2129 }
2130
2131 #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
2132 #[schemars(deny_unknown_fields)]
2133 struct JournalSettingsJson {
2134 pub path: Option<String>,
2135 pub hour_format: Option<HourFormat>,
2136 }
2137
2138 impl Settings for JournalSettings {
2139 const KEY: Option<&'static str> = Some("journal");
2140
2141 type FileContent = JournalSettingsJson;
2142
2143 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2144 sources.json_merge()
2145 }
2146
2147 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2148 vscode.enum_setting("time_format", &mut current.hour_format, |s| match s {
2149 "12" => Some(HourFormat::Hour12),
2150 "24" => Some(HourFormat::Hour24),
2151 _ => None,
2152 });
2153 }
2154 }
2155
2156 #[gpui::test]
2157 fn test_global_settings(cx: &mut App) {
2158 let mut store = SettingsStore::new(cx);
2159 store.register_setting::<UserSettings>(cx);
2160 store
2161 .set_default_settings(
2162 r#"{
2163 "user": {
2164 "name": "John Doe",
2165 "age": 30,
2166 "staff": false
2167 }
2168 }"#,
2169 cx,
2170 )
2171 .unwrap();
2172
2173 // Set global settings - these should override defaults but not user settings
2174 store
2175 .set_global_settings(
2176 r#"{
2177 "user": {
2178 "name": "Global User",
2179 "age": 35,
2180 "staff": true
2181 }
2182 }"#,
2183 cx,
2184 )
2185 .unwrap();
2186
2187 // Before user settings, global settings should apply
2188 assert_eq!(
2189 store.get::<UserSettings>(None),
2190 &UserSettings {
2191 name: "Global User".to_string(),
2192 age: 35,
2193 staff: true,
2194 }
2195 );
2196
2197 // Set user settings - these should override both defaults and global
2198 store
2199 .set_user_settings(
2200 r#"{
2201 "user": {
2202 "age": 40
2203 }
2204 }"#,
2205 cx,
2206 )
2207 .unwrap();
2208
2209 // User settings should override global settings
2210 assert_eq!(
2211 store.get::<UserSettings>(None),
2212 &UserSettings {
2213 name: "Global User".to_string(), // Name from global settings
2214 age: 40, // Age from user settings
2215 staff: true, // Staff from global settings
2216 }
2217 );
2218 }
2219
2220 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2221 struct LanguageSettings {
2222 #[serde(default)]
2223 languages: HashMap<String, LanguageSettingEntry>,
2224 }
2225
2226 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2227 #[schemars(deny_unknown_fields)]
2228 struct LanguageSettingEntry {
2229 language_setting_1: Option<bool>,
2230 language_setting_2: Option<bool>,
2231 }
2232
2233 impl Settings for LanguageSettings {
2234 const KEY: Option<&'static str> = None;
2235
2236 type FileContent = Self;
2237
2238 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2239 sources.json_merge()
2240 }
2241
2242 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2243 current.languages.extend(
2244 vscode
2245 .read_value("vscode_languages")
2246 .and_then(|value| value.as_array())
2247 .map(|languages| {
2248 languages
2249 .iter()
2250 .filter_map(|value| value.as_object())
2251 .filter_map(|item| {
2252 let mut rest = item.clone();
2253 let name = rest.remove("name")?.as_str()?.to_string();
2254 let entry = serde_json::from_value::<LanguageSettingEntry>(
2255 serde_json::Value::Object(rest),
2256 )
2257 .ok()?;
2258
2259 Some((name, entry))
2260 })
2261 })
2262 .into_iter()
2263 .flatten(),
2264 );
2265 }
2266 }
2267}