Skip to content

Fix link wrapping punctuation#125

Open
leynos wants to merge 4 commits intomainfrom
j7plpf-codex/add-test-for-link-wrapping-punctuation
Open

Fix link wrapping punctuation#125
leynos wants to merge 4 commits intomainfrom
j7plpf-codex/add-test-for-link-wrapping-punctuation

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 22, 2025

Summary

  • add helper for punctuation detection
  • adjust wrapping to keep trailing punctuation with preceding link
  • test punctuation handling after link wrap

Testing

  • make fmt
  • make lint
  • make test

https://chatgpt.com/codex/tasks/task_e_687f3b34074c8322bef6bb579224f3f8

Summary by Sourcery

Fix link wrapping to prevent orphaned punctuation by introducing punctuation detection and updating the wrapping logic

Bug Fixes:

  • Ensure trailing punctuation remains attached to a wrapped link instead of being orphaned

Enhancements:

  • Add is_punctuation helper function to detect ASCII punctuation tokens

Tests:

  • Add test to verify punctuation stays with wrapped links

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 22, 2025

Reviewer's Guide

This PR introduces a helper for punctuation detection, updates the wrapping algorithm to attach trailing punctuation to preceding links, and adds a unit test to verify this behavior.

Class diagram for updated wrap logic and punctuation helper

classDiagram
    class wrap {
        +wrap_preserving_code(text: &str, width: usize) Vec<String>
        +should_break_line(width: usize, current_width: usize, last_split: Option<usize>) bool
        +is_punctuation(token: &str) bool
    }
Loading

Flow diagram for updated line wrapping with punctuation handling

flowchart TD
    A[Start wrapping text] --> B{Is token punctuation?}
    B -- No --> C{Should break line?}
    C -- Yes --> D[Push current line]
    C -- No --> E[Continue accumulating]
    D --> E
    B -- Yes --> F{Is current line non-empty and no last split?}
    F -- Yes --> G[Attach punctuation to current line]
    G --> H[Push current line]
    H --> I[Clear current]
    F -- No --> E
    I --> E
    E --> B
Loading

File-Level Changes

Change Details Files
Introduce punctuation detection helper
  • Add is_punctuation function that checks for ASCII punctuation
src/wrap.rs
Adjust text wrapping to preserve trailing punctuation
  • Skip default line break when punctuation follows without a valid split
  • Append punctuation token to current line and flush it to avoid orphaning
src/wrap.rs
Add unit test for link trailing punctuation
  • Add test_wrap_link_trailing_punctuation to assert punctuation stays with the link
tests/wrap.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 22, 2025

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 2 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 12370b0 and f35086f.

📒 Files selected for processing (1)
  • src/wrap.rs (2 hunks)

Summary by CodeRabbit

  • Bug Fixes

    • Improved line wrapping to ensure punctuation marks directly before or after Markdown links are not left isolated on separate lines.
  • Tests

    • Added tests to verify that punctuation remains correctly attached to links during line wrapping, covering various cases with leading and trailing punctuation.

Walkthrough

Introduce a helper function to detect ASCII punctuation tokens and update the line-wrapping logic in wrap_preserving_code to handle punctuation differently when no split point exists. Add new tests verifying that Markdown links with surrounding punctuation wrap without orphaning punctuation marks on separate lines.

Changes

File(s) Change Summary
src/wrap.rs Add TRAILING_PUNCTUATION constant and is_punctuation function; modify wrap_preserving_code to handle trailing punctuation tokens specially during wrapping.
tests/wrap.rs Add multiple tests to verify wrapping behaviour of Markdown links with trailing, multiple, various, leading, and combined punctuation.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant wrap_preserving_code
    participant is_punctuation

    Caller->>wrap_preserving_code: Call with text and width
    wrap_preserving_code->>is_punctuation: Check if token is punctuation
    is_punctuation-->>wrap_preserving_code: Return true/false
    alt No split point and token is punctuation
        wrap_preserving_code->>wrap_preserving_code: Append token, flush line, clear buffer
    else
        wrap_preserving_code->>wrap_preserving_code: Continue normal wrapping
    end
    wrap_preserving_code-->>Caller: Return wrapped lines
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

Possibly related PRs

Poem

When links and dots would drift apart,
This patch unites them, heart to heart.
No more orphans, lines align—
Punctuation hugs the link just fine!
Code and test in harmony,
Wrapping text with poetry.
🎉

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch j7plpf-codex/add-test-for-link-wrapping-punctuation

🪧 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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 docstrings to generate docstrings for this 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
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey @leynos - I've reviewed your changes and found some issues that need to be addressed.

  • is_punctuation currently treats any ASCII punctuation token (e.g. ‘[’ or ‘]’) as a break—consider narrowing that to just the typical trailing punctuation (.,;:?!…) or using Unicode punctuation categories so you don’t misclassify markdown delimiters.
  • Rather than a separate special‐case block for punctuation after wrapping, you could fold punctuation detection into your existing last_split logic to streamline the flow and avoid extra continues.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- is_punctuation currently treats any ASCII punctuation token (e.g. ‘[’ or ‘]’) as a break—consider narrowing that to just the typical trailing punctuation (.,;:?!…) or using Unicode punctuation categories so you don’t misclassify markdown delimiters.
- Rather than a separate special‐case block for punctuation after wrapping, you could fold punctuation detection into your existing last_split logic to streamline the flow and avoid extra continues.

## Individual Comments

### Comment 1
<location> `tests/wrap.rs:478` </location>
<code_context>
     );
 }
+
+/// Ensures that punctuation following a wrapped link is not orphaned.
+#[test]
+fn test_wrap_link_trailing_punctuation() {
+    let input = lines_vec![
+        "See [HTML table support for more \
+         details](docs/architecture.md#html-table-support-in-mdtablefix).",
+    ];
+    let expected = lines_vec![
+        "See",
+        "[HTML table support for more \
+         details](docs/architecture.md#html-table-support-in-mdtablefix).",
+    ];
+    let output = process_stream(&input);
+    assert_eq!(output, expected);
+}
</code_context>

<issue_to_address>
Consider adding tests for multiple and leading punctuation cases.

Please add tests for multiple trailing punctuation marks, various punctuation types, and punctuation before the link to ensure comprehensive coverage.

Suggested implementation:

```rust
/// Ensures that punctuation following a wrapped link is not orphaned.
#[test]
fn test_wrap_link_trailing_punctuation() {
    let input = lines_vec![
        "See [HTML table support for more \
         details](docs/architecture.md#html-table-support-in-mdtablefix).",
    ];
    let expected = lines_vec![
        "See",

```

```rust
        "[HTML table support for more \
         details](docs/architecture.md#html-table-support-in-mdtablefix).",
    ];
    let output = process_stream(&input);
    assert_eq!(output, expected);
}

/// Ensures that multiple trailing punctuation marks after a wrapped link are not orphaned.
#[test]
fn test_wrap_link_multiple_trailing_punctuation() {
    let input = lines_vec![
        "Check this [link](foo.md)!?",
    ];
    let expected = lines_vec![
        "Check this",
        "[link](foo.md)!?",
    ];
    let output = process_stream(&input);
    assert_eq!(output, expected);
}

/// Ensures that various punctuation types after a wrapped link are not orphaned.
#[test]
fn test_wrap_link_various_trailing_punctuation() {
    let input = lines_vec![
        "Reference [doc](bar.md):",
        "See [note](baz.md)...",
        "Alert [warn](warn.md);",
    ];
    let expected = lines_vec![
        "Reference",
        "[doc](bar.md):",
        "See",
        "[note](baz.md)...",
        "Alert",
        "[warn](warn.md);",
    ];
    let output = process_stream(&input);
    assert_eq!(output, expected);
}

/// Ensures that punctuation before a link is handled correctly.
#[test]
fn test_wrap_link_leading_punctuation() {
    let input = lines_vec![
        "\"[Quoted link](quote.md)\" is important.",
        "([Parenthesized link](paren.md)) is here.",
    ];
    let expected = lines_vec![
        "\"",
        "[Quoted link](quote.md)\" is important.",
        "([Parenthesized link](paren.md)) is here.",
    ];
    let output = process_stream(&input);
    assert_eq!(output, expected);
}

/// Ensures that both leading and trailing punctuation around a link are handled.
#[test]
fn test_wrap_link_leading_and_trailing_punctuation() {
    let input = lines_vec![
        "\"[Link](foo.md)!\"",
        "([Another](bar.md)?)",
    ];
    let expected = lines_vec![
        "\"",
        "[Link](foo.md)!\"",
        "([Another](bar.md)?)",
    ];
    let output = process_stream(&input);
    assert_eq!(output, expected);
}

```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tests/wrap.rs
@github-actions
Copy link
Copy Markdown

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 24, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

@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: 3

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8e8be26 and e0e236d.

📒 Files selected for processing (2)
  • src/wrap.rs (2 hunks)
  • tests/wrap.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • src/wrap.rs
  • tests/wrap.rs
🧬 Code Graph Analysis (1)
tests/wrap.rs (1)
src/process.rs (1)
  • process_stream (206-214)
🔇 Additional comments (6)
src/wrap.rs (1)

196-196: LGTM!

The is_punctuation function correctly checks if all characters in a token are trailing punctuation marks. The implementation is concise and follows the single responsibility principle.

tests/wrap.rs (5)

478-492: LGTM!

The test correctly verifies that trailing punctuation after a link remains attached to the link line rather than being orphaned. The test structure is clear and follows good testing practices.


494-504: LGTM!

The test effectively verifies that multiple trailing punctuation marks (!?) are kept with the link. The assertions correctly check both positive (punctuation stays with link) and negative (punctuation not orphaned) conditions.


506-531: LGTM!

The test comprehensively covers various punctuation types (colon, ellipsis, semicolon) and ensures none are orphaned on separate lines. The test structure efficiently validates multiple scenarios in a single test.


533-550: LGTM!

The test properly verifies that leading punctuation (quotation marks, parentheses) before links is handled correctly without creating orphaned punctuation lines. The assertions are appropriate for the test scenario.


552-565: LGTM!

The test effectively validates the combined scenario of both leading and trailing punctuation around links. This ensures comprehensive coverage of punctuation handling edge cases.

Comment thread src/wrap.rs Outdated
Comment thread src/wrap.rs Outdated
Comment thread src/wrap.rs Outdated
After flushing a line, wrap_preserving_code attempted to check for whitespace again even though the token could not be whitespace. The extra branch was unreachable and made last_split updates confusing. The value is now reset to None unconditionally.
Copy link
Copy Markdown
Contributor

@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

♻️ Duplicate comments (2)
src/wrap.rs (2)

194-194: Include quotation marks and parentheses in the punctuation character set.

The current TRAILING_PUNCTUATION constant lacks quotation marks and parentheses, which are common trailing punctuation around links. Based on test cases and typical usage patterns, these characters should be considered trailing punctuation.

Apply this diff to include the missing punctuation characters:

-const TRAILING_PUNCTUATION: &[char] = &['.', ',', ';', ':', '?', '!', '…'];
+const TRAILING_PUNCTUATION: &[char] = &['.', ',', ';', ':', '?', '!', '…', '"', '\'', '(', ')'];

237-245: Add width constraint to prevent line overflow.

The punctuation attachment logic correctly prevents orphaning punctuation marks, but it doesn't verify that appending the punctuation token won't exceed the target width. This could result in lines longer than intended.

Apply this diff to add the width constraint:

-            if last_split.is_none() && is_punctuation(&token) {
+            if last_split.is_none() && is_punctuation(&token) && token_width <= width {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e0e236d and 12370b0.

📒 Files selected for processing (1)
  • src/wrap.rs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Comments must use en-GB-oxendict spelling and grammar.
Function documentation must include clear examples.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Place function attributes after doc comments.
Do not use return in single-line functions.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Clippy warnings MUST be disallowed.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Use predicate functions for conditional criteria with more than two branches.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Use functions and composition. Avoid repetition by extracting reusable logic. Prefer generators or comprehensions, and declarative code to imperative repetition when readable.
Small, meaningful functions. Functions must be small, clear in purpose, single responsibility, and obey command/query segregation.
Name things precisely. Use clear, descriptive variable and function names. For booleans, prefer names with is, has, or should.
Structure log...

Files:

  • src/wrap.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • src/wrap.rs
⏰ Context from checks skipped due to timeout of 240000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-test
🔇 Additional comments (1)
src/wrap.rs (1)

254-254: Verify unconditional last_split resets in src/wrap.rs

Unconditional resets at lines 243 and 254 clear any previously recorded split point after handling punctuation or at the end of each token iteration. Ensure this change does not regress whitespace-based breaks:

  • Inspect the whitespace branch at lines 210–214 where last_split is set on all-whitespace tokens.
  • Review the resets at line 243 (inside the punctuation handler) and line 254 (fallback for all other tokens).
  • Run the wrapping test suite, paying special attention to scenarios with consecutive spaces or tabs:
cargo test wrap_text_unmatched_backticks wrap_text_preserves_hyphenated_words wrap_text_preserves_code_spans
cargo test test_wrap_list_item test_wrap_blockquote test_wrap_hard_linebreak_backslash

Confirm all tests pass to validate unchanged whitespace splitting behaviour.

Comment thread src/wrap.rs

const TRAILING_PUNCTUATION: &[char] = &['.', ',', ';', ':', '?', '!', '…'];

fn is_punctuation(token: &str) -> bool { token.chars().all(|c| TRAILING_PUNCTUATION.contains(&c)) }
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve function documentation and consider edge cases.

The is_punctuation function lacks documentation and doesn't handle empty strings explicitly. Add rustdoc comments explaining the function's purpose and behaviour.

Apply this diff to add documentation and improve robustness:

-fn is_punctuation(token: &str) -> bool { token.chars().all(|c| TRAILING_PUNCTUATION.contains(&c)) }
+/// Check if a token consists entirely of trailing punctuation characters.
+///
+/// Returns `true` if all characters in the token are found in `TRAILING_PUNCTUATION`,
+/// and `false` for empty strings.
+///
+/// # Examples
+///
+/// ```
+/// # use mdtablefix::wrap::is_punctuation;
+/// assert!(is_punctuation(".,!"));
+/// assert!(!is_punctuation("word."));
+/// assert!(!is_punctuation(""));
+/// ```
+fn is_punctuation(token: &str) -> bool {
+    !token.is_empty() && token.chars().all(|c| TRAILING_PUNCTUATION.contains(&c))
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn is_punctuation(token: &str) -> bool { token.chars().all(|c| TRAILING_PUNCTUATION.contains(&c)) }
/// Check if a token consists entirely of trailing punctuation characters.
///
/// Returns `true` if all characters in the token are found in `TRAILING_PUNCTUATION`,
/// and `false` for empty strings.
///
/// # Examples
///
///
🤖 Prompt for AI Agents
In src/wrap.rs at line 196, the is_punctuation function lacks documentation and
does not explicitly handle empty strings. Add rustdoc comments above the
function to explain its purpose and usage with examples. Modify the function to
return false for empty strings by checking if the token is not empty before
verifying all characters are punctuation.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant