Skip to content

Refactor attach_orphan_specifiers function to reduce complexity #109

@coderabbitai

Description

@coderabbitai

Problem

The attach_orphan_specifiers function in src/fences.rs has a fairly complex peekable loop that makes the specifier-attachment state transitions difficult to follow and maintain.

Current Implementation Concerns

  • Complex state management within a single function
  • Peekable iterator logic mixed with business logic
  • Multiple conditional branches that are hard to reason about
  • State transitions for tracking whether we're inside a fenced block

Proposed Solution

Refactor the function to improve maintainability and clarity:

  1. Extract helper functions:

    • is_orphan_specifier(line: &str) -> bool - Check if a line is a valid orphan specifier
    • is_opening_fence_without_specifier(line: &str) -> bool - Check if line is an opening fence without language specifier
    • attach_specifier_to_fence(fence_line: &str, specifier: &str) -> String - Combine specifier with fence line
  2. Use a state machine approach:

    • Define clear states: LookingForSpecifier, FoundSpecifier, InsideFence
    • Make state transitions explicit and easier to test
    • Use one pass with peekable() to match "lang" + "```" pairs
  3. Separate concerns:

    • Line classification logic
    • State management
    • Line transformation

Benefits

  • Improved readability and maintainability
  • Easier unit testing of individual components
  • Clearer separation of concerns
  • More explicit state transitions

Related

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions