1use alacritty_terminal::vte::ansi::{
2 CursorShape as AlacCursorShape, CursorStyle as AlacCursorStyle,
3};
4use collections::HashMap;
5use gpui::{AbsoluteLength, App, FontFallbacks, FontFeatures, FontWeight, Pixels, px};
6use schemars::JsonSchema;
7use serde_derive::{Deserialize, Serialize};
8
9use settings::SettingsSources;
10use std::path::PathBuf;
11use task::Shell;
12use theme::FontFamilyName;
13
14#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
15#[serde(rename_all = "snake_case")]
16pub enum TerminalDockPosition {
17 Left,
18 Bottom,
19 Right,
20}
21
22#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
23pub struct Toolbar {
24 pub breadcrumbs: bool,
25}
26
27#[derive(Clone, Debug, Deserialize)]
28pub struct TerminalSettings {
29 pub shell: Shell,
30 pub working_directory: WorkingDirectory,
31 pub font_size: Option<Pixels>,
32 pub font_family: Option<FontFamilyName>,
33 pub font_fallbacks: Option<FontFallbacks>,
34 pub font_features: Option<FontFeatures>,
35 pub font_weight: Option<FontWeight>,
36 pub line_height: TerminalLineHeight,
37 pub env: HashMap<String, String>,
38 pub cursor_shape: Option<CursorShape>,
39 pub blinking: TerminalBlink,
40 pub alternate_scroll: AlternateScroll,
41 pub option_as_meta: bool,
42 pub copy_on_select: bool,
43 pub keep_selection_on_copy: bool,
44 pub button: bool,
45 pub dock: TerminalDockPosition,
46 pub default_width: Pixels,
47 pub default_height: Pixels,
48 pub detect_venv: VenvSettings,
49 pub max_scroll_history_lines: Option<usize>,
50 pub toolbar: Toolbar,
51 pub scrollbar: ScrollbarSettings,
52 pub minimum_contrast: f32,
53}
54
55#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
56pub struct ScrollbarSettings {
57 /// When to show the scrollbar in the terminal.
58 ///
59 /// Default: inherits editor scrollbar settings
60 pub show: Option<ShowScrollbar>,
61}
62
63#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
64pub struct ScrollbarSettingsContent {
65 /// When to show the scrollbar in the terminal.
66 ///
67 /// Default: inherits editor scrollbar settings
68 pub show: Option<Option<ShowScrollbar>>,
69}
70
71/// When to show the scrollbar in the terminal.
72///
73/// Default: auto
74#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
75#[serde(rename_all = "snake_case")]
76pub enum ShowScrollbar {
77 /// Show the scrollbar if there's important information or
78 /// follow the system's configured behavior.
79 Auto,
80 /// Match the system's configured behavior.
81 System,
82 /// Always show the scrollbar.
83 Always,
84 /// Never show the scrollbar.
85 Never,
86}
87
88#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
89#[serde(rename_all = "snake_case")]
90pub enum VenvSettings {
91 #[default]
92 Off,
93 On {
94 /// Default directories to search for virtual environments, relative
95 /// to the current working directory. We recommend overriding this
96 /// in your project's settings, rather than globally.
97 activate_script: Option<ActivateScript>,
98 directories: Option<Vec<PathBuf>>,
99 },
100}
101
102pub struct VenvSettingsContent<'a> {
103 pub activate_script: ActivateScript,
104 pub directories: &'a [PathBuf],
105}
106
107impl VenvSettings {
108 pub fn as_option(&self) -> Option<VenvSettingsContent<'_>> {
109 match self {
110 VenvSettings::Off => None,
111 VenvSettings::On {
112 activate_script,
113 directories,
114 } => Some(VenvSettingsContent {
115 activate_script: activate_script.unwrap_or(ActivateScript::Default),
116 directories: directories.as_deref().unwrap_or(&[]),
117 }),
118 }
119 }
120}
121
122#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema)]
123#[serde(rename_all = "snake_case")]
124pub enum ActivateScript {
125 #[default]
126 Default,
127 Csh,
128 Fish,
129 Nushell,
130 PowerShell,
131}
132
133#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
134pub struct TerminalSettingsContent {
135 /// What shell to use when opening a terminal.
136 ///
137 /// Default: system
138 pub shell: Option<Shell>,
139 /// What working directory to use when launching the terminal
140 ///
141 /// Default: current_project_directory
142 pub working_directory: Option<WorkingDirectory>,
143 /// Sets the terminal's font size.
144 ///
145 /// If this option is not included,
146 /// the terminal will default to matching the buffer's font size.
147 pub font_size: Option<f32>,
148 /// Sets the terminal's font family.
149 ///
150 /// If this option is not included,
151 /// the terminal will default to matching the buffer's font family.
152 pub font_family: Option<FontFamilyName>,
153
154 /// Sets the terminal's font fallbacks.
155 ///
156 /// If this option is not included,
157 /// the terminal will default to matching the buffer's font fallbacks.
158 #[schemars(extend("uniqueItems" = true))]
159 pub font_fallbacks: Option<Vec<FontFamilyName>>,
160
161 /// Sets the terminal's line height.
162 ///
163 /// Default: comfortable
164 pub line_height: Option<TerminalLineHeight>,
165 pub font_features: Option<FontFeatures>,
166 /// Sets the terminal's font weight in CSS weight units 0-900.
167 pub font_weight: Option<f32>,
168 /// Any key-value pairs added to this list will be added to the terminal's
169 /// environment. Use `:` to separate multiple values.
170 ///
171 /// Default: {}
172 pub env: Option<HashMap<String, String>>,
173 /// Default cursor shape for the terminal.
174 /// Can be "bar", "block", "underline", or "hollow".
175 ///
176 /// Default: None
177 pub cursor_shape: Option<CursorShape>,
178 /// Sets the cursor blinking behavior in the terminal.
179 ///
180 /// Default: terminal_controlled
181 pub blinking: Option<TerminalBlink>,
182 /// Sets whether Alternate Scroll mode (code: ?1007) is active by default.
183 /// Alternate Scroll mode converts mouse scroll events into up / down key
184 /// presses when in the alternate screen (e.g. when running applications
185 /// like vim or less). The terminal can still set and unset this mode.
186 ///
187 /// Default: on
188 pub alternate_scroll: Option<AlternateScroll>,
189 /// Sets whether the option key behaves as the meta key.
190 ///
191 /// Default: false
192 pub option_as_meta: Option<bool>,
193 /// Whether or not selecting text in the terminal will automatically
194 /// copy to the system clipboard.
195 ///
196 /// Default: false
197 pub copy_on_select: Option<bool>,
198 /// Whether to keep the text selection after copying it to the clipboard.
199 ///
200 /// Default: false
201 pub keep_selection_on_copy: Option<bool>,
202 /// Whether to show the terminal button in the status bar.
203 ///
204 /// Default: true
205 pub button: Option<bool>,
206 pub dock: Option<TerminalDockPosition>,
207 /// Default width when the terminal is docked to the left or right.
208 ///
209 /// Default: 640
210 pub default_width: Option<f32>,
211 /// Default height when the terminal is docked to the bottom.
212 ///
213 /// Default: 320
214 pub default_height: Option<f32>,
215 /// Activates the python virtual environment, if one is found, in the
216 /// terminal's working directory (as resolved by the working_directory
217 /// setting). Set this to "off" to disable this behavior.
218 ///
219 /// Default: on
220 pub detect_venv: Option<VenvSettings>,
221 /// The maximum number of lines to keep in the scrollback history.
222 /// Maximum allowed value is 100_000, all values above that will be treated as 100_000.
223 /// 0 disables the scrolling.
224 /// Existing terminals will not pick up this change until they are recreated.
225 /// 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.
226 ///
227 /// Default: 10_000
228 pub max_scroll_history_lines: Option<usize>,
229 /// Toolbar related settings
230 pub toolbar: Option<ToolbarContent>,
231 /// Scrollbar-related settings
232 pub scrollbar: Option<ScrollbarSettingsContent>,
233 /// The minimum APCA perceptual contrast between foreground and background colors.
234 ///
235 /// APCA (Accessible Perceptual Contrast Algorithm) is more accurate than WCAG 2.x,
236 /// especially for dark mode. Values range from 0 to 106.
237 ///
238 /// Based on APCA Readability Criterion (ARC) Bronze Simple Mode:
239 /// https://readtech.org/ARC/tests/bronze-simple-mode/
240 /// - 0: No contrast adjustment
241 /// - 45: Minimum for large fluent text (36px+)
242 /// - 60: Minimum for other content text
243 /// - 75: Minimum for body text
244 /// - 90: Preferred for body text
245 ///
246 /// Default: 0 (no adjustment)
247 pub minimum_contrast: Option<f32>,
248}
249
250impl settings::Settings for TerminalSettings {
251 const KEY: Option<&'static str> = Some("terminal");
252
253 type FileContent = TerminalSettingsContent;
254
255 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> anyhow::Result<Self> {
256 let settings: Self = sources.json_merge()?;
257
258 // Validate minimum_contrast for APCA
259 if settings.minimum_contrast < 0.0 || settings.minimum_contrast > 106.0 {
260 anyhow::bail!(
261 "terminal.minimum_contrast must be between 0 and 106, but got {}. \
262 APCA values: 0 = no adjustment, 75 = recommended for body text, 106 = maximum contrast.",
263 settings.minimum_contrast
264 );
265 }
266
267 Ok(settings)
268 }
269
270 fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
271 let name = |s| format!("terminal.integrated.{s}");
272
273 vscode.f32_setting(&name("fontSize"), &mut current.font_size);
274 if let Some(font_family) = vscode.read_string(&name("fontFamily")) {
275 current.font_family = Some(FontFamilyName(font_family.into()));
276 }
277 vscode.bool_setting(&name("copyOnSelection"), &mut current.copy_on_select);
278 vscode.bool_setting("macOptionIsMeta", &mut current.option_as_meta);
279 vscode.usize_setting("scrollback", &mut current.max_scroll_history_lines);
280 match vscode.read_bool(&name("cursorBlinking")) {
281 Some(true) => current.blinking = Some(TerminalBlink::On),
282 Some(false) => current.blinking = Some(TerminalBlink::Off),
283 None => {}
284 }
285 vscode.enum_setting(
286 &name("cursorStyle"),
287 &mut current.cursor_shape,
288 |s| match s {
289 "block" => Some(CursorShape::Block),
290 "line" => Some(CursorShape::Bar),
291 "underline" => Some(CursorShape::Underline),
292 _ => None,
293 },
294 );
295 // they also have "none" and "outline" as options but just for the "Inactive" variant
296 if let Some(height) = vscode
297 .read_value(&name("lineHeight"))
298 .and_then(|v| v.as_f64())
299 {
300 current.line_height = Some(TerminalLineHeight::Custom(height as f32))
301 }
302
303 #[cfg(target_os = "windows")]
304 let platform = "windows";
305 #[cfg(target_os = "linux")]
306 let platform = "linux";
307 #[cfg(target_os = "macos")]
308 let platform = "osx";
309 #[cfg(target_os = "freebsd")]
310 let platform = "freebsd";
311
312 // TODO: handle arguments
313 let shell_name = format!("{platform}Exec");
314 if let Some(s) = vscode.read_string(&name(&shell_name)) {
315 current.shell = Some(Shell::Program(s.to_owned()))
316 }
317
318 if let Some(env) = vscode
319 .read_value(&name(&format!("env.{platform}")))
320 .and_then(|v| v.as_object())
321 {
322 for (k, v) in env {
323 if v.is_null() {
324 if let Some(zed_env) = current.env.as_mut() {
325 zed_env.remove(k);
326 }
327 }
328 let Some(v) = v.as_str() else { continue };
329 if let Some(zed_env) = current.env.as_mut() {
330 zed_env.insert(k.clone(), v.to_owned());
331 } else {
332 current.env = Some([(k.clone(), v.to_owned())].into_iter().collect())
333 }
334 }
335 }
336 }
337}
338
339#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
340#[serde(rename_all = "snake_case")]
341pub enum TerminalLineHeight {
342 /// Use a line height that's comfortable for reading, 1.618
343 #[default]
344 Comfortable,
345 /// Use a standard line height, 1.3. This option is useful for TUIs,
346 /// particularly if they use box characters
347 Standard,
348 /// Use a custom line height.
349 Custom(f32),
350}
351
352impl TerminalLineHeight {
353 pub fn value(&self) -> AbsoluteLength {
354 let value = match self {
355 TerminalLineHeight::Comfortable => 1.618,
356 TerminalLineHeight::Standard => 1.3,
357 TerminalLineHeight::Custom(line_height) => f32::max(*line_height, 1.),
358 };
359 px(value).into()
360 }
361}
362
363#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
364#[serde(rename_all = "snake_case")]
365pub enum TerminalBlink {
366 /// Never blink the cursor, ignoring the terminal mode.
367 Off,
368 /// Default the cursor blink to off, but allow the terminal to
369 /// set blinking.
370 TerminalControlled,
371 /// Always blink the cursor, ignoring the terminal mode.
372 On,
373}
374
375#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
376#[serde(rename_all = "snake_case")]
377pub enum AlternateScroll {
378 On,
379 Off,
380}
381
382#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
383#[serde(rename_all = "snake_case")]
384pub enum WorkingDirectory {
385 /// Use the current file's project directory. Will Fallback to the
386 /// first project directory strategy if unsuccessful.
387 CurrentProjectDirectory,
388 /// Use the first project in this workspace's directory.
389 FirstProjectDirectory,
390 /// Always use this platform's home directory (if it can be found).
391 AlwaysHome,
392 /// Always use a specific directory. This value will be shell expanded.
393 /// If this path is not a valid directory the terminal will default to
394 /// this platform's home directory (if it can be found).
395 Always { directory: String },
396}
397
398// Toolbar related settings
399#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
400pub struct ToolbarContent {
401 /// Whether to display the terminal title in breadcrumbs inside the terminal pane.
402 /// Only shown if the terminal title is not empty.
403 ///
404 /// The shell running in the terminal needs to be configured to emit the title.
405 /// Example: `echo -e "\e]2;New Title\007";`
406 ///
407 /// Default: true
408 pub breadcrumbs: Option<bool>,
409}
410
411#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
412#[serde(rename_all = "snake_case")]
413pub enum CursorShape {
414 /// Cursor is a block like `█`.
415 #[default]
416 Block,
417 /// Cursor is an underscore like `_`.
418 Underline,
419 /// Cursor is a vertical bar like `⎸`.
420 Bar,
421 /// Cursor is a hollow box like `▯`.
422 Hollow,
423}
424
425impl From<CursorShape> for AlacCursorShape {
426 fn from(value: CursorShape) -> Self {
427 match value {
428 CursorShape::Block => AlacCursorShape::Block,
429 CursorShape::Underline => AlacCursorShape::Underline,
430 CursorShape::Bar => AlacCursorShape::Beam,
431 CursorShape::Hollow => AlacCursorShape::HollowBlock,
432 }
433 }
434}
435
436impl From<CursorShape> for AlacCursorStyle {
437 fn from(value: CursorShape) -> Self {
438 AlacCursorStyle {
439 shape: value.into(),
440 blinking: false,
441 }
442 }
443}