standard.rs
This file
Path
crates/printer/src/standard.rs
3,987 lines · 133.1 KiB · Rust
Last changed by
style: apply rustfmtAndrew Gallantbefore adoptionbb8172f
History of this fileTake it
The walk stopped after 200 commits: lines older than 5f5da48 point at it.
globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 1–13why, one step back1use std::{2 cell::{Cell, RefCell},3 cmp,4 io::{self, Write},5 path::Path,6 sync::Arc,7 time::Instant,8};910use {11 bstr::ByteSlice,12 grep_matcher::{Match, Matcher},13 grep_searcher::{searcher: move "max matches" from printer to searcherPavel Safronovbefore adoptiona6e0be3
line 14why, one step back14 LineStep, Searcher, Sink, SinkContext, SinkFinish, SinkMatch,globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 15–25why, one step back15 },16 termcolor::{ColorSpec, NoColor, WriteColor},17};1819use crate::{20 color::ColorSpecs,21 counter::CounterWriter,22 hyperlink::{self, HyperlinkConfig},23 stats::Stats,24 util::{25 DecimalFormatter, PrinterPath, Replacer, Sunk,style: apply rustfmtAndrew Gallantbefore adoptionbb8172f
line 26why, one step back26 find_iter_at_in_context, trim_ascii_prefix, trim_line_terminator,globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 27–748why, one step back27 },28};2930/// The configuration for the standard printer.31///32/// This is manipulated by the StandardBuilder and then referenced by the33/// actual implementation. Once a printer is build, the configuration is frozen34/// and cannot changed.35#[derive(Debug, Clone)]36struct Config {37 colors: ColorSpecs,38 hyperlink: HyperlinkConfig,39 stats: bool,40 heading: bool,41 path: bool,42 only_matching: bool,43 per_match: bool,44 per_match_one_line: bool,45 replacement: Arc<Option<Vec<u8>>>,46 max_columns: Option<u64>,47 max_columns_preview: bool,48 column: bool,49 byte_offset: bool,50 trim_ascii: bool,51 separator_search: Arc<Option<Vec<u8>>>,52 separator_context: Arc<Option<Vec<u8>>>,53 separator_field_match: Arc<Vec<u8>>,54 separator_field_context: Arc<Vec<u8>>,55 separator_path: Option<u8>,56 path_terminator: Option<u8>,57}5859impl Default for Config {60 fn default() -> Config {61 Config {62 colors: ColorSpecs::default(),63 hyperlink: HyperlinkConfig::default(),64 stats: false,65 heading: false,66 path: true,67 only_matching: false,68 per_match: false,69 per_match_one_line: false,70 replacement: Arc::new(None),71 max_columns: None,72 max_columns_preview: false,73 column: false,74 byte_offset: false,75 trim_ascii: false,76 separator_search: Arc::new(None),77 separator_context: Arc::new(Some(b"--".to_vec())),78 separator_field_match: Arc::new(b":".to_vec()),79 separator_field_context: Arc::new(b"-".to_vec()),80 separator_path: None,81 path_terminator: None,82 }83 }84}8586/// A builder for the "standard" grep-like printer.87///88/// The builder permits configuring how the printer behaves. Configurable89/// behavior includes, but is not limited to, limiting the number of matches,90/// tweaking separators, executing pattern replacements, recording statistics91/// and setting colors.92///93/// Some configuration options, such as the display of line numbers or94/// contextual lines, are drawn directly from the95/// `grep_searcher::Searcher`'s configuration.96///97/// Once a `Standard` printer is built, its configuration cannot be changed.98#[derive(Clone, Debug)]99pub struct StandardBuilder {100 config: Config,101}102103impl StandardBuilder {104 /// Return a new builder for configuring the standard printer.105 pub fn new() -> StandardBuilder {106 StandardBuilder { config: Config::default() }107 }108109 /// Build a printer using any implementation of `termcolor::WriteColor`.110 ///111 /// The implementation of `WriteColor` used here controls whether colors112 /// are used or not when colors have been configured using the113 /// `color_specs` method.114 ///115 /// For maximum portability, callers should generally use either116 /// `termcolor::StandardStream` or `termcolor::BufferedStandardStream`117 /// where appropriate, which will automatically enable colors on Windows118 /// when possible.119 ///120 /// However, callers may also provide an arbitrary writer using the121 /// `termcolor::Ansi` or `termcolor::NoColor` wrappers, which always enable122 /// colors via ANSI escapes or always disable colors, respectively.123 ///124 /// As a convenience, callers may use `build_no_color` to automatically125 /// select the `termcolor::NoColor` wrapper to avoid needing to import126 /// from `termcolor` explicitly.127 pub fn build<W: WriteColor>(&self, wtr: W) -> Standard<W> {128 Standard {129 config: self.config.clone(),130 wtr: RefCell::new(CounterWriter::new(wtr)),131 matches: vec![],132 }133 }134135 /// Build a printer from any implementation of `io::Write` and never emit136 /// any colors, regardless of the user color specification settings.137 ///138 /// This is a convenience routine for139 /// `StandardBuilder::build(termcolor::NoColor::new(wtr))`.140 pub fn build_no_color<W: io::Write>(141 &self,142 wtr: W,143 ) -> Standard<NoColor<W>> {144 self.build(NoColor::new(wtr))145 }146147 /// Set the user color specifications to use for coloring in this printer.148 ///149 /// A [`UserColorSpec`](crate::UserColorSpec) can be constructed from150 /// a string in accordance with the color specification format. See151 /// the `UserColorSpec` type documentation for more details on the152 /// format. A [`ColorSpecs`] can then be generated from zero or more153 /// `UserColorSpec`s.154 ///155 /// Regardless of the color specifications provided here, whether color156 /// is actually used or not is determined by the implementation of157 /// `WriteColor` provided to `build`. For example, if `termcolor::NoColor`158 /// is provided to `build`, then no color will ever be printed regardless159 /// of the color specifications provided here.160 ///161 /// This completely overrides any previous color specifications. This does162 /// not add to any previously provided color specifications on this163 /// builder.164 pub fn color_specs(&mut self, specs: ColorSpecs) -> &mut StandardBuilder {165 self.config.colors = specs;166 self167 }168169 /// Set the configuration to use for hyperlinks output by this printer.170 ///171 /// Regardless of the hyperlink format provided here, whether hyperlinks172 /// are actually used or not is determined by the implementation of173 /// `WriteColor` provided to `build`. For example, if `termcolor::NoColor`174 /// is provided to `build`, then no hyperlinks will ever be printed175 /// regardless of the format provided here.176 ///177 /// This completely overrides any previous hyperlink format.178 ///179 /// The default configuration results in not emitting any hyperlinks.180 pub fn hyperlink(181 &mut self,182 config: HyperlinkConfig,183 ) -> &mut StandardBuilder {184 self.config.hyperlink = config;185 self186 }187188 /// Enable the gathering of various aggregate statistics.189 ///190 /// When this is enabled (it's disabled by default), statistics will be191 /// gathered for all uses of `Standard` printer returned by `build`,192 /// including but not limited to, the total number of matches, the total193 /// number of bytes searched and the total number of bytes printed.194 ///195 /// Aggregate statistics can be accessed via the sink's196 /// [`StandardSink::stats`] method.197 ///198 /// When this is enabled, this printer may need to do extra work in order199 /// to compute certain statistics, which could cause the search to take200 /// longer.201 ///202 /// For a complete description of available statistics, see [`Stats`].203 pub fn stats(&mut self, yes: bool) -> &mut StandardBuilder {204 self.config.stats = yes;205 self206 }207208 /// Enable the use of "headings" in the printer.209 ///210 /// When this is enabled, and if a file path has been given to the printer,211 /// then the file path will be printed once on its own line before showing212 /// any matches. If the heading is not the first thing emitted by the213 /// printer, then a line terminator is printed before the heading.214 ///215 /// By default, this option is disabled. When disabled, the printer will216 /// not show any heading and will instead print the file path (if one is217 /// given) on the same line as each matching (or context) line.218 pub fn heading(&mut self, yes: bool) -> &mut StandardBuilder {219 self.config.heading = yes;220 self221 }222223 /// When enabled, if a path was given to the printer, then it is shown in224 /// the output (either as a heading or as a prefix to each matching line).225 /// When disabled, then no paths are ever included in the output even when226 /// a path is provided to the printer.227 ///228 /// This is enabled by default.229 pub fn path(&mut self, yes: bool) -> &mut StandardBuilder {230 self.config.path = yes;231 self232 }233234 /// Only print the specific matches instead of the entire line containing235 /// each match. Each match is printed on its own line. When multi line236 /// search is enabled, then matches spanning multiple lines are printed237 /// such that only the matching portions of each line are shown.238 pub fn only_matching(&mut self, yes: bool) -> &mut StandardBuilder {239 self.config.only_matching = yes;240 self241 }242243 /// Print at least one line for every match.244 ///245 /// This is similar to the `only_matching` option, except the entire line246 /// is printed for each match. This is typically useful in conjunction with247 /// the `column` option, which will show the starting column number for248 /// every match on every line.249 ///250 /// When multi-line mode is enabled, each match is printed, including every251 /// line in the match. As with single line matches, if a line contains252 /// multiple matches (even if only partially), then that line is printed253 /// once for each match it participates in, assuming it's the first line in254 /// that match. In multi-line mode, column numbers only indicate the start255 /// of a match. Subsequent lines in a multi-line match always have a column256 /// number of `1`.257 ///258 /// When a match contains multiple lines, enabling `per_match_one_line`259 /// will cause only the first line each in match to be printed.260 pub fn per_match(&mut self, yes: bool) -> &mut StandardBuilder {261 self.config.per_match = yes;262 self263 }264265 /// Print at most one line per match when `per_match` is enabled.266 ///267 /// By default, every line in each match found is printed when `per_match`268 /// is enabled. However, this is sometimes undesirable, e.g., when you269 /// only ever want one line per match.270 ///271 /// This is only applicable when multi-line matching is enabled, since272 /// otherwise, matches are guaranteed to span one line.273 ///274 /// This is disabled by default.275 pub fn per_match_one_line(&mut self, yes: bool) -> &mut StandardBuilder {276 self.config.per_match_one_line = yes;277 self278 }279280 /// Set the bytes that will be used to replace each occurrence of a match281 /// found.282 ///283 /// The replacement bytes given may include references to capturing groups,284 /// which may either be in index form (e.g., `$2`) or can reference named285 /// capturing groups if present in the original pattern (e.g., `$foo`).286 ///287 /// For documentation on the full format, please see the `Capture` trait's288 /// `interpolate` method in the289 /// [grep-printer](https://docs.rs/grep-printer) crate.290 pub fn replacement(291 &mut self,292 replacement: Option<Vec<u8>>,293 ) -> &mut StandardBuilder {294 self.config.replacement = Arc::new(replacement);295 self296 }297298 /// Set the maximum number of columns allowed for each line printed. A299 /// single column is heuristically defined as a single byte.300 ///301 /// If a line is found which exceeds this maximum, then it is replaced302 /// with a message indicating that the line has been omitted.303 ///304 /// The default is to not specify a limit, in which each matching or305 /// contextual line is printed regardless of how long it is.306 pub fn max_columns(&mut self, limit: Option<u64>) -> &mut StandardBuilder {307 self.config.max_columns = limit;308 self309 }310311 /// When enabled, if a line is found to be over the configured maximum312 /// column limit (measured in terms of bytes), then a preview of the long313 /// line will be printed instead.314 ///315 /// The preview will correspond to the first `N` *grapheme clusters* of316 /// the line, where `N` is the limit configured by `max_columns`.317 ///318 /// If no limit is set, then enabling this has no effect.319 ///320 /// This is disabled by default.321 pub fn max_columns_preview(&mut self, yes: bool) -> &mut StandardBuilder {322 self.config.max_columns_preview = yes;323 self324 }325326 /// Print the column number of the first match in a line.327 ///328 /// This option is convenient for use with `per_match` which will print a329 /// line for every match along with the starting offset for that match.330 ///331 /// Column numbers are computed in terms of bytes from the start of the332 /// line being printed.333 ///334 /// This is disabled by default.335 pub fn column(&mut self, yes: bool) -> &mut StandardBuilder {336 self.config.column = yes;337 self338 }339340 /// Print the absolute byte offset of the beginning of each line printed.341 ///342 /// The absolute byte offset starts from the beginning of each search and343 /// is zero based.344 ///345 /// If the `only_matching` option is set, then this will print the absolute346 /// byte offset of the beginning of each match.347 pub fn byte_offset(&mut self, yes: bool) -> &mut StandardBuilder {348 self.config.byte_offset = yes;349 self350 }351352 /// When enabled, all lines will have prefix ASCII whitespace trimmed353 /// before being written.354 ///355 /// This is disabled by default.356 pub fn trim_ascii(&mut self, yes: bool) -> &mut StandardBuilder {357 self.config.trim_ascii = yes;358 self359 }360361 /// Set the separator used between sets of search results.362 ///363 /// When this is set, then it will be printed on its own line immediately364 /// before the results for a single search if and only if a previous search365 /// had already printed results. In effect, this permits showing a divider366 /// between sets of search results that does not appear at the beginning367 /// or end of all search results.368 ///369 /// To reproduce the classic grep format, this is typically set to `--`370 /// (the same as the context separator) if and only if contextual lines371 /// have been requested, but disabled otherwise.372 ///373 /// By default, this is disabled.374 pub fn separator_search(375 &mut self,376 sep: Option<Vec<u8>>,377 ) -> &mut StandardBuilder {378 self.config.separator_search = Arc::new(sep);379 self380 }381382 /// Set the separator used between discontiguous runs of search context,383 /// but only when the searcher is configured to report contextual lines.384 ///385 /// The separator is always printed on its own line, even if it's empty.386 ///387 /// If no separator is set, then nothing is printed when a context break388 /// occurs.389 ///390 /// By default, this is set to `--`.391 pub fn separator_context(392 &mut self,393 sep: Option<Vec<u8>>,394 ) -> &mut StandardBuilder {395 self.config.separator_context = Arc::new(sep);396 self397 }398399 /// Set the separator used between fields emitted for matching lines.400 ///401 /// For example, when the searcher has line numbers enabled, this printer402 /// will print the line number before each matching line. The bytes given403 /// here will be written after the line number but before the matching404 /// line.405 ///406 /// By default, this is set to `:`.407 pub fn separator_field_match(408 &mut self,409 sep: Vec<u8>,410 ) -> &mut StandardBuilder {411 self.config.separator_field_match = Arc::new(sep);412 self413 }414415 /// Set the separator used between fields emitted for context lines.416 ///417 /// For example, when the searcher has line numbers enabled, this printer418 /// will print the line number before each context line. The bytes given419 /// here will be written after the line number but before the context420 /// line.421 ///422 /// By default, this is set to `-`.423 pub fn separator_field_context(424 &mut self,425 sep: Vec<u8>,426 ) -> &mut StandardBuilder {427 self.config.separator_field_context = Arc::new(sep);428 self429 }430431 /// Set the path separator used when printing file paths.432 ///433 /// When a printer is configured with a file path, and when a match is434 /// found, that file path will be printed (either as a heading or as a435 /// prefix to each matching or contextual line, depending on other436 /// configuration settings). Typically, printing is done by emitting the437 /// file path as is. However, this setting provides the ability to use a438 /// different path separator from what the current environment has439 /// configured.440 ///441 /// A typical use for this option is to permit cygwin users on Windows to442 /// set the path separator to `/` instead of using the system default of443 /// `\`.444 pub fn separator_path(&mut self, sep: Option<u8>) -> &mut StandardBuilder {445 self.config.separator_path = sep;446 self447 }448449 /// Set the path terminator used.450 ///451 /// The path terminator is a byte that is printed after every file path452 /// emitted by this printer.453 ///454 /// If no path terminator is set (the default), then paths are terminated455 /// by either new lines (for when `heading` is enabled) or the match or456 /// context field separators (e.g., `:` or `-`).457 pub fn path_terminator(458 &mut self,459 terminator: Option<u8>,460 ) -> &mut StandardBuilder {461 self.config.path_terminator = terminator;462 self463 }464}465466/// The standard printer, which implements grep-like formatting, including467/// color support.468///469/// A default printer can be created with either of the `Standard::new` or470/// `Standard::new_no_color` constructors. However, there are a considerable471/// number of options that configure this printer's output. Those options can472/// be configured using [`StandardBuilder`].473///474/// This type is generic over `W`, which represents any implementation475/// of the `termcolor::WriteColor` trait. If colors are not desired,476/// then the `new_no_color` constructor can be used, or, alternatively,477/// the `termcolor::NoColor` adapter can be used to wrap any `io::Write`478/// implementation without enabling any colors.479#[derive(Clone, Debug)]480pub struct Standard<W> {481 config: Config,482 wtr: RefCell<CounterWriter<W>>,483 matches: Vec<Match>,484}485486impl<W: WriteColor> Standard<W> {487 /// Return a standard printer with a default configuration that writes488 /// matches to the given writer.489 ///490 /// The writer should be an implementation of `termcolor::WriteColor`491 /// and not just a bare implementation of `io::Write`. To use a normal492 /// `io::Write` implementation (simultaneously sacrificing colors), use493 /// the `new_no_color` constructor.494 pub fn new(wtr: W) -> Standard<W> {495 StandardBuilder::new().build(wtr)496 }497}498499impl<W: io::Write> Standard<NoColor<W>> {500 /// Return a standard printer with a default configuration that writes501 /// matches to the given writer.502 ///503 /// The writer can be any implementation of `io::Write`. With this504 /// constructor, the printer will never emit colors.505 pub fn new_no_color(wtr: W) -> Standard<NoColor<W>> {506 StandardBuilder::new().build_no_color(wtr)507 }508}509510impl<W: WriteColor> Standard<W> {511 /// Return an implementation of `Sink` for the standard printer.512 ///513 /// This does not associate the printer with a file path, which means this514 /// implementation will never print a file path along with the matches.515 pub fn sink<'s, M: Matcher>(516 &'s mut self,517 matcher: M,518 ) -> StandardSink<'static, 's, M, W> {519 let interpolator =520 hyperlink::Interpolator::new(&self.config.hyperlink);521 let stats = if self.config.stats { Some(Stats::new()) } else { None };522 let needs_match_granularity = self.needs_match_granularity();523 StandardSink {524 matcher,525 standard: self,526 replacer: Replacer::new(),527 interpolator,528 path: None,529 start_time: Instant::now(),530 match_count: 0,531 binary_byte_offset: None,532 stats,533 needs_match_granularity,534 }535 }536537 /// Return an implementation of `Sink` associated with a file path.538 ///539 /// When the printer is associated with a path, then it may, depending on540 /// its configuration, print the path along with the matches found.541 pub fn sink_with_path<'p, 's, M, P>(542 &'s mut self,543 matcher: M,544 path: &'p P,545 ) -> StandardSink<'p, 's, M, W>546 where547 M: Matcher,548 P: ?Sized + AsRef<Path>,549 {550 if !self.config.path {551 return self.sink(matcher);552 }553 let interpolator =554 hyperlink::Interpolator::new(&self.config.hyperlink);555 let stats = if self.config.stats { Some(Stats::new()) } else { None };556 let ppath = PrinterPath::new(path.as_ref())557 .with_separator(self.config.separator_path);558 let needs_match_granularity = self.needs_match_granularity();559 StandardSink {560 matcher,561 standard: self,562 replacer: Replacer::new(),563 interpolator,564 path: Some(ppath),565 start_time: Instant::now(),566 match_count: 0,567 binary_byte_offset: None,568 stats,569 needs_match_granularity,570 }571 }572573 /// Returns true if and only if the configuration of the printer requires574 /// us to find each individual match in the lines reported by the searcher.575 ///576 /// We care about this distinction because finding each individual match577 /// costs more, so we only do it when we need to.578 fn needs_match_granularity(&self) -> bool {579 let supports_color = self.wtr.borrow().supports_color();580 let match_colored = !self.config.colors.matched().is_none();581582 // Coloring requires identifying each individual match.583 (supports_color && match_colored)584 // The column feature requires finding the position of the first match.585 || self.config.column586 // Requires finding each match for performing replacement.587 || self.config.replacement.is_some()588 // Emitting a line for each match requires finding each match.589 || self.config.per_match590 // Emitting only the match requires finding each match.591 || self.config.only_matching592 // Computing certain statistics requires finding each match.593 || self.config.stats594 }595}596597impl<W> Standard<W> {598 /// Returns true if and only if this printer has written at least one byte599 /// to the underlying writer during any of the previous searches.600 pub fn has_written(&self) -> bool {601 self.wtr.borrow().total_count() > 0602 }603604 /// Return a mutable reference to the underlying writer.605 pub fn get_mut(&mut self) -> &mut W {606 self.wtr.get_mut().get_mut()607 }608609 /// Consume this printer and return back ownership of the underlying610 /// writer.611 pub fn into_inner(self) -> W {612 self.wtr.into_inner().into_inner()613 }614}615616/// An implementation of `Sink` associated with a matcher and an optional file617/// path for the standard printer.618///619/// A `Sink` can be created via the [`Standard::sink`] or620/// [`Standard::sink_with_path`] methods, depending on whether you want to621/// include a file path in the printer's output.622///623/// Building a `StandardSink` is cheap, and callers should create a new one624/// for each thing that is searched. After a search has completed, callers may625/// query this sink for information such as whether a match occurred or whether626/// binary data was found (and if so, the offset at which it occurred).627///628/// This type is generic over a few type parameters:629///630/// * `'p` refers to the lifetime of the file path, if one is provided. When631/// no file path is given, then this is `'static`.632/// * `'s` refers to the lifetime of the [`Standard`] printer that this type633/// borrows.634/// * `M` refers to the type of matcher used by635/// `grep_searcher::Searcher` that is reporting results to this sink.636/// * `W` refers to the underlying writer that this printer is writing its637/// output to.638#[derive(Debug)]639pub struct StandardSink<'p, 's, M: Matcher, W> {640 matcher: M,641 standard: &'s mut Standard<W>,642 replacer: Replacer<M>,643 interpolator: hyperlink::Interpolator,644 path: Option<PrinterPath<'p>>,645 start_time: Instant,646 match_count: u64,647 binary_byte_offset: Option<u64>,648 stats: Option<Stats>,649 needs_match_granularity: bool,650}651652impl<'p, 's, M: Matcher, W: WriteColor> StandardSink<'p, 's, M, W> {653 /// Returns true if and only if this printer received a match in the654 /// previous search.655 ///656 /// This is unaffected by the result of searches before the previous657 /// search on this sink.658 pub fn has_match(&self) -> bool {659 self.match_count > 0660 }661662 /// Return the total number of matches reported to this sink.663 ///664 /// This corresponds to the number of times `Sink::matched` is called665 /// on the previous search.666 ///667 /// This is unaffected by the result of searches before the previous668 /// search on this sink.669 pub fn match_count(&self) -> u64 {670 self.match_count671 }672673 /// If binary data was found in the previous search, this returns the674 /// offset at which the binary data was first detected.675 ///676 /// The offset returned is an absolute offset relative to the entire677 /// set of bytes searched.678 ///679 /// This is unaffected by the result of searches before the previous680 /// search. e.g., If the search prior to the previous search found binary681 /// data but the previous search found no binary data, then this will682 /// return `None`.683 pub fn binary_byte_offset(&self) -> Option<u64> {684 self.binary_byte_offset685 }686687 /// Return a reference to the stats produced by the printer for all688 /// searches executed on this sink.689 ///690 /// This only returns stats if they were requested via the691 /// [`StandardBuilder`] configuration.692 pub fn stats(&self) -> Option<&Stats> {693 self.stats.as_ref()694 }695696 /// Execute the matcher over the given bytes and record the match697 /// locations if the current configuration demands match granularity.698 fn record_matches(699 &mut self,700 searcher: &Searcher,701 bytes: &[u8],702 range: std::ops::Range<usize>,703 ) -> io::Result<()> {704 self.standard.matches.clear();705 if !self.needs_match_granularity {706 return Ok(());707 }708 // If printing requires knowing the location of each individual match,709 // then compute and stored those right now for use later. While this710 // adds an extra copy for storing the matches, we do amortize the711 // allocation for it and this greatly simplifies the printing logic to712 // the extent that it's easy to ensure that we never do more than713 // one search to find the matches (well, for replacements, we do one714 // additional search to perform the actual replacement).715 let matches = &mut self.standard.matches;716 find_iter_at_in_context(717 searcher,718 &self.matcher,719 bytes,720 range.clone(),721 |m| {722 let (s, e) = (m.start() - range.start, m.end() - range.start);723 matches.push(Match::new(s, e));724 true725 },726 )?;727 // Don't report empty matches appearing at the end of the bytes.728 if !matches.is_empty()729 && matches.last().unwrap().is_empty()730 && matches.last().unwrap().start() >= range.end731 {732 matches.pop().unwrap();733 }734 Ok(())735 }736737 /// If the configuration specifies a replacement, then this executes the738 /// replacement, lazily allocating memory if necessary.739 ///740 /// To access the result of a replacement, use `replacer.replacement()`.741 fn replace(742 &mut self,743 searcher: &Searcher,744 bytes: &[u8],745 range: std::ops::Range<usize>,746 ) -> io::Result<()> {747 self.replacer.clear();748 if self.standard.config.replacement.is_some() {printer: slightly simplify codeChristopherYoungbefore adoption5e2d32f
lines 749–750why, one step back749 let replacement =750 (*self.standard.config.replacement).as_ref().unwrap();globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 751–789why, one step back751 self.replacer.replace_all(752 searcher,753 &self.matcher,754 bytes,755 range,756 replacement,757 )?;758 }759 Ok(())760 }761}762763impl<'p, 's, M: Matcher, W: WriteColor> Sink for StandardSink<'p, 's, M, W> {764 type Error = io::Error;765766 fn matched(767 &mut self,768 searcher: &Searcher,769 mat: &SinkMatch<'_>,770 ) -> Result<bool, io::Error> {771 self.match_count += 1;772773 self.record_matches(774 searcher,775 mat.buffer(),776 mat.bytes_range_in_buffer(),777 )?;778 self.replace(searcher, mat.buffer(), mat.bytes_range_in_buffer())?;779780 if let Some(ref mut stats) = self.stats {781 stats.add_matches(self.standard.matches.len() as u64);782 stats.add_matched_lines(mat.lines().count() as u64);783 }784 if searcher.binary_detection().convert_byte().is_some() {785 if self.binary_byte_offset.is_some() {786 return Ok(false);787 }788 }789 StandardImpl::from_match(searcher, self, mat).sink()?;searcher: move "max matches" from printer to searcherPavel Safronovbefore adoptiona6e0be3
line 790why, one step back790 Ok(true)globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 791–811why, one step back791 }792793 fn context(794 &mut self,795 searcher: &Searcher,796 ctx: &SinkContext<'_>,797 ) -> Result<bool, io::Error> {798 self.standard.matches.clear();799 self.replacer.clear();800801 if searcher.invert_match() {802 self.record_matches(searcher, ctx.bytes(), 0..ctx.bytes().len())?;803 self.replace(searcher, ctx.bytes(), 0..ctx.bytes().len())?;804 }805 if searcher.binary_detection().convert_byte().is_some() {806 if self.binary_byte_offset.is_some() {807 return Ok(false);808 }809 }810811 StandardImpl::from_context(searcher, self, ctx).sink()?;searcher: move "max matches" from printer to searcherPavel Safronovbefore adoptiona6e0be3
line 812why, one step back812 Ok(true)globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 813–1258why, one step back813 }814815 fn context_break(816 &mut self,817 searcher: &Searcher,818 ) -> Result<bool, io::Error> {819 StandardImpl::new(searcher, self).write_context_separator()?;820 Ok(true)821 }822823 fn binary_data(824 &mut self,825 searcher: &Searcher,826 binary_byte_offset: u64,827 ) -> Result<bool, io::Error> {828 if searcher.binary_detection().quit_byte().is_some() {829 if let Some(ref path) = self.path {830 log::debug!(831 "ignoring {path}: found binary data at \832 offset {binary_byte_offset}",833 path = path.as_path().display(),834 );835 }836 }837 self.binary_byte_offset = Some(binary_byte_offset);838 Ok(true)839 }840841 fn begin(&mut self, _searcher: &Searcher) -> Result<bool, io::Error> {842 self.standard.wtr.borrow_mut().reset_count();843 self.start_time = Instant::now();844 self.match_count = 0;845 self.binary_byte_offset = None;846 Ok(true)847 }848849 fn finish(850 &mut self,851 searcher: &Searcher,852 finish: &SinkFinish,853 ) -> Result<(), io::Error> {854 if let Some(offset) = self.binary_byte_offset {855 StandardImpl::new(searcher, self).write_binary_message(offset)?;856 }857 if let Some(stats) = self.stats.as_mut() {858 stats.add_elapsed(self.start_time.elapsed());859 stats.add_searches(1);860 if self.match_count > 0 {861 stats.add_searches_with_match(1);862 }863 stats.add_bytes_searched(finish.byte_count());864 stats.add_bytes_printed(self.standard.wtr.borrow().count());865 }866 Ok(())867 }868}869870/// The actual implementation of the standard printer. This couples together871/// the searcher, the sink implementation and information about the match.872///873/// A StandardImpl is initialized every time a match or a contextual line is874/// reported.875#[derive(Debug)]876struct StandardImpl<'a, M: Matcher, W> {877 searcher: &'a Searcher,878 sink: &'a StandardSink<'a, 'a, M, W>,879 sunk: Sunk<'a>,880 /// Set to true if and only if we are writing a match with color.881 in_color_match: Cell<bool>,882}883884impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {885 /// Bundle self with a searcher and return the core implementation of Sink.886 fn new(887 searcher: &'a Searcher,888 sink: &'a StandardSink<'_, '_, M, W>,889 ) -> StandardImpl<'a, M, W> {890 StandardImpl {891 searcher,892 sink,893 sunk: Sunk::empty(),894 in_color_match: Cell::new(false),895 }896 }897898 /// Bundle self with a searcher and return the core implementation of Sink899 /// for use with handling matching lines.900 fn from_match(901 searcher: &'a Searcher,902 sink: &'a StandardSink<'_, '_, M, W>,903 mat: &'a SinkMatch<'a>,904 ) -> StandardImpl<'a, M, W> {905 let sunk = Sunk::from_sink_match(906 mat,907 &sink.standard.matches,908 sink.replacer.replacement(),909 );910 StandardImpl { sunk, ..StandardImpl::new(searcher, sink) }911 }912913 /// Bundle self with a searcher and return the core implementation of Sink914 /// for use with handling contextual lines.915 fn from_context(916 searcher: &'a Searcher,917 sink: &'a StandardSink<'_, '_, M, W>,918 ctx: &'a SinkContext<'a>,919 ) -> StandardImpl<'a, M, W> {920 let sunk = Sunk::from_sink_context(921 ctx,922 &sink.standard.matches,923 sink.replacer.replacement(),924 );925 StandardImpl { sunk, ..StandardImpl::new(searcher, sink) }926 }927928 fn sink(&self) -> io::Result<()> {929 self.write_search_prelude()?;930 if self.sunk.matches().is_empty() {931 if self.multi_line() && !self.is_context() {932 self.sink_fast_multi_line()933 } else {934 self.sink_fast()935 }936 } else {937 if self.multi_line() && !self.is_context() {938 self.sink_slow_multi_line()939 } else {940 self.sink_slow()941 }942 }943 }944945 /// Print matches (limited to one line) quickly by avoiding the detection946 /// of each individual match in the lines reported in the given947 /// `SinkMatch`.948 ///949 /// This should only be used when the configuration does not demand match950 /// granularity and the searcher is not in multi line mode.951 fn sink_fast(&self) -> io::Result<()> {952 debug_assert!(self.sunk.matches().is_empty());953 debug_assert!(!self.multi_line() || self.is_context());954955 self.write_prelude(956 self.sunk.absolute_byte_offset(),957 self.sunk.line_number(),958 None,959 )?;960 self.write_line(self.sunk.bytes())961 }962963 /// Print matches (possibly spanning more than one line) quickly by964 /// avoiding the detection of each individual match in the lines reported965 /// in the given `SinkMatch`.966 ///967 /// This should only be used when the configuration does not demand match968 /// granularity. This may be used when the searcher is in multi line mode.969 fn sink_fast_multi_line(&self) -> io::Result<()> {970 debug_assert!(self.sunk.matches().is_empty());971 // This isn't actually a required invariant for using this method,972 // but if we wind up here and multi line mode is disabled, then we973 // should still treat it as a bug since we should be using matched_fast974 // instead.975 debug_assert!(self.multi_line());976977 let line_term = self.searcher.line_terminator().as_byte();978 let mut absolute_byte_offset = self.sunk.absolute_byte_offset();979 for (i, line) in self.sunk.lines(line_term).enumerate() {980 self.write_prelude(981 absolute_byte_offset,982 self.sunk.line_number().map(|n| n + i as u64),983 None,984 )?;985 absolute_byte_offset += line.len() as u64;986987 self.write_line(line)?;988 }989 Ok(())990 }991992 /// Print a matching line where the configuration of the printer requires993 /// finding each individual match (e.g., for coloring).994 fn sink_slow(&self) -> io::Result<()> {995 debug_assert!(!self.sunk.matches().is_empty());996 debug_assert!(!self.multi_line() || self.is_context());997998 if self.config().only_matching {999 for &m in self.sunk.matches() {1000 self.write_prelude(1001 self.sunk.absolute_byte_offset() + m.start() as u64,1002 self.sunk.line_number(),1003 Some(m.start() as u64 + 1),1004 )?;10051006 let buf = &self.sunk.bytes()[m];1007 self.write_colored_line(&[Match::new(0, buf.len())], buf)?;1008 }1009 } else if self.config().per_match {1010 for &m in self.sunk.matches() {1011 self.write_prelude(1012 self.sunk.absolute_byte_offset() + m.start() as u64,1013 self.sunk.line_number(),1014 Some(m.start() as u64 + 1),1015 )?;1016 self.write_colored_line(&[m], self.sunk.bytes())?;1017 }1018 } else {1019 self.write_prelude(1020 self.sunk.absolute_byte_offset(),1021 self.sunk.line_number(),1022 Some(self.sunk.matches()[0].start() as u64 + 1),1023 )?;1024 self.write_colored_line(self.sunk.matches(), self.sunk.bytes())?;1025 }1026 Ok(())1027 }10281029 fn sink_slow_multi_line(&self) -> io::Result<()> {1030 debug_assert!(!self.sunk.matches().is_empty());1031 debug_assert!(self.multi_line());10321033 if self.config().only_matching {1034 return self.sink_slow_multi_line_only_matching();1035 } else if self.config().per_match {1036 return self.sink_slow_multi_per_match();1037 }10381039 let line_term = self.searcher.line_terminator().as_byte();1040 let bytes = self.sunk.bytes();1041 let matches = self.sunk.matches();1042 let mut midx = 0;1043 let mut count = 0;1044 let mut stepper = LineStep::new(line_term, 0, bytes.len());1045 while let Some((start, end)) = stepper.next(bytes) {1046 let mut line = Match::new(start, end);1047 self.write_prelude(1048 self.sunk.absolute_byte_offset() + line.start() as u64,1049 self.sunk.line_number().map(|n| n + count),1050 Some(matches[0].start() as u64 + 1),1051 )?;1052 count += 1;1053 self.trim_ascii_prefix(bytes, &mut line);1054 if self.exceeds_max_columns(&bytes[line]) {1055 self.write_exceeded_line(bytes, line, matches, &mut midx)?;1056 } else {1057 self.write_colored_matches(bytes, line, matches, &mut midx)?;1058 self.write_line_term()?;1059 }1060 }1061 Ok(())1062 }10631064 fn sink_slow_multi_line_only_matching(&self) -> io::Result<()> {1065 let line_term = self.searcher.line_terminator().as_byte();1066 let spec = self.config().colors.matched();1067 let bytes = self.sunk.bytes();1068 let matches = self.sunk.matches();1069 let mut midx = 0;1070 let mut count = 0;1071 let mut stepper = LineStep::new(line_term, 0, bytes.len());1072 while let Some((start, end)) = stepper.next(bytes) {1073 let mut line = Match::new(start, end);1074 self.trim_line_terminator(bytes, &mut line);1075 self.trim_ascii_prefix(bytes, &mut line);1076 while !line.is_empty() {1077 if matches[midx].end() <= line.start() {1078 if midx + 1 < matches.len() {1079 midx += 1;1080 continue;1081 } else {1082 break;1083 }1084 }1085 let m = matches[midx];10861087 if line.start() < m.start() {1088 let upto = cmp::min(line.end(), m.start());1089 line = line.with_start(upto);1090 } else {1091 let upto = cmp::min(line.end(), m.end());1092 self.write_prelude(1093 self.sunk.absolute_byte_offset() + m.start() as u64,1094 self.sunk.line_number().map(|n| n + count),1095 Some(m.start() as u64 + 1),1096 )?;10971098 let this_line = line.with_end(upto);1099 line = line.with_start(upto);1100 if self.exceeds_max_columns(&bytes[this_line]) {1101 self.write_exceeded_line(1102 bytes, this_line, matches, &mut midx,1103 )?;1104 } else {1105 self.write_spec(spec, &bytes[this_line])?;1106 self.write_line_term()?;1107 }1108 }1109 }1110 count += 1;1111 }1112 Ok(())1113 }11141115 fn sink_slow_multi_per_match(&self) -> io::Result<()> {1116 let line_term = self.searcher.line_terminator().as_byte();1117 let spec = self.config().colors.matched();1118 let bytes = self.sunk.bytes();1119 for &m in self.sunk.matches() {1120 let mut count = 0;1121 let mut stepper = LineStep::new(line_term, 0, bytes.len());1122 while let Some((start, end)) = stepper.next(bytes) {1123 let mut line = Match::new(start, end);1124 if line.start() >= m.end() {1125 break;1126 } else if line.end() <= m.start() {1127 count += 1;1128 continue;1129 }1130 self.write_prelude(1131 self.sunk.absolute_byte_offset() + line.start() as u64,1132 self.sunk.line_number().map(|n| n + count),1133 Some(m.start().saturating_sub(line.start()) as u64 + 1),1134 )?;1135 count += 1;1136 self.trim_line_terminator(bytes, &mut line);1137 self.trim_ascii_prefix(bytes, &mut line);1138 if self.exceeds_max_columns(&bytes[line]) {1139 self.write_exceeded_line(bytes, line, &[m], &mut 0)?;1140 continue;1141 }11421143 while !line.is_empty() {1144 if m.end() <= line.start() {1145 self.write(&bytes[line])?;1146 line = line.with_start(line.end());1147 } else if line.start() < m.start() {1148 let upto = cmp::min(line.end(), m.start());1149 self.write(&bytes[line.with_end(upto)])?;1150 line = line.with_start(upto);1151 } else {1152 let upto = cmp::min(line.end(), m.end());1153 self.write_spec(spec, &bytes[line.with_end(upto)])?;1154 line = line.with_start(upto);1155 }1156 }1157 self.write_line_term()?;1158 // It turns out that vimgrep really only wants one line per1159 // match, even when a match spans multiple lines. So when1160 // that option is enabled, we just quit after printing the1161 // first line.1162 //1163 // See: https://github.com/BurntSushi/ripgrep/issues/18661164 if self.config().per_match_one_line {1165 break;1166 }1167 }1168 }1169 Ok(())1170 }11711172 /// Write the beginning part of a matching line. This (may) include things1173 /// like the file path, line number among others, depending on the1174 /// configuration and the parameters given.1175 #[inline(always)]1176 fn write_prelude(1177 &self,1178 absolute_byte_offset: u64,1179 line_number: Option<u64>,1180 column: Option<u64>,1181 ) -> io::Result<()> {1182 let mut prelude = PreludeWriter::new(self);1183 prelude.start(line_number, column)?;1184 prelude.write_path()?;1185 prelude.write_line_number(line_number)?;1186 prelude.write_column_number(column)?;1187 prelude.write_byte_offset(absolute_byte_offset)?;1188 prelude.end()1189 }11901191 #[inline(always)]1192 fn write_line(&self, line: &[u8]) -> io::Result<()> {1193 let line = if !self.config().trim_ascii {1194 line1195 } else {1196 let lineterm = self.searcher.line_terminator();1197 let full_range = Match::new(0, line.len());1198 let range = trim_ascii_prefix(lineterm, line, full_range);1199 &line[range]1200 };1201 if self.exceeds_max_columns(line) {1202 let range = Match::new(0, line.len());1203 self.write_exceeded_line(1204 line,1205 range,1206 self.sunk.matches(),1207 &mut 0,1208 )?;1209 } else {1210 // self.write_trim(line)?;1211 self.write(line)?;1212 if !self.has_line_terminator(line) {1213 self.write_line_term()?;1214 }1215 }1216 Ok(())1217 }12181219 fn write_colored_line(1220 &self,1221 matches: &[Match],1222 bytes: &[u8],1223 ) -> io::Result<()> {1224 // If we know we aren't going to emit color, then we can go faster.1225 let spec = self.config().colors.matched();1226 if !self.wtr().borrow().supports_color() || spec.is_none() {1227 return self.write_line(bytes);1228 }12291230 let mut line = Match::new(0, bytes.len());1231 self.trim_ascii_prefix(bytes, &mut line);1232 if self.exceeds_max_columns(bytes) {1233 self.write_exceeded_line(bytes, line, matches, &mut 0)1234 } else {1235 self.write_colored_matches(bytes, line, matches, &mut 0)?;1236 self.write_line_term()?;1237 Ok(())1238 }1239 }12401241 /// Write the `line` portion of `bytes`, with appropriate coloring for1242 /// each `match`, starting at `match_index`.1243 ///1244 /// This accounts for trimming any whitespace prefix and will *never* print1245 /// a line terminator. If a match exceeds the range specified by `line`,1246 /// then only the part of the match within `line` (if any) is printed.1247 fn write_colored_matches(1248 &self,1249 bytes: &[u8],1250 mut line: Match,1251 matches: &[Match],1252 match_index: &mut usize,1253 ) -> io::Result<()> {1254 self.trim_line_terminator(bytes, &mut line);1255 if matches.is_empty() {1256 self.write(&bytes[line])?;1257 return Ok(());1258 }colors: add `highlight` type support for matching linesemrebenguebefore adoption99fe884
line 1259why, one step back1259 self.start_line_highlight()?;globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 1260–1285why, one step back1260 while !line.is_empty() {1261 if matches[*match_index].end() <= line.start() {1262 if *match_index + 1 < matches.len() {1263 *match_index += 1;1264 continue;1265 } else {1266 self.end_color_match()?;1267 self.write(&bytes[line])?;1268 break;1269 }1270 }12711272 let m = matches[*match_index];1273 if line.start() < m.start() {1274 let upto = cmp::min(line.end(), m.start());1275 self.end_color_match()?;1276 self.write(&bytes[line.with_end(upto)])?;1277 line = line.with_start(upto);1278 } else {1279 let upto = cmp::min(line.end(), m.end());1280 self.start_color_match()?;1281 self.write(&bytes[line.with_end(upto)])?;1282 line = line.with_start(upto);1283 }1284 }1285 self.end_color_match()?;colors: add `highlight` type support for matching linesemrebenguebefore adoption99fe884
line 1286why, one step back1286 self.end_line_highlight()?;globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 1287–1388why, one step back1287 Ok(())1288 }12891290 fn write_exceeded_line(1291 &self,1292 bytes: &[u8],1293 mut line: Match,1294 matches: &[Match],1295 match_index: &mut usize,1296 ) -> io::Result<()> {1297 if self.config().max_columns_preview {1298 let original = line;1299 let end = bytes[line]1300 .grapheme_indices()1301 .map(|(_, end, _)| end)1302 .take(self.config().max_columns.unwrap_or(0) as usize)1303 .last()1304 .unwrap_or(0)1305 + line.start();1306 line = line.with_end(end);1307 self.write_colored_matches(bytes, line, matches, match_index)?;13081309 if matches.is_empty() {1310 self.write(b" [... omitted end of long line]")?;1311 } else {1312 let remaining = matches1313 .iter()1314 .filter(|m| {1315 m.start() >= line.end() && m.start() < original.end()1316 })1317 .count();1318 let tense = if remaining == 1 { "match" } else { "matches" };1319 write!(1320 self.wtr().borrow_mut(),1321 " [... {} more {}]",1322 remaining,1323 tense,1324 )?;1325 }1326 self.write_line_term()?;1327 return Ok(());1328 }1329 if self.sunk.original_matches().is_empty() {1330 if self.is_context() {1331 self.write(b"[Omitted long context line]")?;1332 } else {1333 self.write(b"[Omitted long matching line]")?;1334 }1335 } else {1336 if self.config().only_matching {1337 if self.is_context() {1338 self.write(b"[Omitted long context line]")?;1339 } else {1340 self.write(b"[Omitted long matching line]")?;1341 }1342 } else {1343 write!(1344 self.wtr().borrow_mut(),1345 "[Omitted long line with {} matches]",1346 self.sunk.original_matches().len(),1347 )?;1348 }1349 }1350 self.write_line_term()?;1351 Ok(())1352 }13531354 /// If this printer has a file path associated with it, then this will1355 /// write that path to the underlying writer followed by a line terminator.1356 /// (If a path terminator is set, then that is used instead of the line1357 /// terminator.)1358 fn write_path_line(&self) -> io::Result<()> {1359 if let Some(path) = self.path() {1360 self.write_path_hyperlink(path)?;1361 if let Some(term) = self.config().path_terminator {1362 self.write(&[term])?;1363 } else {1364 self.write_line_term()?;1365 }1366 }1367 Ok(())1368 }13691370 fn write_search_prelude(&self) -> io::Result<()> {1371 let this_search_written = self.wtr().borrow().count() > 0;1372 if this_search_written {1373 return Ok(());1374 }1375 if let Some(ref sep) = *self.config().separator_search {1376 let ever_written = self.wtr().borrow().total_count() > 0;1377 if ever_written {1378 self.write(sep)?;1379 self.write_line_term()?;1380 }1381 }1382 if self.config().heading {1383 self.write_path_line()?;1384 }1385 Ok(())1386 }13871388 fn write_binary_message(&self, offset: u64) -> io::Result<()> {searcher: move "max matches" from printer to searcherPavel Safronovbefore adoptiona6e0be3
line 1389why, one step back1389 if !self.sink.has_match() {globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 1390–1487why, one step back1390 return Ok(());1391 }13921393 let bin = self.searcher.binary_detection();1394 if let Some(byte) = bin.quit_byte() {1395 if let Some(path) = self.path() {1396 self.write_path_hyperlink(path)?;1397 self.write(b": ")?;1398 }1399 let remainder = format!(1400 "WARNING: stopped searching binary file after match \1401 (found {:?} byte around offset {})\n",1402 [byte].as_bstr(),1403 offset,1404 );1405 self.write(remainder.as_bytes())?;1406 } else if let Some(byte) = bin.convert_byte() {1407 if let Some(path) = self.path() {1408 self.write_path_hyperlink(path)?;1409 self.write(b": ")?;1410 }1411 let remainder = format!(1412 "binary file matches (found {:?} byte around offset {})\n",1413 [byte].as_bstr(),1414 offset,1415 );1416 self.write(remainder.as_bytes())?;1417 }1418 Ok(())1419 }14201421 fn write_context_separator(&self) -> io::Result<()> {1422 if let Some(ref sep) = *self.config().separator_context {1423 self.write(sep)?;1424 self.write_line_term()?;1425 }1426 Ok(())1427 }14281429 fn write_line_term(&self) -> io::Result<()> {1430 self.write(self.searcher.line_terminator().as_bytes())1431 }14321433 fn write_spec(&self, spec: &ColorSpec, buf: &[u8]) -> io::Result<()> {1434 let mut wtr = self.wtr().borrow_mut();1435 wtr.set_color(spec)?;1436 wtr.write_all(buf)?;1437 wtr.reset()?;1438 Ok(())1439 }14401441 fn write_path(&self, path: &PrinterPath) -> io::Result<()> {1442 let mut wtr = self.wtr().borrow_mut();1443 wtr.set_color(self.config().colors.path())?;1444 wtr.write_all(path.as_bytes())?;1445 wtr.reset()1446 }14471448 fn write_path_hyperlink(&self, path: &PrinterPath) -> io::Result<()> {1449 let status = self.start_hyperlink(path, None, None)?;1450 self.write_path(path)?;1451 self.end_hyperlink(status)1452 }14531454 fn start_hyperlink(1455 &self,1456 path: &PrinterPath,1457 line_number: Option<u64>,1458 column: Option<u64>,1459 ) -> io::Result<hyperlink::InterpolatorStatus> {1460 let Some(hyperpath) = path.as_hyperlink() else {1461 return Ok(hyperlink::InterpolatorStatus::inactive());1462 };1463 let values =1464 hyperlink::Values::new(hyperpath).line(line_number).column(column);1465 self.sink.interpolator.begin(&values, &mut *self.wtr().borrow_mut())1466 }14671468 fn end_hyperlink(1469 &self,1470 status: hyperlink::InterpolatorStatus,1471 ) -> io::Result<()> {1472 self.sink.interpolator.finish(status, &mut *self.wtr().borrow_mut())1473 }14741475 fn start_color_match(&self) -> io::Result<()> {1476 if self.in_color_match.get() {1477 return Ok(());1478 }1479 self.wtr().borrow_mut().set_color(self.config().colors.matched())?;1480 self.in_color_match.set(true);1481 Ok(())1482 }14831484 fn end_color_match(&self) -> io::Result<()> {1485 if !self.in_color_match.get() {1486 return Ok(());1487 }colors: add `highlight` type support for matching linesemrebenguebefore adoption99fe884
lines 1488–1494why, one step back1488 if self.highlight_on() {1489 self.wtr()1490 .borrow_mut()1491 .set_color(self.config().colors.highlight())?;1492 } else {1493 self.wtr().borrow_mut().reset()?;1494 }globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
line 1495why, one step back1495 self.in_color_match.set(false);colors: add `highlight` type support for matching linesemrebenguebefore adoption99fe884
lines 1496–1515why, one step back1496 Ok(())1497 }14981499 fn highlight_on(&self) -> bool {1500 !self.config().colors.highlight().is_none() && !self.is_context()1501 }15021503 fn start_line_highlight(&self) -> io::Result<()> {1504 if self.highlight_on() {1505 self.wtr()1506 .borrow_mut()1507 .set_color(self.config().colors.highlight())?;1508 }1509 Ok(())1510 }15111512 fn end_line_highlight(&self) -> io::Result<()> {1513 if self.highlight_on() {1514 self.wtr().borrow_mut().reset()?;1515 }globset: support nested alternatesLuke Sandbergbefore adoption5f5da48
lines 1516–2680why, one step back1516 Ok(())1517 }15181519 fn write(&self, buf: &[u8]) -> io::Result<()> {1520 self.wtr().borrow_mut().write_all(buf)1521 }15221523 fn trim_line_terminator(&self, buf: &[u8], line: &mut Match) {1524 trim_line_terminator(&self.searcher, buf, line);1525 }15261527 fn has_line_terminator(&self, buf: &[u8]) -> bool {1528 self.searcher.line_terminator().is_suffix(buf)1529 }15301531 fn is_context(&self) -> bool {1532 self.sunk.context_kind().is_some()1533 }15341535 /// Return the underlying configuration for this printer.1536 fn config(&self) -> &'a Config {1537 &self.sink.standard.config1538 }15391540 /// Return the underlying writer that we are printing to.1541 fn wtr(&self) -> &'a RefCell<CounterWriter<W>> {1542 &self.sink.standard.wtr1543 }15441545 /// Return the path associated with this printer, if one exists.1546 fn path(&self) -> Option<&'a PrinterPath<'a>> {1547 self.sink.path.as_ref()1548 }15491550 /// Return the appropriate field separator based on whether we are emitting1551 /// matching or contextual lines.1552 fn separator_field(&self) -> &[u8] {1553 if self.is_context() {1554 &self.config().separator_field_context1555 } else {1556 &self.config().separator_field_match1557 }1558 }15591560 /// Returns true if and only if the given line exceeds the maximum number1561 /// of columns set. If no maximum is set, then this always returns false.1562 fn exceeds_max_columns(&self, line: &[u8]) -> bool {1563 self.config().max_columns.map_or(false, |m| line.len() as u64 > m)1564 }15651566 /// Returns true if and only if the searcher may report matches over1567 /// multiple lines.1568 ///1569 /// Note that this doesn't just return whether the searcher is in multi1570 /// line mode, but also checks if the matter can match over multiple lines.1571 /// If it can't, then we don't need multi line handling, even if the1572 /// searcher has multi line mode enabled.1573 fn multi_line(&self) -> bool {1574 self.searcher.multi_line_with_matcher(&self.sink.matcher)1575 }15761577 /// Trim prefix ASCII spaces from the given slice and return the1578 /// corresponding range.1579 ///1580 /// This stops trimming a prefix as soon as it sees non-whitespace or a1581 /// line terminator.1582 fn trim_ascii_prefix(&self, slice: &[u8], range: &mut Match) {1583 if !self.config().trim_ascii {1584 return;1585 }1586 let lineterm = self.searcher.line_terminator();1587 *range = trim_ascii_prefix(lineterm, slice, *range)1588 }1589}15901591/// A writer for the prelude (the beginning part of a matching line).1592///1593/// This encapsulates the state needed to print the prelude.1594struct PreludeWriter<'a, M: Matcher, W> {1595 std: &'a StandardImpl<'a, M, W>,1596 next_separator: PreludeSeparator,1597 field_separator: &'a [u8],1598 interp_status: hyperlink::InterpolatorStatus,1599}16001601/// A type of separator used in the prelude1602enum PreludeSeparator {1603 /// No separator.1604 None,1605 /// The field separator, either for a matching or contextual line.1606 FieldSeparator,1607 /// The path terminator.1608 PathTerminator,1609}16101611impl<'a, M: Matcher, W: WriteColor> PreludeWriter<'a, M, W> {1612 /// Creates a new prelude printer.1613 #[inline(always)]1614 fn new(std: &'a StandardImpl<'a, M, W>) -> PreludeWriter<'a, M, W> {1615 PreludeWriter {1616 std,1617 next_separator: PreludeSeparator::None,1618 field_separator: std.separator_field(),1619 interp_status: hyperlink::InterpolatorStatus::inactive(),1620 }1621 }16221623 /// Starts the prelude with a hyperlink when applicable.1624 ///1625 /// If a heading was written, and the hyperlink format is invariant on1626 /// the line number, then this doesn't hyperlink each line prelude, as it1627 /// wouldn't point to the line anyway. The hyperlink on the heading should1628 /// be sufficient and less confusing.1629 #[inline(always)]1630 fn start(1631 &mut self,1632 line_number: Option<u64>,1633 column: Option<u64>,1634 ) -> io::Result<()> {1635 let Some(path) = self.std.path() else { return Ok(()) };1636 if self.config().hyperlink.format().is_line_dependent()1637 || !self.config().heading1638 {1639 self.interp_status =1640 self.std.start_hyperlink(path, line_number, column)?;1641 }1642 Ok(())1643 }16441645 /// Ends the prelude and writes the remaining output.1646 #[inline(always)]1647 fn end(&mut self) -> io::Result<()> {1648 self.std.end_hyperlink(std::mem::replace(1649 &mut self.interp_status,1650 hyperlink::InterpolatorStatus::inactive(),1651 ))?;1652 self.write_separator()1653 }16541655 /// If this printer has a file path associated with it, then this will1656 /// write that path to the underlying writer followed by the given field1657 /// separator. (If a path terminator is set, then that is used instead of1658 /// the field separator.)1659 #[inline(always)]1660 fn write_path(&mut self) -> io::Result<()> {1661 // The prelude doesn't handle headings, only what comes before a match1662 // on the same line. So if we are emitting paths in headings, we should1663 // not do it here on each line.1664 if self.config().heading {1665 return Ok(());1666 }1667 let Some(path) = self.std.path() else { return Ok(()) };1668 self.write_separator()?;1669 self.std.write_path(path)?;16701671 self.next_separator = if self.config().path_terminator.is_some() {1672 PreludeSeparator::PathTerminator1673 } else {1674 PreludeSeparator::FieldSeparator1675 };1676 Ok(())1677 }16781679 /// Writes the line number field if present.1680 #[inline(always)]1681 fn write_line_number(&mut self, line: Option<u64>) -> io::Result<()> {1682 let Some(line_number) = line else { return Ok(()) };1683 self.write_separator()?;1684 let n = DecimalFormatter::new(line_number);1685 self.std.write_spec(self.config().colors.line(), n.as_bytes())?;1686 self.next_separator = PreludeSeparator::FieldSeparator;1687 Ok(())1688 }16891690 /// Writes the column number field if present and configured to do so.1691 #[inline(always)]1692 fn write_column_number(&mut self, column: Option<u64>) -> io::Result<()> {1693 if !self.config().column {1694 return Ok(());1695 }1696 let Some(column_number) = column else { return Ok(()) };1697 self.write_separator()?;1698 let n = DecimalFormatter::new(column_number);1699 self.std.write_spec(self.config().colors.column(), n.as_bytes())?;1700 self.next_separator = PreludeSeparator::FieldSeparator;1701 Ok(())1702 }17031704 /// Writes the byte offset field if configured to do so.1705 #[inline(always)]1706 fn write_byte_offset(&mut self, offset: u64) -> io::Result<()> {1707 if !self.config().byte_offset {1708 return Ok(());1709 }1710 self.write_separator()?;1711 let n = DecimalFormatter::new(offset);1712 self.std.write_spec(self.config().colors.column(), n.as_bytes())?;1713 self.next_separator = PreludeSeparator::FieldSeparator;1714 Ok(())1715 }17161717 /// Writes the separator defined by the preceding field.1718 ///1719 /// This is called before writing the contents of a field, and at1720 /// the end of the prelude.1721 #[inline(always)]1722 fn write_separator(&mut self) -> io::Result<()> {1723 match self.next_separator {1724 PreludeSeparator::None => {}1725 PreludeSeparator::FieldSeparator => {1726 self.std.write(self.field_separator)?;1727 }1728 PreludeSeparator::PathTerminator => {1729 if let Some(term) = self.config().path_terminator {1730 self.std.write(&[term])?;1731 }1732 }1733 }1734 self.next_separator = PreludeSeparator::None;1735 Ok(())1736 }17371738 #[inline(always)]1739 fn config(&self) -> &Config {1740 self.std.config()1741 }1742}17431744#[cfg(test)]1745mod tests {1746 use grep_matcher::LineTerminator;1747 use grep_regex::{RegexMatcher, RegexMatcherBuilder};1748 use grep_searcher::SearcherBuilder;1749 use termcolor::{Ansi, NoColor};17501751 use super::{ColorSpecs, Standard, StandardBuilder};17521753 const SHERLOCK: &'static str = "\1754For the Doctor Watsons of this world, as opposed to the Sherlock1755Holmeses, success in the province of detective work must always1756be, to a very large extent, the result of luck. Sherlock Holmes1757can extract a clew from a wisp of straw or a flake of cigar ash;1758but Doctor Watson has to have it taken out for him and dusted,1759and exhibited clearly, with a label attached.\1760";17611762 #[allow(dead_code)]1763 const SHERLOCK_CRLF: &'static str = "\1764For the Doctor Watsons of this world, as opposed to the Sherlock\r1765Holmeses, success in the province of detective work must always\r1766be, to a very large extent, the result of luck. Sherlock Holmes\r1767can extract a clew from a wisp of straw or a flake of cigar ash;\r1768but Doctor Watson has to have it taken out for him and dusted,\r1769and exhibited clearly, with a label attached.\1770";17711772 fn printer_contents(printer: &mut Standard<NoColor<Vec<u8>>>) -> String {1773 String::from_utf8(printer.get_mut().get_ref().to_owned()).unwrap()1774 }17751776 fn printer_contents_ansi(printer: &mut Standard<Ansi<Vec<u8>>>) -> String {1777 String::from_utf8(printer.get_mut().get_ref().to_owned()).unwrap()1778 }17791780 #[test]1781 fn reports_match() {1782 let matcher = RegexMatcher::new("Sherlock").unwrap();1783 let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));1784 let mut sink = printer.sink(&matcher);1785 SearcherBuilder::new()1786 .line_number(false)1787 .build()1788 .search_reader(&matcher, SHERLOCK.as_bytes(), &mut sink)1789 .unwrap();1790 assert!(sink.has_match());17911792 let matcher = RegexMatcher::new("zzzzz").unwrap();1793 let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));1794 let mut sink = printer.sink(&matcher);1795 SearcherBuilder::new()1796 .line_number(false)1797 .build()1798 .search_reader(&matcher, SHERLOCK.as_bytes(), &mut sink)1799 .unwrap();1800 assert!(!sink.has_match());1801 }18021803 #[test]1804 fn reports_binary() {1805 use grep_searcher::BinaryDetection;18061807 let matcher = RegexMatcher::new("Sherlock").unwrap();1808 let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));1809 let mut sink = printer.sink(&matcher);1810 SearcherBuilder::new()1811 .line_number(false)1812 .build()1813 .search_reader(&matcher, SHERLOCK.as_bytes(), &mut sink)1814 .unwrap();1815 assert!(sink.binary_byte_offset().is_none());18161817 let matcher = RegexMatcher::new(".+").unwrap();1818 let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));1819 let mut sink = printer.sink(&matcher);1820 SearcherBuilder::new()1821 .line_number(false)1822 .binary_detection(BinaryDetection::quit(b'\x00'))1823 .build()1824 .search_reader(&matcher, &b"abc\x00"[..], &mut sink)1825 .unwrap();1826 assert_eq!(sink.binary_byte_offset(), Some(3));1827 }18281829 #[test]1830 fn reports_stats() {1831 use std::time::Duration;18321833 let matcher = RegexMatcher::new("Sherlock|opposed").unwrap();1834 let mut printer =1835 StandardBuilder::new().stats(true).build(NoColor::new(vec![]));1836 let stats = {1837 let mut sink = printer.sink(&matcher);1838 SearcherBuilder::new()1839 .line_number(false)1840 .build()1841 .search_reader(&matcher, SHERLOCK.as_bytes(), &mut sink)1842 .unwrap();1843 sink.stats().unwrap().clone()1844 };1845 let buf = printer_contents(&mut printer);18461847 assert!(stats.elapsed() > Duration::default());1848 assert_eq!(stats.searches(), 1);1849 assert_eq!(stats.searches_with_match(), 1);1850 assert_eq!(stats.bytes_searched(), SHERLOCK.len() as u64);1851 assert_eq!(stats.bytes_printed(), buf.len() as u64);1852 assert_eq!(stats.matched_lines(), 2);1853 assert_eq!(stats.matches(), 3);1854 }18551856 #[test]1857 fn reports_stats_multiple() {1858 use std::time::Duration;18591860 let matcher = RegexMatcher::new("Sherlock|opposed").unwrap();1861 let mut printer =1862 StandardBuilder::new().stats(true).build(NoColor::new(vec![]));1863 let stats = {1864 let mut sink = printer.sink(&matcher);1865 SearcherBuilder::new()1866 .line_number(false)1867 .build()1868 .search_reader(&matcher, SHERLOCK.as_bytes(), &mut sink)1869 .unwrap();1870 SearcherBuilder::new()1871 .line_number(false)1872 .build()1873 .search_reader(&matcher, &b"zzzzzzzzzz"[..], &mut sink)1874 .unwrap();1875 SearcherBuilder::new()1876 .line_number(false)1877 .build()1878 .search_reader(&matcher, SHERLOCK.as_bytes(), &mut sink)1879 .unwrap();1880 sink.stats().unwrap().clone()1881 };1882 let buf = printer_contents(&mut printer);18831884 assert!(stats.elapsed() > Duration::default());1885 assert_eq!(stats.searches(), 3);1886 assert_eq!(stats.searches_with_match(), 2);1887 assert_eq!(stats.bytes_searched(), 10 + 2 * SHERLOCK.len() as u64);1888 assert_eq!(stats.bytes_printed(), buf.len() as u64);1889 assert_eq!(stats.matched_lines(), 4);1890 assert_eq!(stats.matches(), 6);1891 }18921893 #[test]1894 fn context_break() {1895 let matcher = RegexMatcher::new("Watson").unwrap();1896 let mut printer = StandardBuilder::new()1897 .separator_context(Some(b"--abc--".to_vec()))1898 .build(NoColor::new(vec![]));1899 SearcherBuilder::new()1900 .line_number(false)1901 .before_context(1)1902 .after_context(1)1903 .build()1904 .search_reader(1905 &matcher,1906 SHERLOCK.as_bytes(),1907 printer.sink(&matcher),1908 )1909 .unwrap();19101911 let got = printer_contents(&mut printer);1912 let expected = "\1913For the Doctor Watsons of this world, as opposed to the Sherlock1914Holmeses, success in the province of detective work must always1915--abc--1916can extract a clew from a wisp of straw or a flake of cigar ash;1917but Doctor Watson has to have it taken out for him and dusted,1918and exhibited clearly, with a label attached.1919";1920 assert_eq_printed!(expected, got);1921 }19221923 #[test]1924 fn context_break_multiple_no_heading() {1925 let matcher = RegexMatcher::new("Watson").unwrap();1926 let mut printer = StandardBuilder::new()1927 .separator_search(Some(b"--xyz--".to_vec()))1928 .separator_context(Some(b"--abc--".to_vec()))1929 .build(NoColor::new(vec![]));19301931 SearcherBuilder::new()1932 .line_number(false)1933 .before_context(1)1934 .after_context(1)1935 .build()1936 .search_reader(1937 &matcher,1938 SHERLOCK.as_bytes(),1939 printer.sink(&matcher),1940 )1941 .unwrap();1942 SearcherBuilder::new()1943 .line_number(false)1944 .before_context(1)1945 .after_context(1)1946 .build()1947 .search_reader(1948 &matcher,1949 SHERLOCK.as_bytes(),1950 printer.sink(&matcher),1951 )1952 .unwrap();19531954 let got = printer_contents(&mut printer);1955 let expected = "\1956For the Doctor Watsons of this world, as opposed to the Sherlock1957Holmeses, success in the province of detective work must always1958--abc--1959can extract a clew from a wisp of straw or a flake of cigar ash;1960but Doctor Watson has to have it taken out for him and dusted,1961and exhibited clearly, with a label attached.1962--xyz--1963For the Doctor Watsons of this world, as opposed to the Sherlock1964Holmeses, success in the province of detective work must always1965--abc--1966can extract a clew from a wisp of straw or a flake of cigar ash;1967but Doctor Watson has to have it taken out for him and dusted,1968and exhibited clearly, with a label attached.1969";1970 assert_eq_printed!(expected, got);1971 }19721973 #[test]1974 fn context_break_multiple_heading() {1975 let matcher = RegexMatcher::new("Watson").unwrap();1976 let mut printer = StandardBuilder::new()1977 .heading(true)1978 .separator_search(Some(b"--xyz--".to_vec()))1979 .separator_context(Some(b"--abc--".to_vec()))1980 .build(NoColor::new(vec![]));19811982 SearcherBuilder::new()1983 .line_number(false)1984 .before_context(1)1985 .after_context(1)1986 .build()1987 .search_reader(1988 &matcher,1989 SHERLOCK.as_bytes(),1990 printer.sink(&matcher),1991 )1992 .unwrap();1993 SearcherBuilder::new()1994 .line_number(false)1995 .before_context(1)1996 .after_context(1)1997 .build()1998 .search_reader(1999 &matcher,2000 SHERLOCK.as_bytes(),The first 2,000 of 3,987 lines.