diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2537261..fcb20bd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,10 +36,10 @@ cargo build --release After the version bump is merged and CI passes, open **Actions > Release > Run workflow**, select **main**, and enter the tag matching the workspace -version in `Cargo.toml`, for example `v1.2.8`. The equivalent CLI command is: +version in `Cargo.toml`, for example `v1.2.9`. The equivalent CLI command is: ```bash -gh workflow run release.yml --repo microsoft/tgrep --ref main -f tag=v1.2.8 +gh workflow run release.yml --repo microsoft/tgrep --ref main -f tag=v1.2.9 ``` The workflow validates the version, creates a missing tag at the exact commit diff --git a/Cargo.lock b/Cargo.lock index eb7eddc..488acfa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1360,7 +1360,7 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "tgrep-cli" -version = "1.2.8" +version = "1.2.9" dependencies = [ "anyhow", "assert_cmd", @@ -1389,7 +1389,7 @@ dependencies = [ [[package]] name = "tgrep-core" -version = "1.2.8" +version = "1.2.9" dependencies = [ "anyhow", "blake3", diff --git a/Cargo.toml b/Cargo.toml index 23d1f46..f516b41 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ exclude = ["vendor/ignore"] resolver = "2" [workspace.package] -version = "1.2.8" +version = "1.2.9" edition = "2024" rust-version = "1.88" license = "MIT" diff --git a/README.md b/README.md index 50b910c..809faeb 100644 --- a/README.md +++ b/README.md @@ -401,6 +401,7 @@ These tables describe search flags. Use `tgrep index --help` and | `-w, --word-regexp` | Require non-word characters or text boundaries on both sides of the match; overrides earlier `-x` | | `-v, --invert-match` | Show lines that do NOT match | | `-o, --only-matching` | Print only the matched parts | +| `--match-context ` | Like `-o`, with up to N Unicode characters on each side of each match on its line. Nearby excerpts may overlap. Columns and byte offsets still identify the match. JSON keeps its full-line events. | | `-e, --regexp ` | Additional pattern (repeatable for OR) | | `-f, --file ` | Read patterns verbatim, one per line; blank lines are empty patterns (repeatable) | | `-U, --multiline` | Enable multiline matching (`.` still excludes `\n`) | diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index b6b3953..535f22b 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -770,7 +770,7 @@ dependencies = [ [[package]] name = "tgrep-core" -version = "1.2.8" +version = "1.2.9" dependencies = [ "anyhow", "blake3", diff --git a/tgrep-cli/src/main.rs b/tgrep-cli/src/main.rs index 263fb4d..394453b 100644 --- a/tgrep-cli/src/main.rs +++ b/tgrep-cli/src/main.rs @@ -135,6 +135,10 @@ struct Cli { #[arg(short = 'o', long = "only-matching", global = true)] only_matching: bool, + /// Print each match with up to N characters on either side on the same line. Implies -o. + #[arg(long, value_name = "N", global = true)] + match_context: Option, + /// Limit matches per file. #[arg(short = 'm', long = "max-count", global = true)] max_count: Option, @@ -1163,7 +1167,8 @@ impl Cli { glob_case_insensitive: self.glob_case_insensitive, type_ops: self.type_ops.clone(), invert_match: self.invert_match, - only_matching: self.only_matching, + only_matching: self.only_matching || self.match_context.is_some(), + match_context: self.match_context.unwrap_or(0), after_context: self.after_context, before_context: self.before_context, context: self.context, diff --git a/tgrep-cli/src/matching.rs b/tgrep-cli/src/matching.rs index 71c9c94..bd89b92 100644 --- a/tgrep-cli/src/matching.rs +++ b/tgrep-cli/src/matching.rs @@ -965,6 +965,7 @@ pub struct MatchOptions { pub invert_match: bool, pub multiline: bool, pub only_matching: bool, + pub match_context: usize, pub before_context: usize, pub after_context: usize, pub max_count: Option, @@ -997,6 +998,27 @@ pub struct MatchOptions { pub report_replacements: bool, } +/// Return a same-line excerpt and the byte range to highlight inside it. +fn match_excerpt(line: &str, start: usize, end: usize, radius: usize) -> (&str, (usize, usize)) { + let mut left = start; + let mut right = end; + // A replacement can introduce a line break into an otherwise single-line buffer. + for ch in line[..start].chars().rev().take(radius) { + if ch == '\n' { + break; + } + left -= ch.len_utf8(); + } + let right_context = &line[end..]; + for (i, ch) in right_context.char_indices().take(radius) { + if ch == '\n' || (ch == '\r' && right_context[i + 1..].starts_with('\n')) { + break; + } + right += ch.len_utf8(); + } + (&line[left..right], (start - left, end - left)) +} + /// One unit of output produced by searching a single file. pub enum Emit<'a> { Match { @@ -1202,51 +1224,52 @@ impl<'a> FileMatches<'a> { } if opts.only_matching && !hit.spans.is_empty() { - // With `-r`, `-o` prints the replacement of each match rather - // than the matched text itself. - if let Some(rep) = &opts.replace { - // ripgrep rewrites the line and reports offsets into the - // result, so each match moves by the length delta of the - // ones before it. Columns stay in source terms here and are - // corrected by `column_shifts` after the caller has mapped - // them back through any lossy-decoding repairs. - let mut shift: isize = 0; - for (start, end, text) in matcher.expansions(line, rep).map_err(E::from)? { - let len = text.len(); - on_emit(Emit::Match { - line_number: hit.idx + 1, - content: Cow::Owned(text), - columns: vec![start + 1], - spans: vec![(0, len)], - absolute_offset: offset + start, - line_offset: offset, - column_shifts: vec![shift], - offset_shift: shift, - terminator_len: 0, - block: None, - hidden: false, - replacements: None, - })?; - shift += len as isize - (end - start) as isize; - } - return Ok(()); - } - for &(s, e) in &hit.spans { - let text = &line[s..e]; + let mut emit = |content, span, start, shift| { on_emit(Emit::Match { line_number: hit.idx + 1, - content: Cow::Borrowed(text), - columns: vec![s + 1], - spans: vec![(0, text.len())], - absolute_offset: offset + s, + content, + columns: vec![start + 1], + spans: vec![span], + absolute_offset: offset + start, line_offset: offset, - column_shifts: Vec::new(), - offset_shift: 0, + column_shifts: if shift == 0 { Vec::new() } else { vec![shift] }, + offset_shift: shift, terminator_len: 0, block: None, hidden: false, replacements: None, - })?; + }) + }; + match &opts.replace { + None => { + for &(start, end) in &hit.spans { + let (text, span) = match_excerpt(line, start, end, opts.match_context); + emit(Cow::Borrowed(text), span, start, 0)?; + } + } + Some(rep) if opts.match_context == 0 => { + // Plain -o only needs the expansions, even on very long lines. + let mut shift = 0; + for (start, end, text) in matcher.expansions(line, rep)? { + let len = text.len(); + emit(Cow::Owned(text), (0, len), start, shift)?; + shift += len as isize - (end - start) as isize; + } + } + Some(rep) => { + // Nearby replacements can also fall inside the excerpt. + let (rewritten, spans) = matcher.replace_all(line, rep)?; + for (&(source, _), (start, end)) in hit.spans.iter().zip(spans) { + let (text, span) = + match_excerpt(&rewritten, start, end, opts.match_context); + emit( + Cow::Owned(text.to_owned()), + span, + source, + start as isize - source as isize, + )?; + } + } } return Ok(()); } @@ -1426,6 +1449,12 @@ fn emit_block<'a, E>( let (a, b) = (rep.dst.0.max(ls), rep.dst.1.min(te)); (a < b).then_some((a, b)) }; + // With match context, an empty replacement still anchors an excerpt on the + // one rewritten line that contains its position. + let anchor = |rep: &Placed, ls: usize, te: usize| { + let at = rep.dst.0; + (opts.match_context > 0 && rep.dst.1 == at && (ls..=te).contains(&at)).then_some((at, at)) + }; let mut rows = 0usize; if opts.only_matching { @@ -1441,14 +1470,16 @@ fn emit_block<'a, E>( .collect(); for (k, &(ls, te, _)) in lines.iter().enumerate() { for (rep, &shift) in block.reps.iter().zip(&shifts) { - let Some((a, b)) = piece(rep, ls, te) else { + let Some((a, b)) = piece(rep, ls, te).or_else(|| anchor(rep, ls, te)) else { continue; }; + let (text, span) = + match_excerpt(&block.text[ls..te], a - ls, b - ls, opts.match_context); on_emit(Emit::Match { line_number: block.first + 1 + k, - content: Cow::Owned(block.text[a..b].to_owned()), + content: Cow::Owned(text.to_owned()), columns: vec![rep.src.0 - block.start + 1], - spans: vec![(0, b - a)], + spans: vec![span], absolute_offset: rep.src.0, line_offset: block.start, column_shifts: vec![shift], diff --git a/tgrep-cli/src/search.rs b/tgrep-cli/src/search.rs index f9697ca..48dba08 100644 --- a/tgrep-cli/src/search.rs +++ b/tgrep-cli/src/search.rs @@ -56,6 +56,7 @@ pub struct SearchOptions { pub type_ops: Vec, pub invert_match: bool, pub only_matching: bool, + pub match_context: usize, pub after_context: Option, pub before_context: Option, pub context: Option, @@ -446,6 +447,7 @@ impl SearchOptions { invert_match: self.invert_match, multiline: self.multiline, only_matching: self.effective_only_matching(), + match_context: self.match_context, before_context: self.before_ctx(), after_context: self.after_ctx(), // `-q` and `--files-without-match` only need to know whether the @@ -1013,7 +1015,7 @@ pub fn run( })?; require_server_coverage(&result)?; require_ordered_filters(&result, &request)?; - require_replace_support(&result, &request)?; + require_render_support(&result, &request)?; Ok((view.root, scope, request, result)) })(); match response { @@ -1463,8 +1465,10 @@ fn server_search_request( if opts.needs_ordered_filters()? { request["params"]["ordered_filters"] = serde_json::json!(true); } - // A server that predates a `--replace` rendering cannot honour it, and - // its reply is then refused. Ask only when the output depends on it. + // Ask for rendering extensions only when the output depends on them. + if opts.match_context > 0 && opts.prints_text_lines() { + request["params"]["match_context"] = serde_json::json!(opts.match_context); + } if opts.needs_replace_blocks(ci) { request["params"]["multiline_replace"] = serde_json::json!(true); } @@ -1479,13 +1483,12 @@ fn server_search_request( Ok(request) } -/// Fail when the result comes from a server that predates the `--replace` -/// rendering `request` asked for. Such a server ignores the request and -/// rewrites `-U` matches line by line, or leaves `--json` submatches without -/// their `replacement`. Reading the request rather than the options keeps -/// this check in step with what `server_search_request` decided to ask for. -fn require_replace_support(result: &serde_json::Value, request: &serde_json::Value) -> Result<()> { +/// Older servers ignore unknown rendering options. Check the reply before printing any rows. +fn require_render_support(result: &serde_json::Value, request: &serde_json::Value) -> Result<()> { let params = &request["params"]; + if params.get("match_context").is_some() && !flag_set(result, "match_context") { + anyhow::bail!("server does not support character context"); + } if flag_set(params, "multiline_replace") && !flag_set(result, "multiline_replace") { anyhow::bail!("server does not support multiline replacement blocks"); } @@ -1579,7 +1582,7 @@ fn render_server_result( // rows, so an old/partial server can never silently answer --hidden. require_server_coverage(result)?; require_ordered_filters(result, request)?; - require_replace_support(result, request)?; + require_render_support(result, request)?; let empty_vec = Vec::new(); let matches = result @@ -4007,7 +4010,7 @@ mod tests { let params = &request["params"]; assert!(params.get("multiline_replace").is_none(), "{params}"); assert!(params.get("report_replacements").is_none(), "{params}"); - assert!(require_replace_support(&serde_json::json!({}), &request).is_ok()); + assert!(require_render_support(&serde_json::json!({}), &request).is_ok()); } for opts in [ @@ -4099,20 +4102,19 @@ mod tests { serde_json::json!({}), serde_json::json!({"multiline_replace": false, "report_replacements": false}), ] { - assert!(require_replace_support(&result, &blocks).is_err()); - assert!(require_replace_support(&result, &json).is_err()); + assert!(require_render_support(&result, &blocks).is_err()); + assert!(require_render_support(&result, &json).is_err()); } assert!( - require_replace_support(&serde_json::json!({"multiline_replace": true}), &json) - .is_err() + require_render_support(&serde_json::json!({"multiline_replace": true}), &json).is_err() ); assert!( - require_replace_support(&serde_json::json!({"report_replacements": true}), &blocks) + require_render_support(&serde_json::json!({"report_replacements": true}), &blocks) .is_err() ); let acked = serde_json::json!({"multiline_replace": true, "report_replacements": true}); - assert!(require_replace_support(&acked, &blocks).is_ok()); - assert!(require_replace_support(&acked, &json).is_ok()); + assert!(require_render_support(&acked, &blocks).is_ok()); + assert!(require_render_support(&acked, &json).is_ok()); } #[test] diff --git a/tgrep-cli/src/serve.rs b/tgrep-cli/src/serve.rs index ec24122..725544c 100644 --- a/tgrep-cli/src/serve.rs +++ b/tgrep-cli/src/serve.rs @@ -837,6 +837,7 @@ struct SearchOpts { files_only: bool, invert_match: bool, only_matching: bool, + match_context: usize, max_count: Option, before_context: usize, after_context: usize, @@ -889,6 +890,7 @@ impl SearchOpts { invert_match: self.invert_match, multiline: self.multiline, only_matching: self.only_matching, + match_context: self.match_context, before_context: self.before_context, after_context: self.after_context, max_count: if self.files_only && !self.stats { @@ -902,7 +904,8 @@ impl SearchOpts { vimgrep: self.vimgrep, // Counts and `-l` need only whether a line matched, not every // span on it. - all_spans: self.stats + all_spans: self.only_matching + || self.stats || self.count_matches || (self.detail && !self.count && !self.files_only), replace_blocks: self.multiline_replace, @@ -1976,10 +1979,21 @@ fn parse_search_params(params: &serde_json::Value) -> std::result::Result std::result::Result Result<()> { "extra_patterns" => value .as_array() .is_some_and(|array| array.iter().all(Value::is_string)), + "match_context" => value.is_u64(), "max_count" | "after_context" | "before_context" | "max_filesize" | "regex_size_limit" | "dfa_size_limit" => value.is_null() || value.is_u64(), "case_insensitive" @@ -1243,7 +1244,7 @@ impl State { let metadata = json!({ "root":entry.view.root(), "view":entry.id, "generation":entry.view.generation().key(), "ready":true, "hidden_complete":true, "ordered_filters":true, - "multiline_replace":true, "report_replacements":true, "backend":"shared-v1", + "multiline_replace":true, "report_replacements":true, "match_context":true, "backend":"shared-v1", "protocol":PROTOCOL, "instance":self.registration.instance, "repository":self.registration.repository }); diff --git a/tgrep-cli/tests/ripgrep_compat.rs b/tgrep-cli/tests/ripgrep_compat.rs index 2827781..2b04dfa 100644 --- a/tgrep-cli/tests/ripgrep_compat.rs +++ b/tgrep-cli/tests/ripgrep_compat.rs @@ -3026,6 +3026,13 @@ fn ordered_filters_and_replacements_reject_servers_without_support() { // client rejects a reply that does not acknowledge them (`None` when an // older server's reply is just as good), and the output (`None` for JSON). for (flags, pattern, fields, reason, expected) in [ + ( + vec!["--no-filename", "--match-context=1"], + "ell", + &["match_context"][..], + Some("character context"), + Some("hello\n"), + ), ( vec!["-l", "-T", "rust", "-t", "rust"], "needle", @@ -3133,6 +3140,7 @@ fn ordered_filters_and_replacements_reject_servers_without_support() { let request: serde_json::Value = serde_json::from_str(&line).unwrap(); // New fields are sent only when the result depends on them. for name in [ + "match_context", "type_ops", "ordered_filters", "multiline_replace", @@ -4674,6 +4682,106 @@ fn invert_match_long_flag() { // ─── Only matching (-o / --only-matching) ─────────────────────────── +#[test] +fn match_context_keeps_match_positions_across_backends() { + let dir = TempDir::new().unwrap(); + let root = dir.path().join("testdata"); + fs::create_dir(&root).unwrap(); + fs::write(root.join("hits"), "ä🌲hit-hit猫z\r\nhit\n").unwrap(); + fs::write(root.join("unrelated"), "nothing here\n").unwrap(); + with_stats_backends(&root, &dir.path().join("idx"), |backend, marker| { + let run = |flags: &[&str]| { + let output = tgrep() + .args(backend) + .args(["--stats", "--color", "never", "-I"]) + .args(flags) + .args(["--", "hit|needle"]) + .arg(&root) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stderr.contains(marker), "{stderr}"); + (String::from_utf8(output.stdout).unwrap(), stderr) + }; + let (plain, base_stats) = run(&["-o", "--column", "-b"]); + let (zero, _) = run(&["--match-context=0", "--column", "-b"]); + assert_eq!(zero, plain); + let (excerpt, stats) = run(&["--match-context=1", "--column", "-b"]); + assert_eq!(excerpt, "1:7:6:🌲hit-\n1:11:10:-hit猫\n2:1:19:hit\n"); + // Each excerpt contains the other hit. Both positions must still be reported. + let (overlap, _) = run(&["--match-context=4", "--column"]); + assert_eq!(overlap, "1:7:ä🌲hit-hit\n1:11:hit-hit猫z\n2:1:hit\n"); + if backend[0] != "--no-index" { + let plan = |s: &str| { + s.lines() + .find(|l| l.starts_with("Query plan:")) + .unwrap() + .to_owned() + }; + assert_eq!(plan(&base_stats), plan(&stats)); + assert!(plan(&stats).contains("candidates: 1/2"), "{stats}"); + } + let (json, _) = run(&["--match-context=1", "--json"]); + let hit = json + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .find(|v| v["type"] == "match") + .unwrap(); + assert_eq!(hit["data"]["lines"]["text"], "ä🌲hit-hit猫z\r\n"); + assert_eq!(hit["data"]["submatches"].as_array().unwrap().len(), 2); + }); +} + +#[test] +fn match_context_highlights_and_replacements() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("lines"); + fs::write(&path, "αhit-hitβ\nxab\ncdz\n").unwrap(); + for (flags, expected) in [ + ( + vec!["--color=always", "--match-context=1", "hit"], + "α\x1b[1;31mhit\x1b[0m-\n-\x1b[1;31mhit\x1b[0mβ\n", + ), + ( + vec!["--match-context=3", "--column", "-b", "-r", "X", "hit"], + "1:3:2:αX-Xβ\n1:5:4:αX-Xβ\n", + ), + (vec!["--match-context=1", "-U", r"ab\ncd"], "xab\ncdz\n"), + ( + vec!["--match-context=1", "-U", "-r", "R", r"ab\ncd"], + "xRz\n", + ), + // An empty replacement still has context; plain -o keeps printing nothing. + (vec!["--match-context=1", "-U", "-r", "", r"ab\ncd"], "xz\n"), + (vec!["-o", "-U", "-r", "", r"ab\ncd"], ""), + ] { + tgrep() + .args(["--no-index", "-I"]) + .args(flags) + .arg(&path) + .assert() + .success() + .stdout(expected); + } +} + +#[test] +fn match_context_does_not_include_cr_from_replacement_crlf() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("lines"); + fs::write(&path, "hit-hit\n").unwrap(); + + tgrep() + .args(["--no-index", "--match-context=3", "-r"]) + .arg("X\r\nY") + .arg("hit") + .arg(&path) + .assert() + .success() + .stdout("X\r\nY-X\nY-X\r\nY\n"); +} + #[test] fn only_matching_short_flag() { let dir = setup_fixture(); diff --git a/tgrep-cli/tests/shared_daemon.rs b/tgrep-cli/tests/shared_daemon.rs index 20bbcd7..f46779c 100644 --- a/tgrep-cli/tests/shared_daemon.rs +++ b/tgrep-cli/tests/shared_daemon.rs @@ -914,6 +914,11 @@ fn assert_compat_queries(root: &Path, marker: &str) -> u64 { let prefix = root.to_string_lossy().replace('\\', "/"); let mut queries = 0; for (flags, pattern, expected) in [ + ( + vec!["--no-filename", "--match-context=1"], + "ell", + Some("hello\n".to_string()), + ), ( vec!["-l", "-T", "rust", "-t", "rust"], "needle",