Skip to content
Myr

colors: add `highlight` type support for matching lines

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This lets users highlight non-matching text in matching lines. Closes #3024, Closes #3107

authored by emrebengue · committed by Andrew Gallant · parent 126bbea · Browse files · 6 files+88 added−17 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+88 added−17 removed

  • other:+88 added−17 removed

6 files+88 added−17 removed

modified:crates/core/flags/complete/rg.zsh+2 added-1 removed
361 unmodified lines
362 tmp=(363 'column:specify coloring for column numbers'364 'line:specify coloring for line numbers'365 'match:specify coloring for match text'366 'highlight:specify coloring for matching lines'367 'path:specify coloring for file names'368 )369 descr='color/style type'369 elif [[ ${IPREFIX#--*=}$PREFIX == (column|line|match|path):[^:]# ]]; then370 elif [[ ${IPREFIX#--*=}$PREFIX == (column|line|match|highlight|path):[^:]# ]]; then371 suf=( -qS: )372 tmp=(373 'none:clear color/style for type'374 'bg:specify background color'
272 unmodified lines
modified:crates/core/flags/defs.rs+38 added-8 removed
749 unmodified lines
750.EX751 \-\-colors 'path:none' \\752 \-\-colors 'line:none' \\753 \-\-colors 'column:none' \\754 \-\-colors 'match:none'754 \-\-colors 'match:none' \\755 \-\-colors 'highlight:none'756.EE757.sp758"759 }
69 unmodified lines
829 fn doc_short(&self) -> &'static str {830 "Configure color settings and styles."831 }832 fn doc_long(&self) -> &'static str {832 r"833 r#"834This flag specifies color settings for use in the output. This flag may be835provided multiple times. Settings are applied iteratively. Pre-existing color836labels are limited to one of eight choices: \fBred\fP, \fBblue\fP, \fBgreen\fP,837\fBcyan\fP, \fBmagenta\fP, \fByellow\fP, \fBwhite\fP and \fBblack\fP. Styles
1 unmodified line
839\fBnounderline\fP, \fBunderline\fP, \fBnoitalic\fP or \fBitalic\fP.840.sp841The format of the flag is842\fB{\fP\fItype\fP\fB}:{\fP\fIattribute\fP\fB}:{\fP\fIvalue\fP\fB}\fP.842\fItype\fP should be one of \fBpath\fP, \fBline\fP, \fBcolumn\fP or843\fBmatch\fP. \fIattribute\fP can be \fBfg\fP, \fBbg\fP or \fBstyle\fP.844\fIvalue\fP is either a color (for \fBfg\fP and \fBbg\fP) or a text style. A845special format, \fB{\fP\fItype\fP\fB}:none\fP, will clear all color settings846for \fItype\fP.843\fItype\fP should be one of \fBpath\fP, \fBline\fP, \fBcolumn\fP,844\fBhighlight\fP or \fBmatch\fP. \fIattribute\fP can be \fBfg\fP, \fBbg\fP or845\fBstyle\fP. \fIvalue\fP is either a color (for \fBfg\fP and \fBbg\fP) or a846text style. A special format, \fB{\fP\fItype\fP\fB}:none\fP, will clear all847color settings for \fItype\fP.848.sp849For example, the following command will change the match color to magenta and850the background color for line numbers to yellow:851.sp852.EX853 rg \-\-colors 'match:fg:magenta' \-\-colors 'line:bg:yellow'854.EE855.sp856Another example, the following command will "highlight" the non-matching text857in matching lines:858.sp859.EX860 rg \-\-colors 'highlight:bg:yellow' \-\-colors 'highlight:fg:black'861.EE862.sp863The "highlight" color type is particularly useful for contrasting matching864lines with surrounding context printed by the \flag{before-context},865\flag{after-context}, \flag{context} or \flag{passthru} flags.866.sp867Extended colors can be used for \fIvalue\fP when the tty supports ANSI color868sequences. These are specified as either \fIx\fP (256-color) or869.IB x , x , x870(24-bit truecolor) where \fIx\fP is a number between \fB0\fP and \fB255\fP
14 unmodified lines
885.EE886.sp887Note that the \fBintense\fP and \fBnointense\fP styles will have no effect when888used alongside these extended color codes.877"889"#890 }891892 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {893 let v = v.unwrap_value();
25 unmodified lines
919 "match:fg:magenta".parse().unwrap(),920 "line:bg:yellow".parse().unwrap()921 ]922 );923924 let args = parse_low_raw(["--colors", "highlight:bg:240"]).unwrap();925 assert_eq!(args.colors, vec!["highlight:bg:240".parse().unwrap()]);926927 let args = parse_low_raw([928 "--colors",929 "match:fg:magenta",930 "--colors",931 "highlight:bg:blue",932 ])933 .unwrap();934 assert_eq!(935 args.colors,936 vec![937 "match:fg:magenta".parse().unwrap(),938 "highlight:bg:blue".parse().unwrap()939 ]940 );941}942943/// --column944#[derive(Debug)]
6770 unmodified lines
modified:crates/printer/src/color.rs+15 added-5 removed
49 unmodified lines
50 match *self {51 ColorError::UnrecognizedOutType(ref name) => write!(52 f,53 "unrecognized output type '{}'. Choose from: \54 path, line, column, match.",54 path, line, column, match, highlight.",55 name,56 ),57 ColorError::UnrecognizedSpecType(ref name) => write!(58 f,59 "unrecognized spec type '{}'. Choose from: \60 fg, bg, style, none.",60 fg, bg, style, none.",61 name,62 ),63 ColorError::UnrecognizedColor(_, ref msg) => write!(f, "{}", msg),64 ColorError::UnrecognizedStyle(ref name) => write!(
4 unmodified lines
69 name,70 ),71 ColorError::InvalidFormat(ref original) => write!(72 f,73 "invalid color spec format: '{}'. Valid format \74 is '(path|line|column|match):(fg|bg|style):(value)'.",73 "invalid color spec format: '{}'. Valid format is \74 '(path|line|column|match|highlight):(fg|bg|style):(value)'.",75 original,76 ),77 }78 }
10 unmodified lines
89 path: ColorSpec,90 line: ColorSpec,91 column: ColorSpec,92 matched: ColorSpec,93 highlight: ColorSpec,94}9596/// A single color specification provided by the user.97///
1 unmodified line
99///100/// The format of a `Spec` is a triple: `{type}:{attribute}:{value}`. Each101/// component is defined as follows:102///102/// * `{type}` can be one of `path`, `line`, `column` or `match`.103/// * `{type}` can be one of `path`, `line`, `column`, `match` or `highlight`.104/// * `{attribute}` can be one of `fg`, `bg` or `style`. `{attribute}` may also105/// be the special value `none`, in which case, `{value}` can be omitted.106/// * `{value}` is either a color name (for `fg`/`bg`) or a style instruction.107///
73 unmodified lines
181 Path,182 Line,183 Column,184 Match,185 Highlight,186}187188/// The specification type.189#[derive(Clone, Debug, Eq, PartialEq)]
27 unmodified lines
217 OutType::Path => spec.merge_into(&mut merged.path),218 OutType::Line => spec.merge_into(&mut merged.line),219 OutType::Column => spec.merge_into(&mut merged.column),220 OutType::Match => spec.merge_into(&mut merged.matched),221 OutType::Highlight => spec.merge_into(&mut merged.highlight),222 }223 }224 merged225 }
25 unmodified lines
251 /// Return the color specification for coloring matched text.252 pub fn matched(&self) -> &ColorSpec {253 &self.matched254 }255256 /// Return the color specification for coloring entire line if there is a257 /// matched text.258 pub fn highlight(&self) -> &ColorSpec {259 &self.highlight260 }261}262263impl UserColorSpec {264 /// Merge this spec into the given color specification.
91 unmodified lines
356 "path" => Ok(OutType::Path),357 "line" => Ok(OutType::Line),358 "column" => Ok(OutType::Column),359 "match" => Ok(OutType::Match),360 "highlight" => Ok(OutType::Highlight),361 _ => Err(ColorError::UnrecognizedOutType(s.to_string())),362 }363 }364}
32 unmodified lines
modified:crates/printer/src/standard.rs+29 added-1 removed
1318 unmodified lines
1319 if matches.is_empty() {1320 self.write(&bytes[line])?;1321 return Ok(());1322 }1323 self.start_line_highlight()?;1324 while !line.is_empty() {1325 if matches[*match_index].end() <= line.start() {1326 if *match_index + 1 < matches.len() {1327 *match_index += 1;
18 unmodified lines
1346 line = line.with_start(upto);1347 }1348 }1349 self.end_color_match()?;1350 self.end_line_highlight()?;1351 Ok(())1352 }13531354 fn write_exceeded_line(
193 unmodified lines
1548 fn end_color_match(&self) -> io::Result<()> {1549 if !self.in_color_match.get() {1550 return Ok(());1551 }1552 if self.highlight_on() {1553 self.wtr()1554 .borrow_mut()1555 .set_color(self.config().colors.highlight())?;1556 } else {1550 self.wtr().borrow_mut().reset()?;1557 self.wtr().borrow_mut().reset()?;1558 }1559 self.in_color_match.set(false);1560 Ok(())1561 }15621563 fn highlight_on(&self) -> bool {1564 !self.config().colors.highlight().is_none() && !self.is_context()1565 }15661567 fn start_line_highlight(&self) -> io::Result<()> {1568 if self.highlight_on() {1569 self.wtr()1570 .borrow_mut()1571 .set_color(self.config().colors.highlight())?;1572 }1573 Ok(())1574 }15751576 fn end_line_highlight(&self) -> io::Result<()> {1577 if self.highlight_on() {1578 self.wtr().borrow_mut().reset()?;1579 }1580 Ok(())1581 }15821583 fn write(&self, buf: &[u8]) -> io::Result<()> {1584 self.wtr().borrow_mut().write_all(buf)1585 }1586
2282 unmodified lines
modified:CHANGELOG.md+2 added
41 unmodified lines
42* [FEATURE #2849](https://github.com/BurntSushi/ripgrep/pull/2849):43 When using multithreading, schedule files to search in order given on CLI.44* [FEATURE #2943](https://github.com/BurntSushi/ripgrep/issues/2943):45 Add `aarch64` release artifacts for Windows.46* [FEATURE #3024](https://github.com/BurntSushi/ripgrep/issues/3024):47 Add `highlight` color type, for styling non-matching text in a matching line.48* [FEATURE #3048](https://github.com/BurntSushi/ripgrep/pull/3048):49 Globs in ripgrep (and the `globset` crate) now support nested alternates.5051
1711 unmodified lines
modified:FAQ.md+2 added-2 removed
283 unmodified lines
284As a special case, `--colors '{type}:none'` will clear all colors and styles285associated with `{type}`, which lets you start with a clean slate (instead of286building on top of ripgrep's default color settings).287288Here's an example that makes highlights the matches with a nice blue background289with bolded white text:288Here's an example that highlights the matches with a nice blue background with289bolded white text:290291```292$ rg somepattern \293 --colors 'match:none' \
770 unmodified lines