Skip to content

Conversation

@snakefoot
Copy link
Contributor

@snakefoot snakefoot commented Aug 8, 2025

With RegEx one could do the following:

regex="abc|def|ghi"

Now one can do this (Remember to remove any leading/trailing white-spaces):

words="abc,def,ghi"

@coderabbitai
Copy link

coderabbitai bot commented Aug 8, 2025

Warning

Rate limit exceeded

@snakefoot has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 13 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 7077467 and 51a6a97.

📒 Files selected for processing (2)
  • src/NLog/Targets/ConsoleWordHighlightingRule.cs (3 hunks)
  • tests/NLog.UnitTests/Targets/ColoredConsoleTargetTests.cs (1 hunks)

Walkthrough

Multi-word highlighting support was added to the ConsoleWordHighlightingRule class, enabling the highlighting of several words in console output with merged overlapping matches. Associated logic for matching, merging, and finding words was refactored. A new parameterized unit test verifies the correct ANSI color output for multiple word matches, including overlapping and multiline cases.

Changes

Cohort / File(s) Change Summary
Multi-word Highlighting Logic
src/NLog/Targets/ConsoleWordHighlightingRule.cs
Added a nullable Words property to support multiple word matches; implemented methods to find, merge, and highlight overlapping matches from multiple words; refactored matching logic to accept arbitrary needles instead of a single text field.
Unit Test for Multi-word Highlighting
tests/NLog.UnitTests/Targets/ColoredConsoleTargetTests.cs
Added a parameterized test method verifying ANSI escape sequences correctly highlight multiple specified words with overlapping occurrences and multiline inputs.

Sequence Diagram(s)

sequenceDiagram
    participant Logger
    participant ConsoleWordHighlightingRule
    participant ConsoleOutput

    Logger->>ConsoleWordHighlightingRule: Log message with text
    alt Words property is set and not empty
        ConsoleWordHighlightingRule->>ConsoleWordHighlightingRule: Find matches for each word in Words
        ConsoleWordHighlightingRule->>ConsoleWordHighlightingRule: Merge overlapping matches
    else
        ConsoleWordHighlightingRule->>ConsoleWordHighlightingRule: Find matches for single Text
    end
    ConsoleWordHighlightingRule->>ConsoleOutput: Write highlighted message with ANSI codes
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

In the console’s glow, words now shine bright,
“Big” and “bigger”—all highlighted right!
Overlapping colors, a rabbit’s delight,
Tests hop along, ensuring output’s in sight.
With every merge, and every hue,
Console rainbows—thanks to you!
🐇✨


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (5)
src/NLog/Targets/ConsoleWordHighlightingRule.cs (4)

83-87: Add public-API metadata for Words.

Words lacks the <docgen> attribute (and default value remarks) that other public properties expose. Adding it keeps XML docs & config-schema generation consistent.


122-133: Guard short-circuit logic with IsNullOrEmpty.

Relying on ReferenceEquals(_text, string.Empty) assumes the empty-string instance is always used.
Safer & clearer:

- if (ReferenceEquals(_text, string.Empty))
+ if (string.IsNullOrEmpty(_text))

Avoids edge-cases if Text is set to an empty span obtained via substring.


134-157: Possible quadratic growth when many words overlap.

YieldWordMatchesForHighlighting merges matches word-by-word, each time copying/merging the accumulated list.
With n words and m matches per word this is O(n × m²) worst-case.

If large word lists are expected, consider:

  • Collect matches for all words → single List
  • Sort by start index
  • Single linear pass to merge overlaps

Reduces complexity to O(totalMatches log totalMatches).


226-242: Minor: avoid extra list copy when source already writable.

PrepareAllMatchesList copies even when allMatchesList.IsReadOnly == false but capacity insufficient.
List<T> automatically grows; returning the existing instance avoids allocation.

tests/NLog.UnitTests/Targets/ColoredConsoleTargetTests.cs (1)

228-233: Mixed escape-sequence casing reduces consistency.

Earlier tests use \x1B; new expectations switch to lowercase \x1b. Functionally identical but stylistically uneven—prefer consistent casing across test suite.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c44b4d1 and 5d1cf47.

📒 Files selected for processing (2)
  • src/NLog/Targets/ConsoleWordHighlightingRule.cs (3 hunks)
  • tests/NLog.UnitTests/Targets/ColoredConsoleTargetTests.cs (1 hunks)
🔇 Additional comments (2)
src/NLog/Targets/ConsoleWordHighlightingRule.cs (1)

210-216: NeedleMatchOverlaps off-by-one definition check.

Current test uses > so ranges that merely touch (e.g., [0,3] and [3,2]) are kept separate.
If highlighting should avoid duplicated resets between adjacent matches, change to >=.

Request confirmation that the current behaviour is intentional.

tests/NLog.UnitTests/Targets/ColoredConsoleTargetTests.cs (1)

229-230: Extra reset \x1b[0m may mask regressions.

Expected string for CR/LF case contains two consecutive resets (…big\x1b[0m\x1b[0m\r\n…).
If implementation later optimises to emit a single reset the test will fail spuriously. Consider asserting with a regex or trimming duplicate resets instead.

Comment on lines +272 to 284
private int FindNextWordForHighlighting(string needle, string haystack, int? prevIndex)
{
int index = prevIndex.HasValue ? prevIndex.Value + _text.Length : 0;
int index = prevIndex.HasValue ? prevIndex.Value + needle.Length : 0;
while (index >= 0)
{
index = IgnoreCase ? haystack.IndexOf(_text, index, System.StringComparison.CurrentCultureIgnoreCase) : haystack.IndexOf(_text, index);
if (index < 0 || (!WholeWords || StringHelpers.IsWholeWord(haystack, _text, index)))
index = IgnoreCase ? haystack.IndexOf(needle, index, System.StringComparison.CurrentCultureIgnoreCase) : haystack.IndexOf(needle, index);
if (index < 0 || (!WholeWords || StringHelpers.IsWholeWord(haystack, needle, index)))
return index;

index += _text.Length;
index += needle.Length;
}
return index;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Skip characters increment for partial-word rejection.

When WholeWords is true and a non-whole match is found, the search resumes after the entire needle (index += needle.Length).
This can skip valid overlapping whole-word matches such as searching “big” in “bigbig”. Incrementing by 1 avoids the blind spot:

- index += needle.Length;
+ index += 1;
🤖 Prompt for AI Agents
In src/NLog/Targets/ConsoleWordHighlightingRule.cs around lines 272 to 284, when
WholeWords is true and a partial match is found, the code increments the index
by the length of the needle, which can skip overlapping whole-word matches. To
fix this, change the increment from needle.Length to 1 so the search advances by
one character instead of skipping ahead, ensuring all potential matches are
checked.

@snakefoot snakefoot force-pushed the dev branch 2 times, most recently from 3643df0 to 7077467 Compare August 8, 2025 14:23
@sonarqubecloud
Copy link

sonarqubecloud bot commented Aug 8, 2025

@snakefoot
Copy link
Contributor Author

This was referenced Sep 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

console-target documentation done all docs done (wiki, api docs, lists on nlog-project.org, xmldocs) feature needs documentation on wiki size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant