on master help sign in
Add ability to change theme on editor
commitce97a2f05fcddf81d8210ec6b25411f8fd7d867a authorwojciechkepka <wojtek.kepka@protonmail.com> dateSat 19 Jun 2021, 13:26 (5 years ago) parentf424a61
10 files changed+240−140
Cargo.lock+7 helix-core/Cargo.toml+1 helix-core/src/indent.rs+17−20 helix-core/src/lib.rs+1−1 helix-core/src/syntax.rs+59−42 helix-term/src/application.rs+37−3 helix-term/src/ui/completion.rs+26−17 helix-term/src/ui/markdown.rs+18−13 helix-view/src/document.rs+25−18 helix-view/src/editor.rs+49−26
Cargo.lock+7
@@ -17,6 +17,12 @@ version = "1.0.41"
1717source = "registry+https://github.com/rust-lang/crates.io-index"
1818checksum = "15af2628f6890fe2609a3b91bef4c83450512802e59489f9c1cb1fa5df064a61"
1919
20+[[package]]
21+name = "arc-swap"
22+version = "1.3.0"
23+source = "registry+https://github.com/rust-lang/crates.io-index"
24+checksum = "e906254e445520903e7fc9da4f709886c84ae4bc4ddaf0e093188d66df4dc820"
25+
2026[[package]]
2127name = "autocfg"
2228version = "1.0.1"
@@ -254,6 +260,7 @@ dependencies = [
254260name = "helix-core"
255261version = "0.2.0"
256262dependencies = [
263+ "arc-swap",
257264 "etcetera",
258265 "helix-syntax",
259266 "once_cell",
helix-core/Cargo.toml+1
@@ -25,6 +25,7 @@ unicode-general-category = "0.4.0"
2525# slab = "0.4.2"
2626tree-sitter = "0.19"
2727once_cell = "1.8"
28+arc-swap = "1"
2829regex = "1"
2930
3031serde = { version = "1.0", features = ["derive"] }
helix-core/src/indent.rs+17−20
@@ -254,26 +254,23 @@ where
254254 Configuration, IndentationConfiguration, Lang, LanguageConfiguration, Loader,
255255 };
256256 use once_cell::sync::OnceCell;
257− let loader = Loader::new(
258− Configuration {
259− language: vec![LanguageConfiguration {
260− scope: "source.rust".to_string(),
261− file_types: vec!["rs".to_string()],
262− language_id: Lang::Rust,
263− highlight_config: OnceCell::new(),
264− //
265− roots: vec![],
266− auto_format: false,
267− language_server: None,
268− indent: Some(IndentationConfiguration {
269− tab_width: 4,
270− unit: String::from(" "),
271− }),
272− indent_query: OnceCell::new(),
273− }],
274− },
275− Vec::new(),
276− );
257+ let loader = Loader::new(Configuration {
258+ language: vec![LanguageConfiguration {
259+ scope: "source.rust".to_string(),
260+ file_types: vec!["rs".to_string()],
261+ language_id: Lang::Rust,
262+ highlight_config: OnceCell::new(),
263+ //
264+ roots: vec![],
265+ auto_format: false,
266+ language_server: None,
267+ indent: Some(IndentationConfiguration {
268+ tab_width: 4,
269+ unit: String::from(" "),
270+ }),
271+ indent_query: OnceCell::new(),
272+ }],
273+ });
277274
278275 // set runtime path so we can find the queries
279276 let mut runtime = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
helix-core/src/lib.rs+1−1
@@ -50,7 +50,7 @@ pub fn find_root(root: Option<&str>) -> Option<std::path::PathBuf> {
5050}
5151
5252#[cfg(not(embed_runtime))]
53−fn runtime_dir() -> std::path::PathBuf {
53+pub fn runtime_dir() -> std::path::PathBuf {
5454 if let Ok(dir) = std::env::var("HELIX_RUNTIME") {
5555 return dir.into();
5656 }
helix-core/src/syntax.rs+59−42
@@ -1,6 +1,8 @@
11use crate::{regex::Regex, Change, Rope, RopeSlice, Transaction};
22pub use helix_syntax::{get_language, get_language_name, Lang};
33
4+use arc_swap::ArcSwap;
5+
46use std::{
57 borrow::Cow,
68 cell::RefCell,
@@ -143,35 +145,48 @@ fn read_query(language: &str, filename: &str) -> String {
143145}
144146
145147impl LanguageConfiguration {
146− pub fn highlight_config(&self, scopes: &[String]) -> Option<Arc<HighlightConfiguration>> {
147− self.highlight_config
148− .get_or_init(|| {
149− let language = get_language_name(self.language_id).to_ascii_lowercase();
148+ fn initialize_highlight(&self, scopes: &[String]) -> Option<Arc<HighlightConfiguration>> {
149+ let language = get_language_name(self.language_id).to_ascii_lowercase();
150150
151− let highlights_query = read_query(&language, "highlights.scm");
152− // always highlight syntax errors
153− // highlights_query += "\n(ERROR) @error";
151+ let highlights_query = read_query(&language, "highlights.scm");
152+ // always highlight syntax errors
153+ // highlights_query += "\n(ERROR) @error";
154154
155− let injections_query = read_query(&language, "injections.scm");
155+ let injections_query = read_query(&language, "injections.scm");
156156
157− let locals_query = "";
157+ let locals_query = "";
158158
159− if highlights_query.is_empty() {
160− None
161− } else {
162− let language = get_language(self.language_id);
163− let mut config = HighlightConfiguration::new(
164− language,
165− &highlights_query,
166− &injections_query,
167− locals_query,
168− )
169− .unwrap(); // TODO: no unwrap
170− config.configure(scopes);
171− Some(Arc::new(config))
172− }
173− })
174− .clone()
159+ if highlights_query.is_empty() {
160+ None
161+ } else {
162+ let language = get_language(self.language_id);
163+ let mut config = HighlightConfiguration::new(
164+ language,
165+ &highlights_query,
166+ &injections_query,
167+ locals_query,
168+ )
169+ .unwrap(); // TODO: no unwrap
170+ config.configure(scopes);
171+ Some(Arc::new(config))
172+ }
173+ }
174+
175+ pub fn highlight_config(&self, scopes: &[String]) -> Option<Arc<HighlightConfiguration>> {
176+ if let Some(config) = self.highlight_config.get() {
177+ if let Some(config) = config {
178+ config.configure(scopes);
179+ }
180+ config.clone()
181+ } else {
182+ self.highlight_config
183+ .get_or_init(|| self.initialize_highlight(scopes))
184+ .clone()
185+ }
186+ }
187+
188+ pub fn is_highlight_initialized(&self) -> bool {
189+ self.highlight_config.get().is_some()
175190 }
176191
177192 pub fn indent_query(&self) -> Option<&IndentQuery> {
@@ -190,22 +205,18 @@ impl LanguageConfiguration {
190205 }
191206}
192207
193−pub static LOADER: OnceCell<Loader> = OnceCell::new();
194−
195208#[derive(Debug)]
196209pub struct Loader {
197210 // highlight_names ?
198211 language_configs: Vec<Arc<LanguageConfiguration>>,
199212 language_config_ids_by_file_type: HashMap<String, usize>, // Vec<usize>
200− scopes: Vec<String>,
201213}
202214
203215impl Loader {
204− pub fn new(config: Configuration, scopes: Vec<String>) -> Self {
216+ pub fn new(config: Configuration) -> Self {
205217 let mut loader = Self {
206218 language_configs: Vec::new(),
207219 language_config_ids_by_file_type: HashMap::new(),
208− scopes,
209220 };
210221
211222 for config in config.language {
@@ -225,10 +236,6 @@ impl Loader {
225236 loader
226237 }
227238
228− pub fn scopes(&self) -> &[String] {
229− &self.scopes
230− }
231−
232239 pub fn language_config_for_file_name(&self, path: &Path) -> Option<Arc<LanguageConfiguration>> {
233240 // Find all the language configurations that match this file name
234241 // or a suffix of the file name.
@@ -253,6 +260,10 @@ impl Loader {
253260 .find(|config| config.scope == scope)
254261 .cloned()
255262 }
263+
264+ pub fn language_configs_iter(&self) -> impl Iterator<Item = &Arc<LanguageConfiguration>> {
265+ self.language_configs.iter()
266+ }
256267}
257268
258269pub struct TsParser {
@@ -771,7 +782,7 @@ pub struct HighlightConfiguration {
771782 combined_injections_query: Option<Query>,
772783 locals_pattern_index: usize,
773784 highlights_pattern_index: usize,
774− highlight_indices: Vec<Option<Highlight>>,
785+ highlight_indices: ArcSwap<Vec<Option<Highlight>>>,
775786 non_local_variable_patterns: Vec<bool>,
776787 injection_content_capture_index: Option<u32>,
777788 injection_language_capture_index: Option<u32>,
@@ -923,7 +934,7 @@ impl HighlightConfiguration {
923934 }
924935 }
925936
926− let highlight_indices = vec![None; query.capture_names().len()];
937+ let highlight_indices = ArcSwap::from_pointee(vec![None; query.capture_names().len()]);
927938 Ok(Self {
928939 language,
929940 query,
@@ -956,17 +967,20 @@ impl HighlightConfiguration {
956967 ///
957968 /// When highlighting, results are returned as `Highlight` values, which contain the index
958969 /// of the matched highlight this list of highlight names.
959− pub fn configure(&mut self, recognized_names: &[String]) {
970+ pub fn configure(&self, recognized_names: &[String]) {
960971 let mut capture_parts = Vec::new();
961− self.highlight_indices.clear();
962− self.highlight_indices
963− .extend(self.query.capture_names().iter().map(move |capture_name| {
972+ let indices: Vec<_> = self
973+ .query
974+ .capture_names()
975+ .iter()
976+ .map(move |capture_name| {
964977 capture_parts.clear();
965978 capture_parts.extend(capture_name.split('.'));
966979
967980 let mut best_index = None;
968981 let mut best_match_len = 0;
969982 for (i, recognized_name) in recognized_names.iter().enumerate() {
983+ let recognized_name = recognized_name;
970984 let mut len = 0;
971985 let mut matches = true;
972986 for part in recognized_name.split('.') {
@@ -982,7 +996,10 @@ impl HighlightConfiguration {
982996 }
983997 }
984998 best_index.map(Highlight)
985− }));
999+ })
1000+ .collect();
1001+
1002+ self.highlight_indices.store(Arc::new(indices));
9861003 }
9871004}
9881005
@@ -1561,7 +1578,7 @@ where
15611578 }
15621579 }
15631580
1564− let current_highlight = layer.config.highlight_indices[capture.index as usize];
1581+ let current_highlight = layer.config.highlight_indices.load()[capture.index as usize];
15651582
15661583 // If this node represents a local definition, then store the current
15671584 // highlight value on the local scope entry representing this node.
helix-term/src/application.rs+37−3
@@ -1,5 +1,6 @@
1+use helix_core::syntax;
12use helix_lsp::{lsp, LspProgressMap};
2−use helix_view::{document::Mode, Document, Editor, Theme, View};
3+use helix_view::{document::Mode, theme, Document, Editor, Theme, View};
34
45use crate::{args::Args, compositor::Compositor, config::Config, keymap::Keymaps, ui};
56
@@ -14,7 +15,7 @@ use std::{
1415 time::Duration,
1516};
1617
17−use anyhow::Error;
18+use anyhow::{Context, Error};
1819
1920use crossterm::{
2021 event::{Event, EventStream},
@@ -36,6 +37,8 @@ pub struct Application {
3637 compositor: Compositor,
3738 editor: Editor,
3839
40+ theme_loader: Arc<theme::Loader>,
41+ syn_loader: Arc<syntax::Loader>,
3942 callbacks: LspCallbacks,
4043
4144 lsp_progress: LspProgressMap,
@@ -47,7 +50,34 @@ impl Application {
4750 use helix_view::editor::Action;
4851 let mut compositor = Compositor::new()?;
4952 let size = compositor.size();
50− let mut editor = Editor::new(size);
53+
54+ let conf_dir = helix_core::config_dir();
55+
56+ let theme_loader =
57+ std::sync::Arc::new(theme::Loader::new(&conf_dir, &helix_core::runtime_dir()));
58+
59+ // load $HOME/.config/helix/languages.toml, fallback to default config
60+ let lang_conf = std::fs::read(conf_dir.join("languages.toml"));
61+ let lang_conf = lang_conf
62+ .as_deref()
63+ .unwrap_or(include_bytes!("../../languages.toml"));
64+
65+ let theme = if let Some(theme) = &config.global.theme {
66+ match theme_loader.load(theme) {
67+ Ok(theme) => theme,
68+ Err(e) => {
69+ log::warn!("failed to load theme `{}` - {}", theme, e);
70+ theme_loader.default()
71+ }
72+ }
73+ } else {
74+ theme_loader.default()
75+ };
76+
77+ let syn_loader_conf = toml::from_slice(lang_conf).expect("Could not parse languages.toml");
78+ let syn_loader = std::sync::Arc::new(syntax::Loader::new(syn_loader_conf));
79+
80+ let mut editor = Editor::new(size, theme_loader.clone(), syn_loader.clone());
5181
5282 let mut editor_view = Box::new(ui::EditorView::new(config.keymaps));
5383 compositor.push(editor_view);
@@ -72,10 +102,14 @@ impl Application {
72102 editor.new_file(Action::VerticalSplit);
73103 }
74104
105+ editor.set_theme(theme);
106+
75107 let mut app = Self {
76108 compositor,
77109 editor,
78110
111+ theme_loader,
112+ syn_loader,
79113 callbacks: FuturesUnordered::new(),
80114 lsp_progress: LspProgressMap::new(),
81115 lsp_progress_enabled: config.global.lsp_progress,
helix-term/src/ui/completion.rs+26−17
@@ -246,34 +246,43 @@ impl Component for Completion {
246246 value: contents,
247247 })) => {
248248 // TODO: convert to wrapped text
249− Markdown::new(format!(
250− "```{}\n{}\n```\n{}",
251− language,
252− option.detail.as_deref().unwrap_or_default(),
253− contents.clone()
254− ))
249+ Markdown::new(
250+ format!(
251+ "```{}\n{}\n```\n{}",
252+ language,
253+ option.detail.as_deref().unwrap_or_default(),
254+ contents.clone()
255+ ),
256+ cx.editor.syn_loader.clone(),
257+ )
255258 }
256259 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent {
257260 kind: lsp::MarkupKind::Markdown,
258261 value: contents,
259262 })) => {
260263 // TODO: set language based on doc scope
261− Markdown::new(format!(
262− "```{}\n{}\n```\n{}",
263− language,
264− option.detail.as_deref().unwrap_or_default(),
265− contents.clone()
266− ))
264+ Markdown::new(
265+ format!(
266+ "```{}\n{}\n```\n{}",
267+ language,
268+ option.detail.as_deref().unwrap_or_default(),
269+ contents.clone()
270+ ),
271+ cx.editor.syn_loader.clone(),
272+ )
267273 }
268274 None if option.detail.is_some() => {
269275 // TODO: copied from above
270276
271277 // TODO: set language based on doc scope
272− Markdown::new(format!(
273− "```{}\n{}\n```",
274− language,
275− option.detail.as_deref().unwrap_or_default(),
276− ))
278+ Markdown::new(
279+ format!(
280+ "```{}\n{}\n```",
281+ language,
282+ option.detail.as_deref().unwrap_or_default(),
283+ ),
284+ cx.editor.syn_loader.clone(),
285+ )
277286 }
278287 None => return,
279288 };
helix-term/src/ui/markdown.rs+18−13
@@ -7,25 +7,34 @@ use tui::{
77 text::Text,
88};
99
10−use std::borrow::Cow;
10+use std::{borrow::Cow, sync::Arc};
1111
12−use helix_core::Position;
12+use helix_core::{syntax, Position};
1313use helix_view::{Editor, Theme};
1414
1515pub struct Markdown {
1616 contents: String,
17+
18+ config_loader: Arc<syntax::Loader>,
1719}
1820
1921// TODO: pre-render and self reference via Pin
2022// better yet, just use Tendril + subtendril for references
2123
2224impl Markdown {
23− pub fn new(contents: String) -> Self {
24− Self { contents }
25+ pub fn new(contents: String, config_loader: Arc<syntax::Loader>) -> Self {
26+ Self {
27+ contents,
28+ config_loader,
29+ }
2530 }
2631}
2732
28−fn parse<'a>(contents: &'a str, theme: Option<&Theme>) -> tui::text::Text<'a> {
33+fn parse<'a>(
34+ contents: &'a str,
35+ theme: Option<&Theme>,
36+ loader: &syntax::Loader,
37+) -> tui::text::Text<'a> {
2938 use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag};
3039 use tui::text::{Span, Spans, Text};
3140
@@ -79,9 +88,7 @@ fn parse<'a>(contents: &'a str, theme: Option<&Theme>) -> tui::text::Text<'a> {
7988 use helix_core::Rope;
8089
8190 let rope = Rope::from(text.as_ref());
82− let syntax = syntax::LOADER
83− .get()
84− .unwrap()
91+ let syntax = loader
8592 .language_config_for_scope(&format!("source.{}", language))
8693 .and_then(|config| config.highlight_config(theme.scopes()))
8794 .map(|config| Syntax::new(&rope, config));
@@ -101,9 +108,7 @@ fn parse<'a>(contents: &'a str, theme: Option<&Theme>) -> tui::text::Text<'a> {
101108 }
102109 HighlightEvent::Source { start, end } => {
103110 let style = match highlights.first() {
104− Some(span) => {
105− theme.get(theme.scopes()[span.0].as_str())
106− }
111+ Some(span) => theme.get(&theme.scopes()[span.0]),
107112 None => text_style,
108113 };
109114
@@ -196,7 +201,7 @@ impl Component for Markdown {
196201 fn render(&self, area: Rect, surface: &mut Surface, cx: &mut Context) {
197202 use tui::widgets::{Paragraph, Widget, Wrap};
198203
199− let text = parse(&self.contents, Some(&cx.editor.theme));
204+ let text = parse(&self.contents, Some(&cx.editor.theme), &self.config_loader);
200205
201206 let par = Paragraph::new(text)
202207 .wrap(Wrap { trim: false })
@@ -207,7 +212,7 @@ impl Component for Markdown {
207212 }
208213
209214 fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
210− let contents = parse(&self.contents, None);
215+ let contents = parse(&self.contents, None, &self.config_loader);
211216 let padding = 2;
212217 let width = std::cmp::min(contents.width() as u16 + padding, viewport.0);
213218 let height = std::cmp::min(contents.height() as u16 + padding, viewport.1);
helix-view/src/document.rs+25−18
@@ -9,11 +9,11 @@ use std::sync::Arc;
99use helix_core::{
1010 chars::{char_is_linebreak, char_is_whitespace},
1111 history::History,
12− syntax::{LanguageConfiguration, LOADER},
12+ syntax::{self, LanguageConfiguration},
1313 ChangeSet, Diagnostic, Rope, Selection, State, Syntax, Transaction,
1414};
1515
16−use crate::{DocumentId, ViewId};
16+use crate::{DocumentId, Theme, ViewId};
1717
1818use std::collections::HashMap;
1919
@@ -236,7 +236,11 @@ impl Document {
236236 }
237237
238238 // TODO: async fn?
239− pub fn load(path: PathBuf) -> Result<Self, Error> {
239+ pub fn load(
240+ path: PathBuf,
241+ theme: Option<&Theme>,
242+ config_loader: Option<&syntax::Loader>,
243+ ) -> Result<Self, Error> {
240244 use std::{fs::File, io::BufReader};
241245
242246 let doc = if !path.exists() {
@@ -256,6 +260,10 @@ impl Document {
256260 doc.set_path(&path)?;
257261 doc.detect_indent_style();
258262
263+ if let Some(loader) = config_loader {
264+ doc.detect_language(theme, loader);
265+ }
266+
259267 Ok(doc)
260268 }
261269
@@ -330,12 +338,10 @@ impl Document {
330338 }
331339 }
332340
333− fn detect_language(&mut self) {
334− if let Some(path) = self.path() {
335− let loader = LOADER.get().unwrap();
336− let language_config = loader.language_config_for_file_name(path);
337− let scopes = loader.scopes();
338− self.set_language(language_config, scopes);
341+ pub fn detect_language(&mut self, theme: Option<&Theme>, config_loader: &syntax::Loader) {
342+ if let Some(path) = &self.path {
343+ let language_config = config_loader.language_config_for_file_name(path);
344+ self.set_language(theme, language_config);
339345 }
340346 }
341347
@@ -472,18 +478,16 @@ impl Document {
472478 // and error out when document is saved
473479 self.path = Some(path);
474480
475− // try detecting the language based on filepath
476− self.detect_language();
477−
478481 Ok(())
479482 }
480483
481484 pub fn set_language(
482485 &mut self,
486+ theme: Option<&Theme>,
483487 language_config: Option<Arc<helix_core::syntax::LanguageConfiguration>>,
484− scopes: &[String],
485488 ) {
486489 if let Some(language_config) = language_config {
490+ let scopes = theme.map(|theme| theme.scopes()).unwrap_or(&[]);
487491 if let Some(highlight_config) = language_config.highlight_config(scopes) {
488492 let syntax = Syntax::new(&self.text, highlight_config);
489493 self.syntax = Some(syntax);
@@ -497,12 +501,15 @@ impl Document {
497501 };
498502 }
499503
500− pub fn set_language2(&mut self, scope: &str) {
501− let loader = LOADER.get().unwrap();
502− let language_config = loader.language_config_for_scope(scope);
503− let scopes = loader.scopes();
504+ pub fn set_language2(
505+ &mut self,
506+ scope: &str,
507+ theme: Option<&Theme>,
508+ config_loader: Arc<syntax::Loader>,
509+ ) {
510+ let language_config = config_loader.language_config_for_scope(scope);
504511
505− self.set_language(language_config, scopes);
512+ self.set_language(theme, language_config);
506513 }
507514
508515 pub fn set_language_server(&mut self, language_server: Option<Arc<helix_lsp::Client>>) {
helix-view/src/editor.rs+49−26
@@ -1,10 +1,14 @@
1−use crate::{theme::Theme, tree::Tree, Document, DocumentId, RegisterSelection, View, ViewId};
1+use crate::{
2+ theme::{self, Theme},
3+ tree::Tree,
4+ Document, DocumentId, RegisterSelection, View, ViewId,
5+};
6+use helix_core::syntax;
27use tui::layout::Rect;
38use tui::terminal::CursorKind;
49
510use futures_util::future;
6−use std::path::PathBuf;
7−use std::time::Duration;
11+use std::{path::PathBuf, sync::Arc, time::Duration};
812
913use slotmap::SlotMap;
1014
@@ -24,6 +28,9 @@ pub struct Editor {
2428 pub theme: Theme,
2529 pub language_servers: helix_lsp::Registry,
2630
31+ pub syn_loader: Arc<syntax::Loader>,
32+ pub theme_loader: Arc<theme::Loader>,
33+
2734 pub status_msg: Option<(String, Severity)>,
2835}
2936
@@ -35,27 +42,11 @@ pub enum Action {
3542}
3643
3744impl Editor {
38− pub fn new(mut area: tui::layout::Rect) -> Self {
39− use helix_core::config_dir;
40− let config = std::fs::read(config_dir().join("theme.toml"));
41− // load $HOME/.config/helix/theme.toml, fallback to default config
42− let toml = config
43− .as_deref()
44− .unwrap_or(include_bytes!("../../theme.toml"));
45− let theme: Theme = toml::from_slice(toml).expect("failed to parse theme.toml");
46−
47− // initialize language registry
48− use helix_core::syntax::{Loader, LOADER};
49−
50− // load $HOME/.config/helix/languages.toml, fallback to default config
51− let config = std::fs::read(helix_core::config_dir().join("languages.toml"));
52− let toml = config
53− .as_deref()
54− .unwrap_or(include_bytes!("../../languages.toml"));
55−
56− let config = toml::from_slice(toml).expect("Could not parse languages.toml");
57− LOADER.get_or_init(|| Loader::new(config, theme.scopes().to_vec()));
58−
45+ pub fn new(
46+ mut area: tui::layout::Rect,
47+ themes: Arc<theme::Loader>,
48+ config_loader: Arc<syntax::Loader>,
49+ ) -> Self {
5950 let language_servers = helix_lsp::Registry::new();
6051
6152 // HAXX: offset the render area height by 1 to account for prompt/commandline
@@ -66,8 +57,10 @@ impl Editor {
6657 documents: SlotMap::with_key(),
6758 count: None,
6859 selected_register: RegisterSelection::default(),
69− theme,
60+ theme: themes.default(),
7061 language_servers,
62+ syn_loader: config_loader,
63+ theme_loader: themes,
7164 registers: Registers::default(),
7265 status_msg: None,
7366 }
@@ -85,6 +78,32 @@ impl Editor {
8578 self.status_msg = Some((error, Severity::Error));
8679 }
8780
81+ pub fn set_theme(&mut self, theme: Theme) {
82+ let scopes = theme.scopes();
83+ for config in self
84+ .syn_loader
85+ .language_configs_iter()
86+ .filter(|cfg| cfg.is_highlight_initialized())
87+ {
88+ config.highlight_config(scopes);
89+ }
90+
91+ self.theme = theme;
92+ self._refresh();
93+ }
94+
95+ pub fn set_theme_from_name(&mut self, theme: &str) {
96+ let theme = match self.theme_loader.load(theme.as_ref()) {
97+ Ok(theme) => theme,
98+ Err(e) => {
99+ log::warn!("failed setting theme `{}` - {}", theme, e);
100+ return;
101+ }
102+ };
103+
104+ self.set_theme(theme);
105+ }
106+
88107 fn _refresh(&mut self) {
89108 for (view, _) in self.tree.views_mut() {
90109 let doc = &self.documents[view.doc];
@@ -168,7 +187,7 @@ impl Editor {
168187 let id = if let Some(id) = id {
169188 id
170189 } else {
171− let mut doc = Document::load(path)?;
190+ let mut doc = Document::load(path, Some(&self.theme), Some(&self.syn_loader))?;
172191
173192 // try to find a language server based on the language name
174193 let language_server = doc
@@ -254,6 +273,10 @@ impl Editor {
254273 self.documents.iter().map(|(_id, doc)| doc)
255274 }
256275
276+ pub fn documents_mut(&mut self) -> impl Iterator<Item = &mut Document> {
277+ self.documents.iter_mut().map(|(_id, doc)| doc)
278+ }
279+
257280 // pub fn current_document(&self) -> Document {
258281 // let id = self.view().doc;
259282 // let doc = &mut editor.documents[id];