[Perf] add comments for highlight logic

pull/90/head
Mist 2024-04-25 15:49:44 +08:00 committed by The Mist
parent 2ff1247b2b
commit 13d7118c06
2 changed files with 35 additions and 25 deletions

View File

@ -10,6 +10,8 @@ fn min_width(width: f32) -> f32 {
}
}
// Because the code block is input by users, we need to calculate the width and height
// to make sure render the width and height of the "editor" shape correctly
pub fn calc_wh(text: &str, char_wdith: f32, line_height: f32) -> (f32, f32) {
let trimmed_text = prepare_code(text);
let lines = trimmed_text.lines();
@ -41,22 +43,20 @@ fn trim_space(text: &str) -> String {
let head_spaces = Regex::new(r"^(\s*)").unwrap().find(first_line);
match head_spaces {
Some(head_spaces) => {
return lines
.into_iter()
.map(|line| {
Regex::new(format!("^{}", head_spaces.as_str()).as_ref())
.unwrap()
.replace(line, "")
.to_string()
})
.collect::<Vec<String>>()
.join("\n");
}
Some(head_spaces) => lines
.into_iter()
.map(|line| {
Regex::new(format!("^{}", head_spaces.as_str()).as_ref())
.unwrap()
.replace(line, "")
.to_string()
})
.collect::<Vec<String>>()
.join("\n"),
None => text.to_string(),
}
}
pub fn prepare_code(code: &str) -> String {
replace_tab_to_space(&trim_space(&code))
trim_space(&replace_tab_to_space(&code))
}

View File

@ -53,6 +53,9 @@ impl Highlight {
))?,
};
// The Syntect clearly distinguish between PHP and PHP Source
// Should use PHP as highlight language if the source content contains "<php" tag
// Should use PHP Source as highlight language if the source content not contains "<php" tag
if let Some(identifier) = self.highlighting_language_source_map.get(&syntax.name[..]) {
if !self.content.contains(identifier) {
return Ok(syntax_set
@ -77,21 +80,28 @@ impl Highlight {
let mut highlight = HighlightLines::new(syntax, &theme_set.themes[theme]);
let attrs = Attrs::new().family(Family::Name(self.font_family.as_ref()));
// Highlight the content line by line using highlight_line function
Ok(LinesWithEndings::from(&self.content)
.map(|line| highlight.highlight_line(line, &syntax_set).unwrap())
.map(|line| {
highlight
.highlight_line(line, &syntax_set)
.unwrap()
.into_iter()
.map(|(style, str)| {
let syntect::highlighting::Color { r, g, b, a: _ } = style.foreground;
let attrs = match style.font_style {
FontStyle::BOLD => attrs.weight(Weight::BOLD),
FontStyle::ITALIC => attrs.style(Style::Italic),
FontStyle::UNDERLINE => attrs.style(Style::Normal),
_ => attrs,
};
(str, attrs.color(cosmic_text::Color::rgb(r, g, b)))
})
.collect::<HighlightResult>()
})
.fold(vec![], |acc, cur| [acc, cur].concat())
.into_iter()
.map(move |(style, str)| {
let syntect::highlighting::Color { r, g, b, a: _ } = style.foreground;
let attrs = match style.font_style {
FontStyle::BOLD => attrs.weight(Weight::BOLD),
FontStyle::ITALIC => attrs.style(Style::Italic),
FontStyle::UNDERLINE => attrs.style(Style::Normal),
_ => attrs,
};
(str, attrs.color(cosmic_text::Color::rgb(r, g, b)))
})
.collect::<HighlightResult>())
}
}