Skip to content

Add character-level context around matches without losing indexed search performance #227

Done

Description

@kubasur

Coding agents need to see context around matches. On a long line of minified JavaScript, -o might return only a function name, while printing the whole line can consume thousands of tokens. A few characters on either side are often enough to see how the function is called.

Ripgrep’s -A, -B, and -C provide context in lines. A common workaround for character-level context is to wrap the expression in .{0,30} and use -o. On the Firefox source tree, this had little effect on ripgrep or unindexed tgrep. For the indexed tgrep query below, it increased search time from 0.44 seconds to 105 seconds. ripgrep discussion · Regex workaround

I ran these commands with tgrep 1.2.8 from the root of the Firefox checkout. Firefox revision

tgrep index .
pattern='PresShell::Destroy|nsGlobalWindowInner::FreeInnerObjects'
tgrep --stats -o "$pattern" . > /dev/null
tgrep --stats -o ".{0,30}(?:$pattern).{0,30}" . > /dev/null

Both queries found 10 matches. The original expression narrowed 470,722 indexed files to 51 candidates. The wrapped expression produced a MatchAll plan and searched 469,879 files.

Firefox search Original expression With regex context
ripgrep 15.2.0 10.6 s 10.3 s
tgrep 1.2.8, unindexed 72.9 s 73.5 s
tgrep 1.2.8, indexed 0.44 s 105 s

Times are medians of three runs on Apple Silicon, excluding index construction.

I propose --match-context N as a character-level counterpart to -C. Running tgrep --match-context 30 "$pattern" . would search for the original expression and print each match with up to 30 characters on either side, stopping at the line boundaries. This would let callers choose how much text to display while preserving the indexed search plan.

My proposed fix is in PR #228.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions