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