| 1 |
use std::borrow::Cow; |
| 2 |
use std::collections::HashMap; |
| 3 |
use std::io::Write; |
| 4 |
|
| •5 |
use ansi_term::AnsiString; |
| 6 |
use itertools::Itertools; |
| 7 |
use syntect::easy::HighlightLines; |
| 8 |
use syntect::highlighting::Style as SyntectStyle; |
| 9 |
use syntect::parsing::{SyntaxReference, SyntaxSet}; |
| 10 |
|
| 11 |
use crate::config::{self, delta_unreachable, Config}; |
| 12 |
use crate::delta::{DiffType, InMergeConflict, MergeParents, State}; |
| 13 |
use crate::features::hyperlinks; |
| 14 |
use crate::features::line_numbers::{self, LineNumbersData}; |
| 15 |
use crate::features::side_by_side::ansifill; |
| 16 |
use crate::features::side_by_side::{self, PanelSide}; |
| 17 |
use crate::handlers::merge_conflict; |
| 18 |
use crate::minusplus::*; |
| 19 |
use crate::paint::superimpose_style_sections::superimpose_style_sections; |
| 20 |
use crate::style::Style; |
| 21 |
use crate::{ansi, style}; |
| 22 |
use crate::{edits, utils, utils::tabs}; |
| 23 |
|
| 24 |
pub type LineSections<'a, S> = Vec<(S, &'a str)>; |
| 25 |
|
| 26 |
pub struct Painter<'p> { |
| 27 |
pub minus_lines: Vec<(String, State)>, |
| 28 |
pub plus_lines: Vec<(String, State)>, |
| 29 |
pub writer: &'p mut dyn Write, |
| 30 |
pub syntax: &'p SyntaxReference, |
| 31 |
pub highlighter: Option<HighlightLines<'p>>, |
| 32 |
pub config: &'p config::Config, |
| 33 |
pub output_buffer: String, |
| 34 |
// If config.line_numbers is true, then the following is always Some(). |
| 35 |
// In side-by-side mode it is always Some (but possibly an empty one), even |
| 36 |
// if config.line_numbers is false. See `UseFullPanelWidth` as well. |
| 37 |
pub line_numbers_data: Option<line_numbers::LineNumbersData<'p>>, |
| 38 |
pub merge_conflict_lines: merge_conflict::MergeConflictLines, |
| 39 |
pub merge_conflict_commit_names: merge_conflict::MergeConflictCommitNames, |
| 40 |
} |
| 41 |
|
| 42 |
// How the background of a line is filled up to the end |
| 43 |
#[derive(Debug, PartialEq, Eq, Clone, Copy)] |
| 44 |
pub enum BgFillMethod { |
| 45 |
// Fill the background with ANSI spaces if possible, |
| 46 |
// but might fallback to Spaces (e.g. in the left side-by-side panel), |
| 47 |
// also see `UseFullPanelWidth` |
| 48 |
TryAnsiSequence, |
| 49 |
Spaces, |
| 50 |
} |
| 51 |
|
| 52 |
// If the background of a line extends to the end, and if configured to do so, how. |
| 53 |
#[derive(Debug, PartialEq, Eq, Clone, Copy)] |
| 54 |
pub enum BgShouldFill { |
| 55 |
With(BgFillMethod), |
| 56 |
No, |
| 57 |
} |
| 58 |
|
| 59 |
impl Default for BgShouldFill { |
| 60 |
fn default() -> Self { |
| 61 |
BgShouldFill::With(BgFillMethod::TryAnsiSequence) |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
#[derive(PartialEq, Debug)] |
| 66 |
pub enum StyleSectionSpecifier<'l> { |
| 67 |
Style(Style), |
| 68 |
StyleSections(LineSections<'l, Style>), |
| 69 |
} |
| 70 |
|
| 71 |
impl<'p> Painter<'p> { |
| 72 |
pub fn new(writer: &'p mut dyn Write, config: &'p config::Config) -> Self { |
| 73 |
let default_syntax = Self::get_syntax(&config.syntax_set, None, &config.default_language); |
| 74 |
let panel_width_fix = ansifill::UseFullPanelWidth::new(config); |
| 75 |
|
| 76 |
let line_numbers_data = if config.line_numbers { |
| 77 |
Some(line_numbers::LineNumbersData::from_format_strings( |
| 78 |
&config.line_numbers_format, |
| 79 |
panel_width_fix, |
| 80 |
)) |
| 81 |
} else if config.side_by_side { |
| 82 |
// If line numbers are disabled in side-by-side then the data is still used |
| 83 |
// for width calculation and to pad odd width to even, see `UseFullPanelWidth` |
| 84 |
// for details. |
| 85 |
Some(line_numbers::LineNumbersData::empty_for_sbs( |
| 86 |
panel_width_fix, |
| 87 |
)) |
| 88 |
} else { |
| 89 |
None |
| 90 |
}; |
| 91 |
Self { |
| 92 |
minus_lines: Vec::new(), |
| 93 |
plus_lines: Vec::new(), |
| 94 |
output_buffer: String::new(), |
| 95 |
syntax: default_syntax, |
| 96 |
highlighter: None, |
| 97 |
writer, |
| 98 |
config, |
| 99 |
line_numbers_data, |
| 100 |
merge_conflict_lines: merge_conflict::MergeConflictLines::new(), |
| 101 |
merge_conflict_commit_names: merge_conflict::MergeConflictCommitNames::new(), |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
pub fn set_syntax(&mut self, filename: Option<&str>) { |
| 106 |
self.syntax = Painter::get_syntax( |
| 107 |
&self.config.syntax_set, |
| 108 |
filename, |
| 109 |
&self.config.default_language, |
| 110 |
); |
| 111 |
} |
| 112 |
|
| 113 |
fn get_syntax<'a>( |
| 114 |
syntax_set: &'a SyntaxSet, |
| 115 |
filename: Option<&str>, |
| 116 |
fallback: &str, |
| 117 |
) -> &'a SyntaxReference { |
| 118 |
if let Some(filename) = filename { |
| 119 |
let path = std::path::Path::new(filename); |
| 120 |
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); |
| 121 |
let extension = path.extension().and_then(|x| x.to_str()).unwrap_or(""); |
| 122 |
|
| 123 |
// Like syntect's `find_syntax_for_file`, without inspecting the file content, plus: |
| 124 |
// If the file has NO extension then look up the whole filename as a |
| 125 |
// syntax definition (if it is longer than 4 bytes). |
| 126 |
// This means file formats like Makefile/Dockerfile/Rakefile etc. will get highlighted, |
| 127 |
// but 1-4 short filenames will not -- even if they, as a whole, match an extension: |
| 128 |
// 'rs' will not get highlighted, while 'x.rs' will. |
| 129 |
if !extension.is_empty() || file_name.len() > 4 { |
| 130 |
if let Some(syntax) = syntax_set |
| 131 |
.find_syntax_by_extension(file_name) |
| 132 |
.or_else(|| syntax_set.find_syntax_by_extension(extension)) |
| 133 |
{ |
| 134 |
return syntax; |
| 135 |
} |
| 136 |
} |
| 137 |
} |
| 138 |
|
| 139 |
// Nothing found, try the user provided fallback, or the internal fallback. |
| 140 |
if let Some(syntax) = syntax_set.find_syntax_for_file(fallback).unwrap_or(None) { |
| 141 |
syntax |
| 142 |
} else { |
| 143 |
syntax_set |
| 144 |
.find_syntax_by_extension(config::SYNTAX_FALLBACK_LANG) |
| 145 |
.unwrap_or_else(|| { |
| 146 |
delta_unreachable("Failed to find any language syntax definitions.") |
| 147 |
}) |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
pub fn set_highlighter(&mut self) { |
| 152 |
if let Some(ref syntax_theme) = self.config.syntax_theme { |
| 153 |
self.highlighter = Some(HighlightLines::new(self.syntax, syntax_theme)) |
| 154 |
}; |
| 155 |
} |
| 156 |
|
| 157 |
pub fn paint_buffered_minus_and_plus_lines(&mut self) { |
| 158 |
if self.minus_lines.is_empty() && self.plus_lines.is_empty() { |
| 159 |
return; |
| 160 |
} |
| 161 |
paint_minus_and_plus_lines( |
| 162 |
MinusPlus::new(&self.minus_lines, &self.plus_lines), |
| 163 |
&mut self.line_numbers_data, |
| 164 |
&mut self.highlighter, |
| 165 |
&mut self.output_buffer, |
| 166 |
self.config, |
| 167 |
); |
| 168 |
self.minus_lines.clear(); |
| 169 |
self.plus_lines.clear(); |
| 170 |
} |
| 171 |
|
| 172 |
pub fn paint_zero_line(&mut self, line: &str, state: State) { |
| 173 |
let lines = &[(line.to_string(), state.clone())]; |
| 174 |
let syntax_style_sections = |
| 175 |
get_syntax_style_sections_for_lines(lines, self.highlighter.as_mut(), self.config); |
| 176 |
let mut diff_style_sections = vec![vec![(self.config.zero_style, lines[0].0.as_str())]]; // TODO: compute style from state |
| 177 |
Painter::update_diff_style_sections( |
| 178 |
lines, |
| 179 |
&mut diff_style_sections, |
| 180 |
None, |
| 181 |
None, |
| 182 |
&[false], |
| 183 |
self.config, |
| 184 |
); |
| 185 |
if self.config.side_by_side { |
| 186 |
// `lines[0].0` so the line has the '\n' already added (as in the +- case) |
| 187 |
side_by_side::paint_zero_lines_side_by_side( |
| 188 |
&lines[0].0, |
| 189 |
syntax_style_sections, |
| 190 |
diff_style_sections, |
| 191 |
&mut self.output_buffer, |
| 192 |
self.config, |
| 193 |
&mut self.line_numbers_data.as_mut(), |
| 194 |
painted_prefix(state, self.config), |
| 195 |
BgShouldFill::With(BgFillMethod::Spaces), |
| 196 |
); |
| 197 |
} else { |
| 198 |
Painter::paint_lines( |
| 199 |
lines, |
| 200 |
&syntax_style_sections, |
| 201 |
diff_style_sections.as_slice(), |
| 202 |
&[false], |
| 203 |
&mut self.output_buffer, |
| 204 |
self.config, |
| 205 |
&mut self.line_numbers_data.as_mut(), |
| 206 |
None, |
| 207 |
BgShouldFill::default(), |
| 208 |
); |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
/// Superimpose background styles and foreground syntax |
| 213 |
/// highlighting styles, and write colored lines to output buffer. |
| 214 |
#[allow(clippy::too_many_arguments)] |
| 215 |
pub fn paint_lines<'a>( |
| 216 |
lines: &'a [(String, State)], |
| 217 |
syntax_style_sections: &[LineSections<'a, SyntectStyle>], |
| 218 |
diff_style_sections: &[LineSections<'a, Style>], |
| 219 |
lines_have_homolog: &[bool], |
| 220 |
output_buffer: &mut String, |
| 221 |
config: &config::Config, |
| 222 |
line_numbers_data: &mut Option<&mut line_numbers::LineNumbersData>, |
| 223 |
empty_line_style: Option<Style>, // a style with background color to highlight an empty line |
| 224 |
background_color_extends_to_terminal_width: BgShouldFill, |
| 225 |
) { |
| 226 |
// There's some unfortunate hackery going on here for two reasons: |
| 227 |
// |
| 228 |
// 1. The prefix needs to be injected into the output stream. |
| 229 |
// |
| 230 |
// 2. We must ensure that we fill rightwards with the appropriate |
| 231 |
// non-emph background color. In that case we don't use the last |
| 232 |
// style of the line, because this might be emph. |
| 233 |
for ((((_, state), syntax_sections), diff_sections), &line_has_homolog) in lines |
| 234 |
.iter() |
| 235 |
.zip_eq(syntax_style_sections) |
| 236 |
.zip_eq(diff_style_sections) |
| 237 |
.zip_eq(lines_have_homolog) |
| 238 |
{ |
| 239 |
let (mut line, line_is_empty) = Painter::paint_line( |
| 240 |
syntax_sections, |
| 241 |
diff_sections, |
| 242 |
state, |
| 243 |
line_numbers_data, |
| 244 |
None, |
| 245 |
painted_prefix(state.clone(), config), |
| 246 |
config, |
| 247 |
); |
| 248 |
let (bg_fill_mode, fill_style) = |
| 249 |
Painter::get_should_right_fill_background_color_and_fill_style( |
| 250 |
diff_sections, |
| 251 |
Some(line_has_homolog), |
| 252 |
state, |
| 253 |
background_color_extends_to_terminal_width, |
| 254 |
config, |
| 255 |
); |
| 256 |
|
| 257 |
if let Some(BgFillMethod::TryAnsiSequence) = bg_fill_mode { |
| 258 |
Painter::right_fill_background_color(&mut line, fill_style); |
| 259 |
} else if let Some(BgFillMethod::Spaces) = bg_fill_mode { |
| 260 |
let text_width = ansi::measure_text_width(&line); |
| 261 |
line.push_str( |
| 262 |
#[allow(clippy::unnecessary_to_owned)] |
| 263 |
&fill_style |
| 264 |
.paint(" ".repeat(config.available_terminal_width - text_width)) |
| 265 |
.to_string(), |
| 266 |
); |
| 267 |
} else if line_is_empty { |
| 268 |
if let Some(empty_line_style) = empty_line_style { |
| 269 |
Painter::mark_empty_line( |
| 270 |
&empty_line_style, |
| 271 |
&mut line, |
| 272 |
if config.line_numbers { Some(" ") } else { None }, |
| 273 |
); |
| 274 |
} |
| 275 |
}; |
| 276 |
|
| 277 |
output_buffer.push_str(&line); |
| 278 |
output_buffer.push('\n'); |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
/// Write painted line to the output buffer, with syntax-highlighting and `style` superimposed. |
| 283 |
// Note that, if passing `style_sections` as |
| 284 |
// `StyleSectionSpecifier::StyleSections`, then tabs must already have been |
| 285 |
// expanded in the text. |
| 286 |
pub fn syntax_highlight_and_paint_line( |
| 287 |
&mut self, |
| 288 |
line: &str, |
| 289 |
style_sections: StyleSectionSpecifier, |
| 290 |
state: State, |
| 291 |
background_color_extends_to_terminal_width: BgShouldFill, |
| 292 |
) { |
| 293 |
let lines = vec![(tabs::expand(line, &self.config.tab_cfg), state)]; |
| 294 |
let syntax_style_sections = |
| 295 |
get_syntax_style_sections_for_lines(&lines, self.highlighter.as_mut(), self.config); |
| 296 |
let diff_style_sections = match style_sections { |
| 297 |
StyleSectionSpecifier::Style(style) => vec![vec![(style, lines[0].0.as_str())]], |
| 298 |
StyleSectionSpecifier::StyleSections(style_sections) => vec![style_sections], |
| 299 |
}; |
| 300 |
Painter::paint_lines( |
| 301 |
&lines, |
| 302 |
&syntax_style_sections, |
| 303 |
&diff_style_sections, |
| 304 |
&[false], |
| 305 |
&mut self.output_buffer, |
| 306 |
self.config, |
| 307 |
&mut None, |
| 308 |
None, |
| 309 |
background_color_extends_to_terminal_width, |
| 310 |
); |
| 311 |
} |
| 312 |
|
| 313 |
/// Determine whether the terminal should fill the line rightwards with a background color, and |
| 314 |
/// the style for doing so. |
| 315 |
pub fn get_should_right_fill_background_color_and_fill_style( |
| 316 |
diff_sections: &[(Style, &str)], |
| 317 |
line_has_homolog: Option<bool>, |
| 318 |
state: &State, |
| 319 |
background_color_extends_to_terminal_width: BgShouldFill, |
| 320 |
config: &config::Config, |
| 321 |
) -> (Option<BgFillMethod>, Style) { |
| 322 |
let fill_style = match state { |
| 323 |
State::HunkMinus(_, None) | State::HunkMinusWrapped => { |
| 324 |
if let Some(true) = line_has_homolog { |
| 325 |
config.minus_non_emph_style |
| 326 |
} else { |
| 327 |
config.minus_style |
| 328 |
} |
| 329 |
} |
| 330 |
State::HunkZero(_, None) | State::HunkZeroWrapped => config.zero_style, |
| 331 |
State::HunkPlus(_, None) | State::HunkPlusWrapped => { |
| 332 |
if let Some(true) = line_has_homolog { |
| 333 |
config.plus_non_emph_style |
| 334 |
} else { |
| 335 |
config.plus_style |
| 336 |
} |
| 337 |
} |
| 338 |
State::HunkMinus(_, Some(_)) |
| 339 |
| State::HunkZero(_, Some(_)) |
| 340 |
| State::HunkPlus(_, Some(_)) => { |
| 341 |
// Consider the following raw line, from git colorMoved: |
| 342 |
// ␛[1;36m+␛[m␛[1;36mclass·X:·pass␛[m␊ The last style section returned by |
| 343 |
// parse_style_sections will be a default style associated with the terminal newline |
| 344 |
// character; we want the last "real" style. |
| 345 |
diff_sections |
| 346 |
.iter() |
| 347 |
.rev() |
| 348 |
.filter(|(_, s)| s != &"\n") |
| 349 |
.map(|(style, _)| *style) |
| 350 |
.next() |
| 351 |
.unwrap_or(config.null_style) |
| 352 |
} |
| 353 |
State::Blame(_) => diff_sections[0].0, |
| 354 |
_ => config.null_style, |
| 355 |
}; |
| 356 |
|
| 357 |
match ( |
| 358 |
fill_style.get_background_color().is_some(), |
| 359 |
background_color_extends_to_terminal_width, |
| 360 |
) { |
| 361 |
(false, _) | (_, BgShouldFill::No) => (None, fill_style), |
| 362 |
(_, BgShouldFill::With(bgmode)) => { |
| 363 |
if config.background_color_extends_to_terminal_width { |
| 364 |
(Some(bgmode), fill_style) |
| 365 |
} else { |
| 366 |
(None, fill_style) |
| 367 |
} |
| 368 |
} |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
/// Emit line with ANSI sequences that extend the background color to the terminal width. |
| 373 |
pub fn right_fill_background_color(line: &mut String, fill_style: Style) { |
| 374 |
// HACK: How to properly incorporate the ANSI_CSI_CLEAR_TO_EOL into ansi_strings? |
| •375 |
line.push_str(&ansi_term::AnsiStrings(&[fill_style.paint("")]).to_string()); |
| 376 |
if line |
| 377 |
.to_lowercase() |
| 378 |
.ends_with(&ansi::ANSI_SGR_RESET.to_lowercase()) |
| 379 |
{ |
| 380 |
line.truncate(line.len() - ansi::ANSI_SGR_RESET.len()); |
| 381 |
} |
| 382 |
line.push_str(ansi::ANSI_CSI_CLEAR_TO_EOL); |
| 383 |
line.push_str(ansi::ANSI_SGR_RESET); |
| 384 |
} |
| 385 |
|
| 386 |
/// Use ANSI sequences to visually mark the current line as empty. If `marker` is None then the |
| 387 |
/// line is marked using terminal emulator colors only, i.e. without appending any marker text |
| 388 |
/// to the line. This is typically appropriate only when the `line` buffer is empty, since |
| 389 |
/// otherwise the ANSI_CSI_CLEAR_TO_BOL instruction would overwrite the text to the left of the |
| 390 |
/// current buffer position. |
| 391 |
pub fn mark_empty_line(empty_line_style: &Style, line: &mut String, marker: Option<&str>) { |
| 392 |
line.push_str( |
| 393 |
#[allow(clippy::unnecessary_to_owned)] |
| 394 |
&empty_line_style |
| 395 |
.paint(marker.unwrap_or(ansi::ANSI_CSI_CLEAR_TO_BOL)) |
| 396 |
.to_string(), |
| 397 |
); |
| 398 |
} |
| 399 |
|
| 400 |
/// Return painted line (maybe prefixed with line numbers field) and an is_empty? boolean. |
| 401 |
pub fn paint_line( |
| 402 |
syntax_sections: &[(SyntectStyle, &str)], |
| 403 |
diff_sections: &[(Style, &str)], |
| 404 |
state: &State, |
| 405 |
line_numbers_data: &mut Option<&mut line_numbers::LineNumbersData>, |
| 406 |
side_by_side_panel: Option<PanelSide>, |
| •407 |
mut painted_prefix: Option<ansi_term::AnsiString>, |
| 408 |
config: &config::Config, |
| 409 |
) -> (String, bool) { |
| 410 |
let mut ansi_strings = Vec::new(); |
| 411 |
|
| 412 |
let output_line_numbers = line_numbers_data.is_some(); |
| 413 |
if output_line_numbers { |
| 414 |
// Unified diff lines are printed in one go, but side-by-side lines |
| 415 |
// are printed in two parts, so do not increment line numbers when the |
| 416 |
// first (left) part is printed. |
| 417 |
let increment = !matches!(side_by_side_panel, Some(side_by_side::Left)); |
| 418 |
if let Some((line_numbers, styles)) = line_numbers::linenumbers_and_styles( |
| 419 |
line_numbers_data.as_mut().unwrap(), |
| 420 |
state, |
| 421 |
config, |
| 422 |
increment, |
| 423 |
) { |
| 424 |
ansi_strings.extend(line_numbers::format_and_paint_line_numbers( |
| 425 |
line_numbers_data.as_ref().unwrap(), |
| 426 |
side_by_side_panel, |
| 427 |
styles, |
| 428 |
line_numbers, |
| 429 |
config, |
| 430 |
)) |
| 431 |
} |
| 432 |
} |
| 433 |
let superimposed = superimpose_style_sections( |
| 434 |
syntax_sections, |
| 435 |
diff_sections, |
| 436 |
config.true_color, |
| 437 |
config.null_syntect_style, |
| 438 |
); |
| 439 |
|
| 440 |
let mut handled_prefix = false; |
| 441 |
for (section_style, text) in &superimposed { |
| 442 |
// If requested re-insert the +/- prefix with proper styling. |
| 443 |
if !handled_prefix { |
| 444 |
if let Some(painted_prefix) = painted_prefix.take() { |
| 445 |
ansi_strings.push(painted_prefix) |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
if !text.is_empty() { |
| 450 |
ansi_strings.push(section_style.paint(text.as_str())); |
| 451 |
} |
| 452 |
handled_prefix = true; |
| 453 |
} |
| 454 |
|
| 455 |
// Only if syntax is empty (implies diff empty) can a line actually be empty. |
| 456 |
let is_empty = syntax_sections.is_empty(); |
| •457 |
(ansi_term::AnsiStrings(&ansi_strings).to_string(), is_empty) |
| 458 |
} |
| 459 |
|
| 460 |
/// Write output buffer to output stream, and clear the buffer. |
| 461 |
pub fn emit(&mut self) -> std::io::Result<()> { |
| 462 |
write!(self.writer, "{}", self.output_buffer)?; |
| 463 |
self.output_buffer.clear(); |
| 464 |
Ok(()) |
| 465 |
} |
| 466 |
|
| 467 |
pub fn should_compute_syntax_highlighting(state: &State, config: &config::Config) -> bool { |
| 468 |
if config.syntax_theme.is_none() { |
| 469 |
return false; |
| 470 |
} |
| 471 |
match state { |
| 472 |
State::HunkMinus(_, None) => { |
| 473 |
config.minus_style.is_syntax_highlighted |
| 474 |
|| config.minus_emph_style.is_syntax_highlighted |
| 475 |
|| config.minus_non_emph_style.is_syntax_highlighted |
| 476 |
} |
| 477 |
State::HunkZero(_, None) => config.zero_style.is_syntax_highlighted, |
| 478 |
State::HunkPlus(_, None) => { |
| 479 |
config.plus_style.is_syntax_highlighted |
| 480 |
|| config.plus_emph_style.is_syntax_highlighted |
| 481 |
|| config.plus_non_emph_style.is_syntax_highlighted |
| 482 |
} |
| 483 |
State::HunkHeader(_, _, _, _) => true, |
| 484 |
State::HunkMinus(_, Some(_raw_line)) |
| 485 |
| State::HunkZero(_, Some(_raw_line)) |
| 486 |
| State::HunkPlus(_, Some(_raw_line)) => { |
| 487 |
// It is possible that the captured raw line contains an ANSI |
| 488 |
// style that has been mapped (via map-styles) to a delta Style |
| 489 |
// with syntax-highlighting. |
| 490 |
true |
| 491 |
} |
| 492 |
State::Blame(_) => true, |
| 493 |
State::GitShowFile => true, |
| 494 |
State::Grep(_, _, _, _) => true, |
| 495 |
State::Unknown |
| 496 |
| State::CommitMeta |
| 497 |
| State::DiffHeader(_) |
| 498 |
| State::HunkMinusWrapped |
| 499 |
| State::HunkZeroWrapped |
| 500 |
| State::HunkPlusWrapped |
| 501 |
| State::MergeConflict(_, _) |
| 502 |
| State::SubmoduleLog |
| 503 |
| State::SubmoduleShort(_) => { |
| 504 |
panic!( |
| 505 |
"should_compute_syntax_highlighting is undefined for state {:?}", |
| 506 |
state |
| 507 |
) |
| 508 |
} |
| 509 |
} |
| 510 |
} |
| 511 |
|
| 512 |
/// There are some rules according to which we update line section styles that were computed |
| 513 |
/// during the initial edit inference pass. This function applies those rules. The rules are |
| 514 |
/// 1. If there are multiple diff styles in the line, then the line must have some |
| 515 |
/// inferred edit operations and so, if there is a special non-emph style that is |
| 516 |
/// distinct from the default style, then it should be used for the non-emph style |
| 517 |
/// sections. |
| 518 |
/// 2. If the line constitutes a whitespace error, then the whitespace error style |
| 519 |
/// should be applied to the added material. |
| 520 |
/// 3. If delta recognized the raw line as one containing ANSI colors that |
| 521 |
/// are going to be preserved in the output, then replace delta's |
| 522 |
/// computed diff styles with these styles from the raw line. (This is |
| 523 |
/// how support for git's --color-moved is implemented.) |
| 524 |
fn update_diff_style_sections<'a>( |
| 525 |
lines: &'a [(String, State)], |
| 526 |
diff_style_sections: &mut Vec<LineSections<'a, Style>>, |
| 527 |
whitespace_error_style: Option<Style>, |
| 528 |
non_emph_style: Option<Style>, |
| 529 |
lines_have_homolog: &[bool], |
| 530 |
config: &config::Config, |
| 531 |
) { |
| 532 |
for (((_, state), style_sections), line_has_homolog) in lines |
| 533 |
.iter() |
| 534 |
.zip_eq(diff_style_sections) |
| 535 |
.zip_eq(lines_have_homolog) |
| 536 |
{ |
| 537 |
if let State::HunkMinus(_, Some(raw_line)) |
| 538 |
| State::HunkZero(_, Some(raw_line)) |
| 539 |
| State::HunkPlus(_, Some(raw_line)) = state |
| 540 |
{ |
| 541 |
// raw_line is captured in handle_hunk_line under certain conditions. If we have |
| 542 |
// done so, then overwrite the style sections with styles parsed directly from the |
| 543 |
// raw line. Currently the only reason this is done is to handle a diff.colorMoved |
| 544 |
// line. |
| 545 |
*style_sections = parse_style_sections(raw_line, config); |
| 546 |
continue; |
| 547 |
} |
| 548 |
let line_has_emph_and_non_emph_sections = |
| 549 |
style_sections_contain_more_than_one_style(style_sections); |
| 550 |
let should_update_non_emph_styles = non_emph_style.is_some() && *line_has_homolog; |
| 551 |
|
| 552 |
// TODO: Git recognizes blank lines at end of file (blank-at-eof) |
| 553 |
// as a whitespace error but delta does not yet. |
| 554 |
// https://git-scm.com/docs/git-config#Documentation/git-config.txt-corewhitespace |
| 555 |
let mut is_whitespace_error = whitespace_error_style.is_some(); |
| 556 |
for (style, s) in style_sections.iter_mut().rev() { |
| 557 |
if is_whitespace_error && !s.trim().is_empty() { |
| 558 |
is_whitespace_error = false; |
| 559 |
} |
| 560 |
// If the line as a whole constitutes a whitespace error then highlight this |
| 561 |
// section if either (a) it is an emph section, or (b) the line lacks any |
| 562 |
// emph/non-emph distinction. |
| 563 |
|
| 564 |
// TODO: is this logic correct now, after introducing |
| 565 |
// line_has_homolog for non_emph style? |
| 566 |
if is_whitespace_error && (style.is_emph || !line_has_emph_and_non_emph_sections) { |
| 567 |
*style = whitespace_error_style.unwrap(); |
| 568 |
} |
| 569 |
// Otherwise, update the style if this is a non-emph section that needs updating. |
| 570 |
else if should_update_non_emph_styles && !style.is_emph { |
| 571 |
*style = non_emph_style.unwrap(); |
| 572 |
if is_whitespace_error { |
| 573 |
*style = whitespace_error_style.unwrap(); |
| 574 |
} |
| 575 |
} |
| 576 |
} |
| 577 |
} |
| 578 |
} |
| 579 |
} |
| 580 |
|
| 581 |
/// Remove initial -/+ character, expand tabs as spaces, and terminate with newline. |
| 582 |
// Terminating with newline character is necessary for many of the sublime syntax definitions to |
| 583 |
// highlight correctly. |
| 584 |
// See https://docs.rs/syntect/3.2.0/syntect/parsing/struct.SyntaxSetBuilder.html#method.add_from_folder |
| 585 |
pub fn prepare(line: &str, prefix_length: usize, config: &config::Config) -> String { |
| 586 |
if !line.is_empty() { |
| 587 |
// The prefix contains -/+/space characters, added by git. We removes them now so they |
| 588 |
// are not present during syntax highlighting or wrapping. If --keep-plus-minus-markers |
| 589 |
// is in effect the prefix is re-inserted in Painter::paint_line. |
| 590 |
let mut line = tabs::remove_prefix_and_expand(prefix_length, line, &config.tab_cfg); |
| 591 |
line.push('\n'); |
| 592 |
line |
| 593 |
} else { |
| 594 |
"\n".to_string() |
| 595 |
} |
| 596 |
} |
| 597 |
|
| 598 |
// Remove initial -/+ characters, expand tabs as spaces, retaining ANSI sequences. Terminate with |
| 599 |
// newline character. |
| 600 |
pub fn prepare_raw_line(raw_line: &str, prefix_length: usize, config: &config::Config) -> String { |
| 601 |
let mut line = tabs::expand(raw_line, &config.tab_cfg); |
| 602 |
line.push('\n'); |
| 603 |
ansi::ansi_preserving_slice(&line, prefix_length) |
| 604 |
} |
| 605 |
|
| 606 |
pub fn paint_minus_and_plus_lines( |
| 607 |
lines: MinusPlus<&Vec<(String, State)>>, |
| 608 |
line_numbers_data: &mut Option<LineNumbersData>, |
| 609 |
highlighter: &mut Option<HighlightLines>, |
| 610 |
output_buffer: &mut String, |
| 611 |
config: &config::Config, |
| 612 |
) { |
| 613 |
let syntax_style_sections = MinusPlus::new( |
| 614 |
get_syntax_style_sections_for_lines(lines[Minus], highlighter.as_mut(), config), |
| 615 |
get_syntax_style_sections_for_lines(lines[Plus], highlighter.as_mut(), config), |
| 616 |
); |
| 617 |
let (mut diff_style_sections, line_alignment) = get_diff_style_sections(&lines, config); |
| 618 |
let lines_have_homolog = edits::make_lines_have_homolog(&line_alignment); |
| 619 |
Painter::update_diff_style_sections( |
| 620 |
lines[Minus], |
| 621 |
&mut diff_style_sections[Minus], |
| 622 |
None, |
| 623 |
if config.minus_non_emph_style != config.minus_emph_style { |
| 624 |
Some(config.minus_non_emph_style) |
| 625 |
} else { |
| 626 |
None |
| 627 |
}, |
| 628 |
&lines_have_homolog[Minus], |
| 629 |
config, |
| 630 |
); |
| 631 |
Painter::update_diff_style_sections( |
| 632 |
lines[Plus], |
| 633 |
&mut diff_style_sections[Plus], |
| 634 |
Some(config.whitespace_error_style), |
| 635 |
if config.plus_non_emph_style != config.plus_emph_style { |
| 636 |
Some(config.plus_non_emph_style) |
| 637 |
} else { |
| 638 |
None |
| 639 |
}, |
| 640 |
&lines_have_homolog[Plus], |
| 641 |
config, |
| 642 |
); |
| 643 |
if config.side_by_side { |
| 644 |
side_by_side::paint_minus_and_plus_lines_side_by_side( |
| 645 |
lines, |
| 646 |
syntax_style_sections, |
| 647 |
diff_style_sections, |
| 648 |
lines_have_homolog, |
| 649 |
line_alignment, |
| 650 |
line_numbers_data, |
| 651 |
output_buffer, |
| 652 |
config, |
| 653 |
) |
| 654 |
} else { |
| 655 |
// Unified diff mode: |
| 656 |
if !lines[Minus].is_empty() { |
| 657 |
Painter::paint_lines( |
| 658 |
lines[Minus], |
| 659 |
&syntax_style_sections[Minus], |
| 660 |
&diff_style_sections[Minus], |
| 661 |
&lines_have_homolog[Minus], |
| 662 |
output_buffer, |
| 663 |
config, |
| 664 |
&mut line_numbers_data.as_mut(), |
| 665 |
Some(config.minus_empty_line_marker_style), |
| 666 |
BgShouldFill::default(), |
| 667 |
); |
| 668 |
} |
| 669 |
if !lines[Plus].is_empty() { |
| 670 |
Painter::paint_lines( |
| 671 |
lines[Plus], |
| 672 |
&syntax_style_sections[Plus], |
| 673 |
&diff_style_sections[Plus], |
| 674 |
&lines_have_homolog[Plus], |
| 675 |
output_buffer, |
| 676 |
config, |
| 677 |
&mut line_numbers_data.as_mut(), |
| 678 |
Some(config.plus_empty_line_marker_style), |
| 679 |
BgShouldFill::default(), |
| 680 |
); |
| 681 |
} |
| 682 |
} |
| 683 |
} |
| 684 |
|
| 685 |
pub fn get_syntax_style_sections_for_lines<'a>( |
| 686 |
lines: &'a [(String, State)], |
| 687 |
highlighter: Option<&mut HighlightLines>, |
| 688 |
config: &config::Config, |
| 689 |
) -> Vec<LineSections<'a, SyntectStyle>> { |
| 690 |
let mut line_sections = Vec::new(); |
| 691 |
match ( |
| 692 |
highlighter, |
| 693 |
lines |
| 694 |
.iter() |
| 695 |
.any(|(_, state)| Painter::should_compute_syntax_highlighting(state, config)), |
| 696 |
) { |
| 697 |
(Some(highlighter), true) => { |
| 698 |
for (line, _) in lines.iter() { |
| 699 |
// Fast but simple length comparison. Overcounts non-printable ansi |
| 700 |
// characters or wider UTF-8, but `truncate_str_short` in the |
| 701 |
// else branch corrects that. |
| 702 |
if line.len() < config.max_syntax_length || config.max_syntax_length == 0 { |
| 703 |
line_sections.push( |
| 704 |
highlighter |
| 705 |
.highlight_line(line, &config.syntax_set) |
| 706 |
.unwrap(), |
| 707 |
); |
| 708 |
} else { |
| 709 |
let line_syntax = ansi::truncate_str_short(line, config.max_syntax_length); |
| 710 |
// Re-split to get references into `line` with correct lifetimes. |
| 711 |
// SAFETY: slicing the string is safe because `truncate_str_short` always |
| 712 |
// returns a prefix of the input and only cuts at grapheme borders. |
| 713 |
let (with_syntax, plain) = line.split_at(line_syntax.len()); |
| 714 |
// Note: splitting a line and only feeding one half to the highlighter may |
| 715 |
// result in wrong highlighting until it is reset the next hunk. |
| 716 |
// |
| 717 |
// Also, as lines are no longer newline terminated they might not be |
| 718 |
// highlighted correctly, and because of lifetimes inserting '\n' here is not |
| 719 |
// possible, also see `prepare()`. |
| 720 |
line_sections.push( |
| 721 |
highlighter |
| 722 |
.highlight_line(with_syntax, &config.syntax_set) |
| 723 |
.unwrap(), |
| 724 |
); |
| 725 |
|
| 726 |
if !plain.is_empty() { |
| 727 |
line_sections |
| 728 |
.last_mut() |
| 729 |
.unwrap() |
| 730 |
.push((config.null_syntect_style, plain)); |
| 731 |
} |
| 732 |
} |
| 733 |
} |
| 734 |
} |
| 735 |
_ => { |
| 736 |
for (line, _) in lines.iter() { |
| 737 |
line_sections.push(vec![(config.null_syntect_style, line.as_str())]) |
| 738 |
} |
| 739 |
} |
| 740 |
} |
| 741 |
line_sections |
| 742 |
} |
| 743 |
|
| 744 |
/// Get background styles to represent diff for minus and plus lines in buffer. |
| 745 |
#[allow(clippy::type_complexity)] |
| 746 |
fn get_diff_style_sections<'a>( |
| 747 |
lines: &MinusPlus<&'a Vec<(String, State)>>, |
| 748 |
config: &config::Config, |
| 749 |
) -> ( |
| 750 |
MinusPlus<Vec<LineSections<'a, Style>>>, |
| 751 |
Vec<(Option<usize>, Option<usize>)>, |
| 752 |
) { |
| 753 |
let (minus_lines, minus_styles): (Vec<&str>, Vec<Style>) = lines[Minus] |
| 754 |
.iter() |
| 755 |
.map(|(s, state)| (s.as_str(), *config.get_style(state))) |
| 756 |
.unzip(); |
| 757 |
let (plus_lines, plus_styles): (Vec<&str>, Vec<Style>) = lines[Plus] |
| 758 |
.iter() |
| 759 |
.map(|(s, state)| (s.as_str(), *config.get_style(state))) |
| 760 |
.unzip(); |
| 761 |
let (minus_line_diff_style_sections, plus_line_diff_style_sections, line_alignment) = |
| 762 |
edits::infer_edits( |
| 763 |
minus_lines, |
| 764 |
plus_lines, |
| 765 |
minus_styles, |
| 766 |
config.minus_emph_style, // FIXME |
| 767 |
plus_styles, |
| 768 |
config.plus_emph_style, // FIXME |
| 769 |
&config.tokenization_regex, |
| 770 |
config.max_line_distance, |
| 771 |
config.max_line_distance_for_naively_paired_lines, |
| 772 |
); |
| 773 |
let diff_sections = MinusPlus::new( |
| 774 |
minus_line_diff_style_sections, |
| 775 |
plus_line_diff_style_sections, |
| 776 |
); |
| 777 |
(diff_sections, line_alignment) |
| 778 |
} |
| 779 |
|
| •780 |
fn painted_prefix(state: State, config: &config::Config) -> Option<AnsiString<'_>> { |
| 781 |
use DiffType::*; |
| 782 |
use State::*; |
| 783 |
match (state, config.keep_plus_minus_markers) { |
| 784 |
// For a combined diff, unless we are in a merge conflict, we do not honor |
| 785 |
// keep_plus_minus_markers -- i.e. we always emit the prefix -- because there is currently |
| 786 |
// no way to distinguish, say, a '+ ' line from a ' +' line, by styles alone. In a merge |
| 787 |
// conflict we do honor the setting because the way merge conflicts are displayed indicates |
| 788 |
// from which commit the lines derive. |
| 789 |
(HunkMinus(Combined(MergeParents::Prefix(prefix), InMergeConflict::No), _), _) => { |
| 790 |
Some(config.minus_style.paint(prefix)) |
| 791 |
} |
| 792 |
(HunkZero(Combined(MergeParents::Prefix(prefix), InMergeConflict::No), _), _) => { |
| 793 |
Some(config.zero_style.paint(prefix)) |
| 794 |
} |
| 795 |
(HunkPlus(Combined(MergeParents::Prefix(prefix), InMergeConflict::No), _), _) => { |
| 796 |
Some(config.plus_style.paint(prefix)) |
| 797 |
} |
| 798 |
// But otherwise we honor keep_plus_minus_markers |
| 799 |
(HunkMinus(_, _), true) => Some(config.minus_style.paint("-".to_string())), |
| 800 |
(HunkZero(_, _), true) => Some(config.zero_style.paint(" ".to_string())), |
| 801 |
(HunkPlus(_, _), true) => Some(config.plus_style.paint("+".to_string())), |
| 802 |
_ => None, |
| 803 |
} |
| 804 |
} |
| 805 |
|
| 806 |
// Parse ANSI styles encountered in `raw_line` and apply `styles_map`. |
| 807 |
pub fn parse_style_sections<'a>( |
| 808 |
raw_line: &'a str, |
| 809 |
config: &config::Config, |
| 810 |
) -> LineSections<'a, Style> { |
| 811 |
let empty_map = HashMap::new(); |
| 812 |
let styles_map = config.styles_map.as_ref().unwrap_or(&empty_map); |
| 813 |
ansi::parse_style_sections(raw_line) |
| 814 |
.iter() |
| 815 |
.map(|(original_style, s)| { |
| 816 |
match styles_map.get(&style::ansi_term_style_equality_key(*original_style)) { |
| 817 |
Some(mapped_style) => (*mapped_style, *s), |
| 818 |
None => ( |
| 819 |
Style { |
| 820 |
ansi_term_style: *original_style, |
| 821 |
..Style::default() |
| 822 |
}, |
| 823 |
*s, |
| 824 |
), |
| 825 |
} |
| 826 |
}) |
| 827 |
.collect() |
| 828 |
} |
| 829 |
|
| 830 |
#[allow(clippy::too_many_arguments)] |
| 831 |
pub fn paint_file_path_with_line_number( |
| 832 |
line_number: Option<usize>, |
| 833 |
file_path: &str, |
| 834 |
pad_line_number: bool, |
| 835 |
separator: &str, |
| 836 |
terminate_with_separator: bool, |
| 837 |
file_style: Option<Style>, // None means do not include file path |
| 838 |
line_number_style: Option<Style>, // None means do not include line number |
| 839 |
config: &Config, |
| 840 |
) -> String { |
| 841 |
let mut file_with_line_number = Vec::new(); |
| 842 |
if let Some(file_style) = file_style { |
| 843 |
let file_path = if let Some(regex_replacement) = &config.file_regex_replacement { |
| 844 |
regex_replacement.execute(file_path) |
| 845 |
} else { |
| 846 |
Cow::from(file_path) |
| 847 |
}; |
| 848 |
file_with_line_number.push(file_style.paint(file_path)) |
| 849 |
}; |
| 850 |
if let Some(line_number) = line_number { |
| 851 |
if let Some(line_number_style) = line_number_style { |
| 852 |
if !file_with_line_number.is_empty() { |
| •853 |
file_with_line_number.push(ansi_term::AnsiString::from(separator)); |
| 854 |
} |
| 855 |
file_with_line_number.push(line_number_style.paint(format!("{line_number}"))) |
| 856 |
} |
| 857 |
} |
| 858 |
if terminate_with_separator { |
| •859 |
file_with_line_number.push(ansi_term::AnsiGenericString::from(separator)); |
| 860 |
} |
| 861 |
if pad_line_number { |
| 862 |
// If requested we pad line numbers to a width of at least |
| 863 |
// 3, so that we do not see any misalignment up to line |
| 864 |
// number 999. However, see |
| 865 |
// https://github.com/BurntSushi/ripgrep/issues/795 for |
| 866 |
// discussion about aligning grep output. |
| 867 |
match line_number { |
| 868 |
Some(n) if n < 10 => { |
| •869 |
file_with_line_number.push(ansi_term::AnsiGenericString::from(" ")) |
| 870 |
} |
| 871 |
Some(n) if n < 100 => { |
| •872 |
file_with_line_number.push(ansi_term::AnsiGenericString::from(" ")) |
| 873 |
} |
| 874 |
_ => {} |
| 875 |
} |
| 876 |
} |
| •877 |
let file_with_line_number = ansi_term::AnsiStrings(&file_with_line_number).to_string(); |
| 878 |
match if config.hyperlinks && !file_with_line_number.is_empty() { |
| 879 |
utils::path::absolute_path(file_path, config) |
| 880 |
} else { |
| 881 |
None |
| 882 |
} { |
| 883 |
Some(absolute_path) => hyperlinks::format_osc8_file_hyperlink( |
| 884 |
absolute_path, |
| 885 |
line_number, |
| 886 |
&file_with_line_number, |
| 887 |
config, |
| 888 |
) |
| 889 |
.into(), |
| 890 |
_ => file_with_line_number, |
| 891 |
} |
| 892 |
} |
| 893 |
|
| 894 |
// edits::annotate doesn't return "coalesced" annotations (see comment there), so we can't assume |
| 895 |
// that `sections.len() > 1 <=> (multiple styles)`. |
| 896 |
fn style_sections_contain_more_than_one_style(sections: &[(Style, &str)]) -> bool { |
| 897 |
if sections.len() > 1 { |
| 898 |
let (first_style, _) = sections[0]; |
| 899 |
sections.iter().any(|(style, _)| *style != first_style) |
| 900 |
} else { |
| 901 |
false |
| 902 |
} |
| 903 |
} |
| 904 |
|
| 905 |
mod superimpose_style_sections { |
| 906 |
use syntect::highlighting::Style as SyntectStyle; |
| 907 |
|
| 908 |
use crate::style::Style; |
| 909 |
use crate::utils::bat::terminal::to_ansi_color; |
| 910 |
|
| 911 |
// We have two different annotations of the same line: |
| 912 |
// `syntax_style_sections` contains foreground styles computed by syntect, |
| 913 |
// and `diff_style_sections` contains styles computed by delta reflecting |
| 914 |
// within-line edits. The delta styles may assign a foreground color, or |
| 915 |
// they may indicate that the foreground color comes from syntax |
| 916 |
// highlighting (the is_syntax_highlighting attribute on style::Style). This |
| 917 |
// function takes in the two input streams and outputs one stream with a |
| 918 |
// single style assigned to each character. |
| 919 |
pub fn superimpose_style_sections( |
| 920 |
syntax_style_sections: &[(SyntectStyle, &str)], |
| 921 |
diff_style_sections: &[(Style, &str)], |
| 922 |
true_color: bool, |
| 923 |
null_syntect_style: SyntectStyle, |
| 924 |
) -> Vec<(Style, String)> { |
| 925 |
coalesce( |
| 926 |
superimpose( |
| 927 |
explode(syntax_style_sections) |
| 928 |
.iter() |
| 929 |
.zip(explode(diff_style_sections)) |
| 930 |
.collect::<Vec<(&(SyntectStyle, char), (Style, char))>>(), |
| 931 |
), |
| 932 |
true_color, |
| 933 |
null_syntect_style, |
| 934 |
) |
| 935 |
} |
| 936 |
|
| 937 |
fn explode<T>(style_sections: &[(T, &str)]) -> Vec<(T, char)> |
| 938 |
where |
| 939 |
T: Copy, |
| 940 |
{ |
| 941 |
let mut exploded: Vec<(T, char)> = Vec::new(); |
| 942 |
for (style, s) in style_sections { |
| 943 |
for c in s.chars() { |
| 944 |
exploded.push((*style, c)); |
| 945 |
} |
| 946 |
} |
| 947 |
exploded |
| 948 |
} |
| 949 |
|
| 950 |
#[allow(clippy::type_complexity)] |
| 951 |
fn superimpose( |
| 952 |
style_section_pairs: Vec<(&(SyntectStyle, char), (Style, char))>, |
| 953 |
) -> Vec<((SyntectStyle, Style), char)> { |
| 954 |
let mut superimposed: Vec<((SyntectStyle, Style), char)> = Vec::new(); |
| 955 |
for ((syntax_style, char_1), (style, char_2)) in style_section_pairs { |
| 956 |
if *char_1 != char_2 { |
| 957 |
panic!( |
| 958 |
"String mismatch encountered while superimposing style sections: '{}' vs '{}'", |
| 959 |
*char_1, char_2 |
| 960 |
) |
| 961 |
} |
| 962 |
superimposed.push(((*syntax_style, style), *char_1)); |
| 963 |
} |
| 964 |
superimposed |
| 965 |
} |
| 966 |
|
| 967 |
fn coalesce( |
| 968 |
style_sections: Vec<((SyntectStyle, Style), char)>, |
| 969 |
true_color: bool, |
| 970 |
null_syntect_style: SyntectStyle, |
| 971 |
) -> Vec<(Style, String)> { |
| 972 |
let make_superimposed_style = |(syntect_style, style): (SyntectStyle, Style)| { |
| 973 |
if style.is_syntax_highlighted && syntect_style != null_syntect_style { |
| 974 |
Style { |
| 975 |
ansi_term_style: ansi_term::Style { |
| 976 |
foreground: to_ansi_color(syntect_style.foreground, true_color), |
| 977 |
..style.ansi_term_style |
| 978 |
}, |
| 979 |
..style |
| 980 |
} |
| 981 |
} else { |
| 982 |
style |
| 983 |
} |
| 984 |
}; |
| 985 |
let mut coalesced: Vec<(Style, String)> = Vec::new(); |
| 986 |
let mut style_sections = style_sections.iter(); |
| 987 |
if let Some((style_pair, c)) = style_sections.next() { |
| 988 |
let mut current_string = c.to_string(); |
| 989 |
let mut current_style_pair = style_pair; |
| 990 |
for (style_pair, c) in style_sections { |
| 991 |
if style_pair != current_style_pair { |
| 992 |
let style = make_superimposed_style(*current_style_pair); |
| 993 |
coalesced.push((style, current_string)); |
| 994 |
current_string = String::new(); |
| 995 |
current_style_pair = style_pair; |
| 996 |
} |
| 997 |
current_string.push(*c); |
| 998 |
} |
| 999 |
|
| 1000 |
// TODO: This is not the ideal location for the following code. |
| 1001 |
if current_string.ends_with('\n') { |
| 1002 |
// Remove the terminating newline whose presence was necessary for the syntax |
| 1003 |
// highlighter to work correctly. |
| 1004 |
current_string.truncate(current_string.len() - 1); |
| 1005 |
} |
| 1006 |
let style = make_superimposed_style(*current_style_pair); |
| 1007 |
coalesced.push((style, current_string)); |
| 1008 |
} |
| 1009 |
coalesced |
| 1010 |
} |
| 1011 |
|
| 1012 |
#[cfg(test)] |
| 1013 |
mod tests { |
| 1014 |
use lazy_static::lazy_static; |
| 1015 |
|
| 1016 |
use super::*; |
| 1017 |
use ansi_term::{self, Color}; |
| 1018 |
use syntect::highlighting::Color as SyntectColor; |
| 1019 |
use syntect::highlighting::FontStyle as SyntectFontStyle; |
| 1020 |
use syntect::highlighting::Style as SyntectStyle; |
| 1021 |
|
| 1022 |
use crate::style::{DecorationStyle, Style}; |
| 1023 |
|
| 1024 |
lazy_static! { |
| 1025 |
static ref SYNTAX_STYLE: SyntectStyle = SyntectStyle { |
| 1026 |
foreground: SyntectColor::BLACK, |
| 1027 |
background: SyntectColor::BLACK, |
| 1028 |
font_style: SyntectFontStyle::BOLD, |
| 1029 |
}; |
| 1030 |
} |
| 1031 |
lazy_static! { |
| 1032 |
static ref SYNTAX_HIGHLIGHTED_STYLE: Style = Style { |
| 1033 |
ansi_term_style: ansi_term::Style { |
| 1034 |
foreground: Some(Color::White), |
| 1035 |
background: Some(Color::White), |
| 1036 |
is_underline: true, |
| 1037 |
..ansi_term::Style::new() |
| 1038 |
}, |
| 1039 |
is_emph: false, |
| 1040 |
is_omitted: false, |
| 1041 |
is_raw: false, |
| 1042 |
is_syntax_highlighted: true, |
| 1043 |
decoration_style: DecorationStyle::NoDecoration, |
| 1044 |
}; |
| 1045 |
} |
| 1046 |
lazy_static! { |
| 1047 |
static ref NON_SYNTAX_HIGHLIGHTED_STYLE: Style = Style { |
| 1048 |
ansi_term_style: ansi_term::Style { |
| 1049 |
foreground: Some(Color::White), |
| 1050 |
background: Some(Color::White), |
| 1051 |
is_underline: true, |
| 1052 |
..ansi_term::Style::new() |
| 1053 |
}, |
| 1054 |
is_emph: false, |
| 1055 |
is_omitted: false, |
| 1056 |
is_raw: false, |
| 1057 |
is_syntax_highlighted: false, |
| 1058 |
decoration_style: DecorationStyle::NoDecoration, |
| 1059 |
}; |
| 1060 |
} |
| 1061 |
lazy_static! { |
| 1062 |
static ref SUPERIMPOSED_STYLE: Style = Style { |
| 1063 |
ansi_term_style: ansi_term::Style { |
| 1064 |
foreground: to_ansi_color(SyntectColor::BLACK, true), |
| 1065 |
background: Some(Color::White), |
| 1066 |
is_underline: true, |
| 1067 |
..ansi_term::Style::new() |
| 1068 |
}, |
| 1069 |
is_emph: false, |
| 1070 |
is_omitted: false, |
| 1071 |
is_raw: false, |
| 1072 |
is_syntax_highlighted: true, |
| 1073 |
decoration_style: DecorationStyle::NoDecoration, |
| 1074 |
}; |
| 1075 |
} |
| 1076 |
|
| 1077 |
#[test] |
| 1078 |
fn test_superimpose_style_sections_1() { |
| 1079 |
let sections_1 = vec![(*SYNTAX_STYLE, "ab")]; |
| 1080 |
let sections_2 = vec![(*SYNTAX_HIGHLIGHTED_STYLE, "ab")]; |
| 1081 |
let superimposed = vec![(*SUPERIMPOSED_STYLE, "ab".to_string())]; |
| 1082 |
assert_eq!( |
| 1083 |
superimpose_style_sections(§ions_1, §ions_2, true, SyntectStyle::default()), |
| 1084 |
superimposed |
| 1085 |
); |
| 1086 |
} |
| 1087 |
|
| 1088 |
#[test] |
| 1089 |
fn test_superimpose_style_sections_2() { |
| 1090 |
let sections_1 = vec![(*SYNTAX_STYLE, "ab")]; |
| 1091 |
let sections_2 = vec![ |
| 1092 |
(*SYNTAX_HIGHLIGHTED_STYLE, "a"), |
| 1093 |
(*SYNTAX_HIGHLIGHTED_STYLE, "b"), |
| 1094 |
]; |
| 1095 |
let superimposed = vec![(*SUPERIMPOSED_STYLE, String::from("ab"))]; |
| 1096 |
assert_eq!( |
| 1097 |
superimpose_style_sections(§ions_1, §ions_2, true, SyntectStyle::default()), |
| 1098 |
superimposed |
| 1099 |
); |
| 1100 |
} |
| 1101 |
|
| 1102 |
#[test] |
| 1103 |
fn test_superimpose_style_sections_3() { |
| 1104 |
let sections_1 = vec![(*SYNTAX_STYLE, "ab")]; |
| 1105 |
let sections_2 = vec![(*NON_SYNTAX_HIGHLIGHTED_STYLE, "ab")]; |
| 1106 |
let superimposed = vec![(*NON_SYNTAX_HIGHLIGHTED_STYLE, "ab".to_string())]; |
| 1107 |
assert_eq!( |
| 1108 |
superimpose_style_sections(§ions_1, §ions_2, true, SyntectStyle::default()), |
| 1109 |
superimposed |
| 1110 |
); |
| 1111 |
} |
| 1112 |
|
| 1113 |
#[test] |
| 1114 |
fn test_explode() { |
| 1115 |
let arbitrary = 0; |
| 1116 |
assert_eq!( |
| 1117 |
explode(&[(arbitrary, "ab")]), |
| 1118 |
vec![(arbitrary, 'a'), (arbitrary, 'b')] |
| 1119 |
) |
| 1120 |
} |
| 1121 |
|
| 1122 |
#[test] |
| 1123 |
fn test_superimpose() { |
| 1124 |
let x = (*SYNTAX_STYLE, 'a'); |
| 1125 |
let pairs = vec![(&x, (*SYNTAX_HIGHLIGHTED_STYLE, 'a'))]; |
| 1126 |
assert_eq!( |
| 1127 |
superimpose(pairs), |
| 1128 |
vec![((*SYNTAX_STYLE, *SYNTAX_HIGHLIGHTED_STYLE), 'a')] |
| 1129 |
); |
| 1130 |
} |
| 1131 |
} |
| 1132 |
} |