terminal.rs

  1use std::path::PathBuf;
  2
  3use collections::HashMap;
  4use schemars::JsonSchema;
  5use serde::{Deserialize, Serialize};
  6use settings_macros::{MergeFrom, with_fallible_options};
  7
  8use crate::{FontFamilyName, FontFeaturesContent, FontSize, FontWeightContent};
  9
 10#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
 11pub struct ProjectTerminalSettingsContent {
 12    /// What shell to use when opening a terminal.
 13    ///
 14    /// Default: system
 15    pub shell: Option<Shell>,
 16    /// What working directory to use when launching the terminal
 17    ///
 18    /// Default: current_project_directory
 19    pub working_directory: Option<WorkingDirectory>,
 20    /// Any key-value pairs added to this list will be added to the terminal's
 21    /// environment. Use `:` to separate multiple values.
 22    ///
 23    /// Default: {}
 24    pub env: Option<HashMap<String, String>>,
 25    /// Activates the python virtual environment, if one is found, in the
 26    /// terminal's working directory (as resolved by the working_directory
 27    /// setting). Set this to "off" to disable this behavior.
 28    ///
 29    /// Default: on
 30    pub detect_venv: Option<VenvSettings>,
 31    /// Regexes used to identify paths for hyperlink navigation.
 32    ///
 33    /// Default: [
 34    ///   // Python-style diagnostics
 35    ///   "File \"(?<path>[^\"]+)\", line (?<line>[0-9]+)",
 36    ///   // Common path syntax with optional line, column, description, trailing punctuation, or
 37    ///   // surrounding symbols or quotes
 38    ///   [
 39    ///     "(?x)",
 40    ///     "# optionally starts with 0-2 opening prefix symbols",
 41    ///     "[({\\[<]{0,2}",
 42    ///     "# which may be followed by an opening quote",
 43    ///     "(?<quote>[\"'`])?",
 44    ///     "# `path` is the shortest sequence of any non-space character",
 45    ///     "(?<link>(?<path>[^ ]+?",
 46    ///     "    # which may end with a line and optionally a column,",
 47    ///     "    (?<line_column>:+[0-9]+(:[0-9]+)?|:?\\([0-9]+([,:][0-9]+)?\\))?",
 48    ///     "))",
 49    ///     "# which must be followed by a matching quote",
 50    ///     "(?(<quote>)\\k<quote>)",
 51    ///     "# and optionally a single closing symbol",
 52    ///     "[)}\\]>]?",
 53    ///     "# if line/column matched, may be followed by a description",
 54    ///     "(?(<line_column>):[^ 0-9][^ ]*)?",
 55    ///     "# which may be followed by trailing punctuation",
 56    ///     "[.,:)}\\]>]*",
 57    ///     "# and always includes trailing whitespace or end of line",
 58    ///     "([ ]+|$)"
 59    ///   ]
 60    /// ]
 61    pub path_hyperlink_regexes: Option<Vec<PathHyperlinkRegex>>,
 62    /// Timeout for hover and Cmd-click path hyperlink discovery in milliseconds.
 63    ///
 64    /// Default: 1
 65    pub path_hyperlink_timeout_ms: Option<u64>,
 66}
 67
 68#[with_fallible_options]
 69#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
 70pub struct TerminalSettingsContent {
 71    #[serde(flatten)]
 72    pub project: ProjectTerminalSettingsContent,
 73    /// Sets the terminal's font size.
 74    ///
 75    /// If this option is not included,
 76    /// the terminal will default to matching the buffer's font size.
 77    pub font_size: Option<FontSize>,
 78    /// Sets the terminal's font family.
 79    ///
 80    /// If this option is not included,
 81    /// the terminal will default to matching the buffer's font family.
 82    pub font_family: Option<FontFamilyName>,
 83
 84    /// Sets the terminal's font fallbacks.
 85    ///
 86    /// If this option is not included,
 87    /// the terminal will default to matching the buffer's font fallbacks.
 88    #[schemars(extend("uniqueItems" = true))]
 89    pub font_fallbacks: Option<Vec<FontFamilyName>>,
 90
 91    /// Sets the terminal's line height.
 92    ///
 93    /// Default: comfortable
 94    pub line_height: Option<TerminalLineHeight>,
 95    pub font_features: Option<FontFeaturesContent>,
 96    /// Sets the terminal's font weight in CSS weight units 0-900.
 97    pub font_weight: Option<FontWeightContent>,
 98    /// Default cursor shape for the terminal.
 99    /// Can be "bar", "block", "underline", or "hollow".
100    ///
101    /// Default: "block"
102    pub cursor_shape: Option<CursorShapeContent>,
103    /// Sets the cursor blinking behavior in the terminal.
104    ///
105    /// Default: terminal_controlled
106    pub blinking: Option<TerminalBlink>,
107    /// Sets whether Alternate Scroll mode (code: ?1007) is active by default.
108    /// Alternate Scroll mode converts mouse scroll events into up / down key
109    /// presses when in the alternate screen (e.g. when running applications
110    /// like vim or  less). The terminal can still set and unset this mode.
111    ///
112    /// Default: on
113    pub alternate_scroll: Option<AlternateScroll>,
114    /// Sets whether the option key behaves as the meta key.
115    ///
116    /// Default: false
117    pub option_as_meta: Option<bool>,
118    /// Whether or not selecting text in the terminal will automatically
119    /// copy to the system clipboard.
120    ///
121    /// Default: false
122    pub copy_on_select: Option<bool>,
123    /// Whether to keep the text selection after copying it to the clipboard.
124    ///
125    /// Default: true
126    pub keep_selection_on_copy: Option<bool>,
127    /// Whether to show the terminal button in the status bar.
128    ///
129    /// Default: true
130    pub button: Option<bool>,
131    pub dock: Option<TerminalDockPosition>,
132    /// Default width when the terminal is docked to the left or right.
133    ///
134    /// Default: 640
135    #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
136    pub default_width: Option<f32>,
137    /// Default height when the terminal is docked to the bottom.
138    ///
139    /// Default: 320
140    #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
141    pub default_height: Option<f32>,
142    /// The maximum number of lines to keep in the scrollback history.
143    /// Maximum allowed value is 100_000, all values above that will be treated as 100_000.
144    /// 0 disables the scrolling.
145    /// Existing terminals will not pick up this change until they are recreated.
146    /// See <a href="https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213">Alacritty documentation</a> for more information.
147    ///
148    /// Default: 10_000
149    pub max_scroll_history_lines: Option<usize>,
150    /// The multiplier for scrolling with the mouse wheel.
151    ///
152    /// Default: 1.0
153    pub scroll_multiplier: Option<f32>,
154    /// Toolbar related settings
155    pub toolbar: Option<TerminalToolbarContent>,
156    /// Scrollbar-related settings
157    pub scrollbar: Option<ScrollbarSettingsContent>,
158    /// The minimum APCA perceptual contrast between foreground and background colors.
159    ///
160    /// APCA (Accessible Perceptual Contrast Algorithm) is more accurate than WCAG 2.x,
161    /// especially for dark mode. Values range from 0 to 106.
162    ///
163    /// Based on APCA Readability Criterion (ARC) Bronze Simple Mode:
164    /// https://readtech.org/ARC/tests/bronze-simple-mode/
165    /// - 0: No contrast adjustment
166    /// - 45: Minimum for large fluent text (36px+)
167    /// - 60: Minimum for other content text
168    /// - 75: Minimum for body text
169    /// - 90: Preferred for body text
170    ///
171    /// Default: 45
172    #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
173    pub minimum_contrast: Option<f32>,
174}
175
176/// Shell configuration to open the terminal with.
177#[derive(
178    Clone,
179    Debug,
180    Default,
181    Serialize,
182    Deserialize,
183    PartialEq,
184    Eq,
185    JsonSchema,
186    MergeFrom,
187    strum::EnumDiscriminants,
188)]
189#[strum_discriminants(derive(strum::VariantArray, strum::VariantNames, strum::FromRepr))]
190#[serde(rename_all = "snake_case")]
191pub enum Shell {
192    /// Use the system's default terminal configuration in /etc/passwd
193    #[default]
194    System,
195    /// Use a specific program with no arguments.
196    Program(String),
197    /// Use a specific program with arguments.
198    WithArguments {
199        /// The program to run.
200        program: String,
201        /// The arguments to pass to the program.
202        args: Vec<String>,
203        /// An optional string to override the title of the terminal tab
204        title_override: Option<String>,
205    },
206}
207
208#[derive(
209    Clone,
210    Debug,
211    Serialize,
212    Deserialize,
213    PartialEq,
214    Eq,
215    JsonSchema,
216    MergeFrom,
217    strum::EnumDiscriminants,
218)]
219#[strum_discriminants(derive(strum::VariantArray, strum::VariantNames, strum::FromRepr))]
220#[serde(rename_all = "snake_case")]
221pub enum WorkingDirectory {
222    /// Use the current file's directory, falling back to the project directory,
223    /// then the first project in the workspace.
224    CurrentFileDirectory,
225    /// Use the current file's project directory. Fallback to the
226    /// first project directory strategy if unsuccessful.
227    CurrentProjectDirectory,
228    /// Use the first project in this workspace's directory. Fallback to using
229    /// this platform's home directory.
230    FirstProjectDirectory,
231    /// Always use this platform's home directory (if it can be found).
232    AlwaysHome,
233    /// Always use a specific directory. This value will be shell expanded.
234    /// If this path is not a valid directory the terminal will default to
235    /// this platform's home directory  (if it can be found).
236    Always { directory: String },
237}
238
239#[with_fallible_options]
240#[derive(
241    Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq, Eq, Default,
242)]
243pub struct ScrollbarSettingsContent {
244    /// When to show the scrollbar in the terminal.
245    ///
246    /// Default: inherits editor scrollbar settings
247    pub show: Option<ShowScrollbar>,
248}
249
250#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom, Default)]
251#[serde(rename_all = "snake_case")]
252pub enum TerminalLineHeight {
253    /// Use a line height that's comfortable for reading, 1.618
254    #[default]
255    Comfortable,
256    /// Use a standard line height, 1.3. This option is useful for TUIs,
257    /// particularly if they use box characters
258    Standard,
259    /// Use a custom line height.
260    Custom(#[serde(serialize_with = "crate::serialize_f32_with_two_decimal_places")] f32),
261}
262
263impl TerminalLineHeight {
264    pub fn value(&self) -> f32 {
265        match self {
266            TerminalLineHeight::Comfortable => 1.618,
267            TerminalLineHeight::Standard => 1.3,
268            TerminalLineHeight::Custom(line_height) => f32::max(*line_height, 1.),
269        }
270    }
271}
272
273/// When to show the scrollbar.
274///
275/// Default: auto
276#[derive(
277    Copy,
278    Clone,
279    Debug,
280    Default,
281    Serialize,
282    Deserialize,
283    JsonSchema,
284    MergeFrom,
285    PartialEq,
286    Eq,
287    strum::VariantArray,
288    strum::VariantNames,
289)]
290#[serde(rename_all = "snake_case")]
291pub enum ShowScrollbar {
292    /// Show the scrollbar if there's important information or
293    /// follow the system's configured behavior.
294    #[default]
295    Auto,
296    /// Match the system's configured behavior.
297    System,
298    /// Always show the scrollbar.
299    Always,
300    /// Never show the scrollbar.
301    Never,
302}
303
304#[derive(
305    Clone,
306    Copy,
307    Debug,
308    Default,
309    Serialize,
310    Deserialize,
311    PartialEq,
312    Eq,
313    JsonSchema,
314    MergeFrom,
315    strum::VariantArray,
316    strum::VariantNames,
317)]
318#[serde(rename_all = "snake_case")]
319// todo() -> combine with CursorShape
320pub enum CursorShapeContent {
321    /// Cursor is a block like `█`.
322    #[default]
323    Block,
324    /// Cursor is an underscore like `_`.
325    Underline,
326    /// Cursor is a vertical bar like `⎸`.
327    Bar,
328    /// Cursor is a hollow box like `▯`.
329    Hollow,
330}
331
332#[derive(
333    Copy,
334    Clone,
335    Debug,
336    Serialize,
337    Deserialize,
338    PartialEq,
339    Eq,
340    JsonSchema,
341    MergeFrom,
342    strum::VariantArray,
343    strum::VariantNames,
344)]
345#[serde(rename_all = "snake_case")]
346pub enum TerminalBlink {
347    /// Never blink the cursor, ignoring the terminal mode.
348    Off,
349    /// Default the cursor blink to off, but allow the terminal to
350    /// set blinking.
351    TerminalControlled,
352    /// Always blink the cursor, ignoring the terminal mode.
353    On,
354}
355
356#[derive(
357    Clone,
358    Copy,
359    Debug,
360    Serialize,
361    Deserialize,
362    PartialEq,
363    Eq,
364    JsonSchema,
365    MergeFrom,
366    strum::VariantArray,
367    strum::VariantNames,
368)]
369#[serde(rename_all = "snake_case")]
370pub enum AlternateScroll {
371    On,
372    Off,
373}
374
375// Toolbar related settings
376#[with_fallible_options]
377#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq, Eq)]
378pub struct TerminalToolbarContent {
379    /// Whether to display the terminal title in breadcrumbs inside the terminal pane.
380    /// Only shown if the terminal title is not empty.
381    ///
382    /// The shell running in the terminal needs to be configured to emit the title.
383    /// Example: `echo -e "\e]2;New Title\007";`
384    ///
385    /// Default: true
386    pub breadcrumbs: Option<bool>,
387}
388
389#[derive(
390    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom,
391)]
392#[serde(rename_all = "snake_case")]
393pub enum CondaManager {
394    /// Automatically detect the conda manager
395    #[default]
396    Auto,
397    /// Use conda
398    Conda,
399    /// Use mamba
400    Mamba,
401    /// Use micromamba
402    Micromamba,
403}
404
405#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
406#[serde(rename_all = "snake_case")]
407pub enum VenvSettings {
408    #[default]
409    Off,
410    On {
411        /// Default directories to search for virtual environments, relative
412        /// to the current working directory. We recommend overriding this
413        /// in your project's settings, rather than globally.
414        activate_script: Option<ActivateScript>,
415        venv_name: Option<String>,
416        directories: Option<Vec<PathBuf>>,
417        /// Preferred Conda manager to use when activating Conda environments.
418        ///
419        /// Default: auto
420        conda_manager: Option<CondaManager>,
421    },
422}
423#[with_fallible_options]
424pub struct VenvSettingsContent<'a> {
425    pub activate_script: ActivateScript,
426    pub venv_name: &'a str,
427    pub directories: &'a [PathBuf],
428    pub conda_manager: CondaManager,
429}
430
431impl VenvSettings {
432    pub fn as_option(&self) -> Option<VenvSettingsContent<'_>> {
433        match self {
434            VenvSettings::Off => None,
435            VenvSettings::On {
436                activate_script,
437                venv_name,
438                directories,
439                conda_manager,
440            } => Some(VenvSettingsContent {
441                activate_script: activate_script.unwrap_or(ActivateScript::Default),
442                venv_name: venv_name.as_deref().unwrap_or(""),
443                directories: directories.as_deref().unwrap_or(&[]),
444                conda_manager: conda_manager.unwrap_or(CondaManager::Auto),
445            }),
446        }
447    }
448}
449
450#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
451#[serde(untagged)]
452pub enum PathHyperlinkRegex {
453    SingleLine(String),
454    MultiLine(Vec<String>),
455}
456
457#[derive(
458    Copy,
459    Clone,
460    Debug,
461    Serialize,
462    Deserialize,
463    JsonSchema,
464    MergeFrom,
465    PartialEq,
466    Eq,
467    strum::VariantArray,
468    strum::VariantNames,
469)]
470#[serde(rename_all = "snake_case")]
471pub enum TerminalDockPosition {
472    Left,
473    Bottom,
474    Right,
475}
476
477#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
478#[serde(rename_all = "snake_case")]
479pub enum ActivateScript {
480    #[default]
481    Default,
482    Csh,
483    Fish,
484    Nushell,
485    PowerShell,
486    Pyenv,
487}
488
489#[cfg(test)]
490mod test {
491    use serde_json::json;
492
493    use crate::{ProjectSettingsContent, Shell};
494
495    #[test]
496    #[ignore]
497    fn test_project_settings() {
498        let project_content =
499            json!({"terminal": {"shell": {"program": "/bin/project"}}, "option_as_meta": true});
500
501        let _user_content =
502            json!({"terminal": {"shell": {"program": "/bin/user"}}, "option_as_meta": false});
503
504        let project_settings =
505            serde_json::from_value::<ProjectSettingsContent>(project_content).unwrap();
506
507        assert_eq!(
508            project_settings.terminal.unwrap().shell,
509            Some(Shell::Program("/bin/project".to_owned()))
510        );
511    }
512}