Syntax highlighting while editing

This commit is contained in:
Jeremy Soller 2022-10-26 19:31:33 -06:00
parent 3444b30d7e
commit 846c646043
2 changed files with 108 additions and 90 deletions

View file

@ -1,9 +1,12 @@
// SPDX-License-Identifier: MIT OR Apache-2.0
use cosmic_text::{Attrs, AttrsList, Color, Family, FontSystem, Style, SwashCache,
TextAction, TextBuffer, TextBufferLine, TextMetrics, Weight};
TextAction, TextBuffer, TextMetrics, Weight};
use orbclient::{EventOption, Renderer, Window, WindowFlag};
use std::{env, fs, process, time::Instant};
use syntect::easy::HighlightLines;
use syntect::parsing::SyntaxSet;
use syntect::highlighting::{ThemeSet, FontStyle, Style as SyntectStyle};
fn main() {
env_logger::init();
@ -57,108 +60,107 @@ fn main() {
window.height() as i32
);
buffer.set_text(&text);
let mut bg_color = orbclient::Color::rgb(0x00, 0x00, 0x00);
let mut font_color = orbclient::Color::rgb(0xFF, 0xFF, 0xFF);
{
use syntect::easy::HighlightLines;
use syntect::parsing::SyntaxSet;
use syntect::highlighting::{ThemeSet, FontStyle, Style as SyntectStyle};
use syntect::util::LinesWithEndings;
let now = Instant::now();
let now = Instant::now();
// Load these once at the start of your program
let ps = SyntaxSet::load_defaults_newlines();
let ts = ThemeSet::load_defaults();
let theme = &ts.themes["base16-eighties.dark"];
//TODO: store newlines in buffer
let ps = SyntaxSet::load_defaults_nonewlines();
let ts = ThemeSet::load_defaults();
let theme = &ts.themes["base16-eighties.dark"];
if let Some(background) = theme.settings.background {
bg_color = orbclient::Color::rgba(
background.r,
background.g,
background.b,
background.a,
);
}
if let Some(foreground) = theme.settings.foreground {
font_color = orbclient::Color::rgba(
foreground.r,
foreground.g,
foreground.b,
foreground.a,
);
}
let syntax = match ps.find_syntax_for_file(&path) {
Ok(Some(some)) => some,
Ok(None) => {
log::warn!("no syntax found for {:?}", path);
ps.find_syntax_plain_text()
}
Err(err) => {
log::warn!("failed to determine syntax for {:?}: {:?}", path, err);
ps.find_syntax_plain_text()
}
};
log::info!("using syntax {:?}", syntax.name);
buffer.lines.clear();
let mut h = HighlightLines::new(syntax, &theme);
for highlight_line in LinesWithEndings::from(&text) { // LinesWithEndings enables use of newlines mode
let ranges: Vec<(SyntectStyle, &str)> = h.highlight_line(highlight_line, &ps).unwrap();
let mut line_text = String::new();
let mut attrs_list = AttrsList::new(attrs);
for (style, string) in ranges.iter() {
let string_trim = match string.lines().next() {
Some(some) => some,
None => continue,
};
let start = line_text.len();
line_text.push_str(string_trim);
let end = line_text.len();
attrs_list.add_span(
start,
end,
attrs
.color(Color::rgba(
style.foreground.r,
style.foreground.g,
style.foreground.b,
style.foreground.a,
))
//TODO: background
.style(if style.font_style.contains(FontStyle::ITALIC) {
Style::Italic
} else {
Style::Normal
})
.weight(if style.font_style.contains(FontStyle::BOLD) {
Weight::BOLD
} else {
Weight::NORMAL
})
//TODO: underline
);
}
buffer.lines.push(TextBufferLine::new(line_text, attrs_list));
}
let elapsed = now.elapsed();
log::info!("Syntax highlighted in {:?}", elapsed);
if let Some(background) = theme.settings.background {
bg_color = orbclient::Color::rgba(
background.r,
background.g,
background.b,
background.a,
);
}
if let Some(foreground) = theme.settings.foreground {
font_color = orbclient::Color::rgba(
foreground.r,
foreground.g,
foreground.b,
foreground.a,
);
}
let syntax = match ps.find_syntax_for_file(&path) {
Ok(Some(some)) => some,
Ok(None) => {
log::warn!("no syntax found for {:?}", path);
ps.find_syntax_plain_text()
}
Err(err) => {
log::warn!("failed to determine syntax for {:?}: {:?}", path, err);
ps.find_syntax_plain_text()
}
};
log::info!("using syntax {:?}, loaded in {:?}", syntax.name, now.elapsed());
let mut swash_cache = SwashCache::new(&font_system);
//TODO: make window not async?
let mut rehighlight = true;
let mut mouse_x = -1;
let mut mouse_y = -1;
let mut mouse_left = false;
loop {
if rehighlight {
let now = Instant::now();
let mut h = HighlightLines::new(syntax, &theme);
for line in buffer.lines.iter_mut() {
let ranges: Vec<(SyntectStyle, &str)> = h.highlight_line(
line.text(),
&ps
).unwrap();
let mut start = 0;
let mut attrs_list = AttrsList::new(attrs);
for (style, string) in ranges.iter() {
let end = start + string.len();
attrs_list.add_span(
start,
end,
attrs
.color(Color::rgba(
style.foreground.r,
style.foreground.g,
style.foreground.b,
style.foreground.a,
))
//TODO: background
.style(if style.font_style.contains(FontStyle::ITALIC) {
Style::Italic
} else {
Style::Normal
})
.weight(if style.font_style.contains(FontStyle::BOLD) {
Weight::BOLD
} else {
Weight::NORMAL
})
//TODO: underline
);
start = end;
}
line.attrs_list = attrs_list;
line.reset();
}
rehighlight = false;
log::info!("Syntax highlighted in {:?}", now.elapsed());
}
if buffer.cursor_moved {
buffer.shape_until_cursor();
buffer.cursor_moved = false;
@ -194,8 +196,24 @@ fn main() {
orbclient::K_END if event.pressed => buffer.action(TextAction::End),
orbclient::K_PGUP if event.pressed => buffer.action(TextAction::PageUp),
orbclient::K_PGDN if event.pressed => buffer.action(TextAction::PageDown),
orbclient::K_ENTER if event.pressed => {
buffer.action(TextAction::Enter);
rehighlight = true;
},
orbclient::K_BKSP if event.pressed => {
buffer.action(TextAction::Backspace);
rehighlight = true;
},
orbclient::K_DEL if event.pressed => {
buffer.action(TextAction::Delete);
rehighlight = true;
},
_ => (),
},
EventOption::TextInput(event) => {
buffer.action(TextAction::Insert(event.character));
rehighlight = true;
},
EventOption::Mouse(event) => {
mouse_x = event.x;
mouse_y = event.y;

View file

@ -175,7 +175,7 @@ impl fmt::Display for TextMetrics {
pub struct TextBufferLine<'a> {
text: String,
attrs_list: AttrsList<'a>,
pub attrs_list: AttrsList<'a>,
shape_opt: Option<ShapeLine>,
layout_opt: Option<Vec<LayoutLine>>,
}