highlight_words([]) creates zero-length matches

#4229 · open · 2 comments

View on GitHub ↗

januththedev

### Description `Text.highlight_words()` treats an empty word iterable as an empty regular expression. Python's regex engine then finds zero-width matches at every character boundary, so the method reports false matches and appends zero-length spans. ### Steps to reproduce ```python from rich.text import Text text = Text("abc") count = text.highlight_words([], "red") assert count == 0 assert text._spans == [] ``` ### Expected behavior An empty word list should be a no-op and return `0`. ### Actual behavior The current implementation builds `re_words = ""` and `re.finditer("", "abc")` yields four zero-width matches. `highlight_words()` returns `4` and appends four zero-length spans. The implementation is in `rich/text.py`, and existing tests only cover non-empty word iterables. I searched existing issues and pull requests for `highlight_words([])` and did not find a matching report. Would maintainers accept a small guard for an empty word iterable plus a regression test? The repository's contribution guide requires tests and a changelog entry for a bug fix.

Comments

januththedev

@willmcgugan, I prepared a minimal TDD fix for this issue on `januththedev:fix/highlight-empty-words`: - commit: `27cca1d` - branch: https://github.com/januththedev/rich/tree/fix/highlight-empty-words - change: return `0` before regex matching when the escaped word pattern is empty - regression test: empty iterable returns `0` and leaves spans unchanged - verification: `114 passed` in `tests/test_text.py`; `git diff --check` passed Black and mypy are not installed locally, so CI will need to run those checks. Per Rich's AI policy, I have not opened a pull request. Could you confirm here that this approach is approved so I can submit the PR?

januththedev

Following up once: the tested branch remains ready at `januththedev:fix/highlight-empty-words`. If AI-assisted contributions are not acceptable under the project policy, please close or flag the issue so I can stop.