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 project directory. Fallback to the
223    /// first project directory strategy if unsuccessful.
224    CurrentProjectDirectory,
225    /// Use the first project in this workspace's directory. Fallback to using
226    /// this platform's home directory.
227    FirstProjectDirectory,
228    /// Always use this platform's home directory (if it can be found).
229    AlwaysHome,
230    /// Always use a specific directory. This value will be shell expanded.
231    /// If this path is not a valid directory the terminal will default to
232    /// this platform's home directory  (if it can be found).
233    Always { directory: String },
234}
235
236#[with_fallible_options]
237#[derive(
238    Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq, Eq, Default,
239)]
240pub struct ScrollbarSettingsContent {
241    /// When to show the scrollbar in the terminal.
242    ///
243    /// Default: inherits editor scrollbar settings
244    pub show: Option<ShowScrollbar>,
245}
246
247#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom, Default)]
248#[serde(rename_all = "snake_case")]
249pub enum TerminalLineHeight {
250    /// Use a line height that's comfortable for reading, 1.618
251    #[default]
252    Comfortable,
253    /// Use a standard line height, 1.3. This option is useful for TUIs,
254    /// particularly if they use box characters
255    Standard,
256    /// Use a custom line height.
257    Custom(#[serde(serialize_with = "crate::serialize_f32_with_two_decimal_places")] f32),
258}
259
260impl TerminalLineHeight {
261    pub fn value(&self) -> f32 {
262        match self {
263            TerminalLineHeight::Comfortable => 1.618,
264            TerminalLineHeight::Standard => 1.3,
265            TerminalLineHeight::Custom(line_height) => f32::max(*line_height, 1.),
266        }
267    }
268}
269
270/// When to show the scrollbar.
271///
272/// Default: auto
273#[derive(
274    Copy,
275    Clone,
276    Debug,
277    Default,
278    Serialize,
279    Deserialize,
280    JsonSchema,
281    MergeFrom,
282    PartialEq,
283    Eq,
284    strum::VariantArray,
285    strum::VariantNames,
286)]
287#[serde(rename_all = "snake_case")]
288pub enum ShowScrollbar {
289    /// Show the scrollbar if there's important information or
290    /// follow the system's configured behavior.
291    #[default]
292    Auto,
293    /// Match the system's configured behavior.
294    System,
295    /// Always show the scrollbar.
296    Always,
297    /// Never show the scrollbar.
298    Never,
299}
300
301#[derive(
302    Clone,
303    Copy,
304    Debug,
305    Default,
306    Serialize,
307    Deserialize,
308    PartialEq,
309    Eq,
310    JsonSchema,
311    MergeFrom,
312    strum::VariantArray,
313    strum::VariantNames,
314)]
315#[serde(rename_all = "snake_case")]
316// todo() -> combine with CursorShape
317pub enum CursorShapeContent {
318    /// Cursor is a block like `█`.
319    #[default]
320    Block,
321    /// Cursor is an underscore like `_`.
322    Underline,
323    /// Cursor is a vertical bar like `⎸`.
324    Bar,
325    /// Cursor is a hollow box like `▯`.
326    Hollow,
327}
328
329#[derive(
330    Copy,
331    Clone,
332    Debug,
333    Serialize,
334    Deserialize,
335    PartialEq,
336    Eq,
337    JsonSchema,
338    MergeFrom,
339    strum::VariantArray,
340    strum::VariantNames,
341)]
342#[serde(rename_all = "snake_case")]
343pub enum TerminalBlink {
344    /// Never blink the cursor, ignoring the terminal mode.
345    Off,
346    /// Default the cursor blink to off, but allow the terminal to
347    /// set blinking.
348    TerminalControlled,
349    /// Always blink the cursor, ignoring the terminal mode.
350    On,
351}
352
353#[derive(
354    Clone,
355    Copy,
356    Debug,
357    Serialize,
358    Deserialize,
359    PartialEq,
360    Eq,
361    JsonSchema,
362    MergeFrom,
363    strum::VariantArray,
364    strum::VariantNames,
365)]
366#[serde(rename_all = "snake_case")]
367pub enum AlternateScroll {
368    On,
369    Off,
370}
371
372// Toolbar related settings
373#[with_fallible_options]
374#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq, Eq)]
375pub struct TerminalToolbarContent {
376    /// Whether to display the terminal title in breadcrumbs inside the terminal pane.
377    /// Only shown if the terminal title is not empty.
378    ///
379    /// The shell running in the terminal needs to be configured to emit the title.
380    /// Example: `echo -e "\e]2;New Title\007";`
381    ///
382    /// Default: true
383    pub breadcrumbs: Option<bool>,
384}
385
386#[derive(
387    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom,
388)]
389#[serde(rename_all = "snake_case")]
390pub enum CondaManager {
391    /// Automatically detect the conda manager
392    #[default]
393    Auto,
394    /// Use conda
395    Conda,
396    /// Use mamba
397    Mamba,
398    /// Use micromamba
399    Micromamba,
400}
401
402#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
403#[serde(rename_all = "snake_case")]
404pub enum VenvSettings {
405    #[default]
406    Off,
407    On {
408        /// Default directories to search for virtual environments, relative
409        /// to the current working directory. We recommend overriding this
410        /// in your project's settings, rather than globally.
411        activate_script: Option<ActivateScript>,
412        venv_name: Option<String>,
413        directories: Option<Vec<PathBuf>>,
414        /// Preferred Conda manager to use when activating Conda environments.
415        ///
416        /// Default: auto
417        conda_manager: Option<CondaManager>,
418    },
419}
420#[with_fallible_options]
421pub struct VenvSettingsContent<'a> {
422    pub activate_script: ActivateScript,
423    pub venv_name: &'a str,
424    pub directories: &'a [PathBuf],
425    pub conda_manager: CondaManager,
426}
427
428impl VenvSettings {
429    pub fn as_option(&self) -> Option<VenvSettingsContent<'_>> {
430        match self {
431            VenvSettings::Off => None,
432            VenvSettings::On {
433                activate_script,
434                venv_name,
435                directories,
436                conda_manager,
437            } => Some(VenvSettingsContent {
438                activate_script: activate_script.unwrap_or(ActivateScript::Default),
439                venv_name: venv_name.as_deref().unwrap_or(""),
440                directories: directories.as_deref().unwrap_or(&[]),
441                conda_manager: conda_manager.unwrap_or(CondaManager::Auto),
442            }),
443        }
444    }
445}
446
447#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
448#[serde(untagged)]
449pub enum PathHyperlinkRegex {
450    SingleLine(String),
451    MultiLine(Vec<String>),
452}
453
454#[derive(
455    Copy,
456    Clone,
457    Debug,
458    Serialize,
459    Deserialize,
460    JsonSchema,
461    MergeFrom,
462    PartialEq,
463    Eq,
464    strum::VariantArray,
465    strum::VariantNames,
466)]
467#[serde(rename_all = "snake_case")]
468pub enum TerminalDockPosition {
469    Left,
470    Bottom,
471    Right,
472}
473
474#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
475#[serde(rename_all = "snake_case")]
476pub enum ActivateScript {
477    #[default]
478    Default,
479    Csh,
480    Fish,
481    Nushell,
482    PowerShell,
483    Pyenv,
484}
485
486#[cfg(test)]
487mod test {
488    use serde_json::json;
489
490    use crate::{ProjectSettingsContent, Shell};
491
492    #[test]
493    #[ignore]
494    fn test_project_settings() {
495        let project_content =
496            json!({"terminal": {"shell": {"program": "/bin/project"}}, "option_as_meta": true});
497
498        let _user_content =
499            json!({"terminal": {"shell": {"program": "/bin/user"}}, "option_as_meta": false});
500
501        let project_settings =
502            serde_json::from_value::<ProjectSettingsContent>(project_content).unwrap();
503
504        assert_eq!(
505            project_settings.terminal.unwrap().shell,
506            Some(Shell::Program("/bin/project".to_owned()))
507        );
508    }
509}