Skip to content

Commit 7b4f90e

Browse files
committed
Support mode 2031 dark/light mode detection
1 parent b08aba8 commit 7b4f90e

File tree

7 files changed

+143
-9
lines changed

7 files changed

+143
-9
lines changed

book/src/themes.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,16 @@
22

33
To use a theme add `theme = "<name>"` to the top of your [`config.toml`](./configuration.md) file, or select it during runtime using `:theme <name>`.
44

5+
Separate themes can be configured for light and dark modes. On terminals supporting [mode 2031 dark/light detection](https://github.com/contour-terminal/contour/blob/master/docs/vt-extensions/color-palette-update-notifications.md), the theme mode is detected from the terminal.
6+
7+
```toml
8+
[theme]
9+
dark = "catppuccin_frappe"
10+
light = "catppuccin_latte"
11+
# Optional. Defaults to the theme set for `dark` if not specified.
12+
# no-preference = "catppuccin_frappe"
13+
```
14+
515
## Creating a theme
616

717
Create a file with the name of your theme as the file name (i.e `mytheme.toml`) and place it in your `themes` directory (i.e `~/.config/helix/themes` or `%AppData%\helix\themes` on Windows). The directory might have to be created beforehand.

helix-term/src/application.rs

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ pub struct Application {
6767
signals: Signals,
6868
jobs: Jobs,
6969
lsp_progress: LspProgressMap,
70+
71+
theme_mode: Option<theme::Mode>,
7072
}
7173

7274
#[cfg(feature = "integration")]
@@ -109,6 +111,7 @@ impl Application {
109111
#[cfg(feature = "integration")]
110112
let backend = TestBackend::new(120, 150);
111113

114+
let theme_mode = backend.get_theme_mode();
112115
let terminal = Terminal::new(backend)?;
113116
let area = terminal.size().expect("couldn't get terminal size");
114117
let mut compositor = Compositor::new(area);
@@ -127,6 +130,7 @@ impl Application {
127130
&mut editor,
128131
&config.load(),
129132
terminal.backend().supports_true_color(),
133+
theme_mode,
130134
);
131135

132136
let keys = Box::new(Map::new(Arc::clone(&config), |config: &Config| {
@@ -246,6 +250,7 @@ impl Application {
246250
signals,
247251
jobs: Jobs::new(),
248252
lsp_progress: LspProgressMap::new(),
253+
theme_mode,
249254
};
250255

251256
Ok(app)
@@ -404,6 +409,7 @@ impl Application {
404409
&mut self.editor,
405410
&default_config,
406411
self.terminal.backend().supports_true_color(),
412+
self.theme_mode,
407413
);
408414

409415
// Re-parse any open documents with the new language config.
@@ -437,12 +443,18 @@ impl Application {
437443
}
438444

439445
/// Load the theme set in configuration
440-
fn load_configured_theme(editor: &mut Editor, config: &Config, terminal_true_color: bool) {
446+
fn load_configured_theme(
447+
editor: &mut Editor,
448+
config: &Config,
449+
terminal_true_color: bool,
450+
mode: Option<theme::Mode>,
451+
) {
441452
let true_color = terminal_true_color || config.editor.true_color || crate::true_color();
442453
let theme = config
443454
.theme
444455
.as_ref()
445-
.and_then(|theme| {
456+
.and_then(|theme_config| {
457+
let theme = theme_config.choose(mode);
446458
editor
447459
.theme_loader
448460
.load(theme)
@@ -643,6 +655,8 @@ impl Application {
643655
}
644656

645657
pub async fn handle_terminal_events(&mut self, event: std::io::Result<termina::Event>) {
658+
use termina::escape::csi;
659+
646660
let mut cx = crate::compositor::Context {
647661
editor: &mut self.editor,
648662
jobs: &mut self.jobs,
@@ -667,6 +681,15 @@ impl Application {
667681
kind: termina::event::KeyEventKind::Release,
668682
..
669683
}) => false,
684+
termina::Event::Csi(csi::Csi::Mode(csi::Mode::ReportTheme(mode))) => {
685+
Self::load_configured_theme(
686+
&mut self.editor,
687+
&self.config.load(),
688+
self.terminal.backend().supports_true_color(),
689+
Some(mode.into()),
690+
);
691+
true
692+
}
670693
event => self.compositor.handle_event(&event.into(), &mut cx),
671694
};
672695

@@ -1117,9 +1140,16 @@ impl Application {
11171140

11181141
#[cfg(not(feature = "integration"))]
11191142
pub fn event_stream(&self) -> impl Stream<Item = std::io::Result<termina::Event>> + Unpin {
1120-
use termina::Terminal as _;
1143+
use termina::{escape::csi, Terminal as _};
11211144
let reader = self.terminal.backend().terminal().event_reader();
1122-
termina::EventStream::new(reader, |event| !event.is_escape())
1145+
termina::EventStream::new(reader, |event| {
1146+
// Accept either non-escape sequences or theme mode updates.
1147+
!event.is_escape()
1148+
|| matches!(
1149+
event,
1150+
termina::Event::Csi(csi::Csi::Mode(csi::Mode::ReportTheme(_)))
1151+
)
1152+
})
11231153
}
11241154

11251155
#[cfg(feature = "integration")]

helix-term/src/config.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::keymap;
22
use crate::keymap::{merge_keys, KeyTrie};
33
use helix_loader::merge_toml_values;
4-
use helix_view::document::Mode;
4+
use helix_view::{document::Mode, theme};
55
use serde::Deserialize;
66
use std::collections::HashMap;
77
use std::fmt::Display;
@@ -11,15 +11,15 @@ use toml::de::Error as TomlError;
1111

1212
#[derive(Debug, Clone, PartialEq)]
1313
pub struct Config {
14-
pub theme: Option<String>,
14+
pub theme: Option<theme::Config>,
1515
pub keys: HashMap<Mode, KeyTrie>,
1616
pub editor: helix_view::editor::Config,
1717
}
1818

1919
#[derive(Debug, Clone, PartialEq, Deserialize)]
2020
#[serde(deny_unknown_fields)]
2121
pub struct ConfigRaw {
22-
pub theme: Option<String>,
22+
pub theme: Option<theme::Config>,
2323
pub keys: Option<HashMap<Mode, KeyTrie>>,
2424
pub editor: Option<toml::Value>,
2525
}

helix-tui/src/backend/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,5 @@ pub trait Backend {
3939
/// Flushes the terminal buffer
4040
fn flush(&mut self) -> Result<(), io::Error>;
4141
fn supports_true_color(&self) -> bool;
42+
fn get_theme_mode(&self) -> Option<helix_view::theme::Mode>;
4243
}

helix-tui/src/backend/termina.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::io::{self, Write as _};
22

33
use helix_view::{
44
graphics::{CursorKind, Rect, UnderlineStyle},
5-
theme::{Color, Modifier},
5+
theme::{self, Color, Modifier},
66
};
77
use termina::{
88
escape::{
@@ -67,6 +67,7 @@ struct Capabilities {
6767
synchronized_output: bool,
6868
true_color: bool,
6969
extended_underlines: bool,
70+
theme_mode: Option<theme::Mode>,
7071
}
7172

7273
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
@@ -154,13 +155,15 @@ impl TerminaBackend {
154155
// If we only receive the device attributes then we know it is not.
155156
write!(
156157
terminal,
157-
"{}{}{}{}{}{}{}",
158+
"{}{}{}{}{}{}{}{}",
158159
// Kitty keyboard
159160
Csi::Keyboard(csi::Keyboard::QueryFlags),
160161
// Synchronized output
161162
Csi::Mode(csi::Mode::QueryDecPrivateMode(csi::DecPrivateMode::Code(
162163
csi::DecPrivateModeCode::SynchronizedOutput
163164
))),
165+
// Mode 2031 theme updates. Query the current theme.
166+
Csi::Mode(csi::Mode::QueryTheme),
164167
// True color and while we're at it, extended underlines:
165168
// <https://github.com/termstandard/colors?tab=readme-ov-file#querying-the-terminal>
166169
Csi::Sgr(csi::Sgr::Background(TEST_COLOR.into())),
@@ -192,6 +195,9 @@ impl TerminaBackend {
192195
})) => {
193196
capabilities.synchronized_output = true;
194197
}
198+
Event::Csi(Csi::Mode(csi::Mode::ReportTheme(mode))) => {
199+
capabilities.theme_mode = Some(mode.into());
200+
}
195201
Event::Dcs(dcs::Dcs::Response {
196202
value: dcs::DcsResponse::GraphicRendition(sgrs),
197203
..
@@ -317,6 +323,11 @@ impl TerminaBackend {
317323
}
318324
}
319325

326+
if self.capabilities.theme_mode.is_some() {
327+
// Enable mode 2031 theme mode notifications:
328+
write!(self.terminal, "{}", decset!(Theme))?;
329+
}
330+
320331
Ok(())
321332
}
322333

@@ -329,6 +340,11 @@ impl TerminaBackend {
329340
)?;
330341
}
331342

343+
if self.capabilities.theme_mode.is_some() {
344+
// Mode 2031 theme notifications.
345+
write!(self.terminal, "{}", decreset!(Theme))?;
346+
}
347+
332348
Ok(())
333349
}
334350

@@ -547,6 +563,10 @@ impl Backend for TerminaBackend {
547563
fn supports_true_color(&self) -> bool {
548564
self.capabilities.true_color
549565
}
566+
567+
fn get_theme_mode(&self) -> Option<theme::Mode> {
568+
self.capabilities.theme_mode
569+
}
550570
}
551571

552572
impl Drop for TerminaBackend {

helix-tui/src/backend/test.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,4 +160,8 @@ impl Backend for TestBackend {
160160
fn supports_true_color(&self) -> bool {
161161
false
162162
}
163+
164+
fn get_theme_mode(&self) -> Option<helix_view::theme::Mode> {
165+
None
166+
}
163167
}

helix-view/src/theme.rs

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,75 @@ pub static BASE16_DEFAULT_THEME: Lazy<Theme> = Lazy::new(|| Theme {
3535
..Theme::from(BASE16_DEFAULT_THEME_DATA.clone())
3636
});
3737

38+
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
39+
pub enum Mode {
40+
Dark,
41+
Light,
42+
}
43+
44+
#[cfg(feature = "term")]
45+
impl From<termina::escape::csi::ThemeMode> for Mode {
46+
fn from(mode: termina::escape::csi::ThemeMode) -> Self {
47+
match mode {
48+
termina::escape::csi::ThemeMode::Dark => Self::Dark,
49+
termina::escape::csi::ThemeMode::Light => Self::Light,
50+
}
51+
}
52+
}
53+
54+
#[derive(Debug, Clone, PartialEq, Eq)]
55+
pub struct Config {
56+
pub light: String,
57+
pub dark: String,
58+
/// A theme to choose when the terminal did not declare either light or dark mode.
59+
/// When not specified the dark theme is preferred.
60+
pub no_preference: Option<String>,
61+
}
62+
63+
impl Config {
64+
pub fn choose(&self, preference: Option<Mode>) -> &str {
65+
match preference {
66+
Some(Mode::Light) => &self.light,
67+
Some(Mode::Dark) => &self.dark,
68+
None => self.no_preference.as_ref().unwrap_or(&self.dark),
69+
}
70+
}
71+
}
72+
73+
impl<'de> Deserialize<'de> for Config {
74+
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
75+
where
76+
D: serde::Deserializer<'de>,
77+
{
78+
#[derive(Deserialize)]
79+
#[serde(untagged, deny_unknown_fields, rename_all = "kebab-case")]
80+
enum InnerConfig {
81+
Constant(String),
82+
Adaptive {
83+
dark: String,
84+
light: String,
85+
no_preference: Option<String>,
86+
},
87+
}
88+
89+
let inner = InnerConfig::deserialize(deserializer)?;
90+
91+
let (light, dark, no_preference) = match inner {
92+
InnerConfig::Constant(theme) => (theme.clone(), theme.clone(), None),
93+
InnerConfig::Adaptive {
94+
light,
95+
dark,
96+
no_preference,
97+
} => (light, dark, no_preference),
98+
};
99+
100+
Ok(Self {
101+
light,
102+
dark,
103+
no_preference,
104+
})
105+
}
106+
}
38107
#[derive(Clone, Debug)]
39108
pub struct Loader {
40109
/// Theme directories to search from highest to lowest priority

0 commit comments

Comments
 (0)