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
Provenance
- Commit
99fe884- Tree
2ac3034- Author
emrebengue <emrebengue@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
126bbea
6 files changed+88 added−17 removed
modified:crates/core/flags/complete/rg.zsh+2 added-1 removed
361 unmodified lines362 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 linesmodified:crates/core/flags/defs.rs+38 added-8 removed
749 unmodified lines750 .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 lines829 fn doc_short(&self) -> &'static str {830 "Configure color settings and styles."831 }832 fn doc_long(&self) -> &'static str {832- r"833+ r#"834 This flag specifies color settings for use in the output. This flag may be835 provided multiple times. Settings are applied iteratively. Pre-existing color836 labels 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. Styles1 unmodified line839 \fBnounderline\fP, \fBunderline\fP, \fBnoitalic\fP or \fBitalic\fP.840 .sp841 The 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. A845-special format, \fB{\fP\fItype\fP\fB}:none\fP, will clear all color settings846-for \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 a846+text style. A special format, \fB{\fP\fItype\fP\fB}:none\fP, will clear all847+color settings for \fItype\fP.848 .sp849 For example, the following command will change the match color to magenta and850 the background color for line numbers to yellow:851 .sp852 .EX853 rg \-\-colors 'match:fg:magenta' \-\-colors 'line:bg:yellow'854 .EE855 .sp856+Another example, the following command will "highlight" the non-matching text857+in matching lines:858+.sp859+.EX860+ rg \-\-colors 'highlight:bg:yellow' \-\-colors 'highlight:fg:black'861+.EE862+.sp863+The "highlight" color type is particularly useful for contrasting matching864+lines with surrounding context printed by the \flag{before-context},865+\flag{after-context}, \flag{context} or \flag{passthru} flags.866+.sp867 Extended colors can be used for \fIvalue\fP when the tty supports ANSI color868 sequences. 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\fP14 unmodified lines885 .EE886 .sp887 Note that the \fBintense\fP and \fBnointense\fP styles will have no effect when888 used alongside these extended color codes.877-"889+"#890 }891 892 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {893 let v = v.unwrap_value();25 unmodified lines919 "match:fg:magenta".parse().unwrap(),920 "line:bg:yellow".parse().unwrap()921 ]922 );923+924+ let args = parse_low_raw(["--colors", "highlight:bg:240"]).unwrap();925+ assert_eq!(args.colors, vec!["highlight:bg:240".parse().unwrap()]);926+927+ 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 }942 943 /// --column944 #[derive(Debug)]6770 unmodified linesmodified:crates/printer/src/color.rs+15 added-5 removed
49 unmodified lines50 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 lines69 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 lines89 path: ColorSpec,90 line: ColorSpec,91 column: ColorSpec,92 matched: ColorSpec,93+ highlight: ColorSpec,94 }95 96 /// A single color specification provided by the user.97 ///1 unmodified line99 ///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 lines181 Path,182 Line,183 Column,184 Match,185+ Highlight,186 }187 188 /// The specification type.189 #[derive(Clone, Debug, Eq, PartialEq)]27 unmodified lines217 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 lines251 /// Return the color specification for coloring matched text.252 pub fn matched(&self) -> &ColorSpec {253 &self.matched254 }255+256+ /// Return the color specification for coloring entire line if there is a257+ /// matched text.258+ pub fn highlight(&self) -> &ColorSpec {259+ &self.highlight260+ }261 }262 263 impl UserColorSpec {264 /// Merge this spec into the given color specification.91 unmodified lines356 "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 linesmodified:crates/printer/src/standard.rs+29 added-1 removed
1318 unmodified lines1319 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 lines1346 line = line.with_start(upto);1347 }1348 }1349 self.end_color_match()?;1350+ self.end_line_highlight()?;1351 Ok(())1352 }1353 1354 fn write_exceeded_line(193 unmodified lines1548 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 }1562 1563+ fn highlight_on(&self) -> bool {1564+ !self.config().colors.highlight().is_none() && !self.is_context()1565+ }1566+1567+ 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+ }1575+1576+ fn end_line_highlight(&self) -> io::Result<()> {1577+ if self.highlight_on() {1578+ self.wtr().borrow_mut().reset()?;1579+ }1580+ Ok(())1581+ }1582+1583 fn write(&self, buf: &[u8]) -> io::Result<()> {1584 self.wtr().borrow_mut().write_all(buf)1585 }1586 2282 unmodified linesmodified:CHANGELOG.md+2 added
41 unmodified lines42 * [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.50 51 1711 unmodified linesmodified:FAQ.md+2 added-2 removed
283 unmodified lines284 As a special case, `--colors '{type}:none'` will clear all colors and styles285 associated with `{type}`, which lets you start with a clean slate (instead of286 building on top of ripgrep's default color settings).287 288-Here's an example that makes highlights the matches with a nice blue background289-with bolded white text:288+Here's an example that highlights the matches with a nice blue background with289+bolded white text:290 291 ```292 $ rg somepattern \293 --colors 'match:none' \770 unmodified lines