Skip to content

perf: optimize syntax highlighting performance - #21

Merged
unhappychoice merged 3 commits into
mainfrom
feat/optimize-syntax-highlighting-20
Nov 9, 2025
Merged

unhappychoice merged 3 commits into
mainfrom
feat/optimize-syntax-highlighting-20

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Nov 9, 2025 •

Copy link
Copy Markdown
Owner

Closes #20
Closes #23

Summary

  • Pre-calculate highlights for old and new content at file switch
  • Remove intermediate UpdateHighlights calls during animation
  • Use cursor_line to determine which highlights to display
  • Track line offset for correct highlight mapping
  • Refactor editor.rs with smaller, focused functions
  • Fix CRLF byte offset calculation

Performance Improvement

  • Before: O(n) highlight calculations per file (n = number of line changes)
  • After: O(2) highlight calculations per file (once for old_content, once for new_content)

Implementation Details

Highlight Selection Strategy

  • Lines before cursor: new_highlights (already edited)
  • Cursor line: no highlights (currently being edited)
  • Lines after cursor: old_highlights (not yet edited, with line offset)

Line Offset Tracking

  • Track insertions (+1) and deletions (-1) to map current buffer lines to old_content lines
  • Used to calculate correct byte offsets for unedited lines

CRLF Fix

  • Pre-calculate line byte offsets from original content
  • Handle CRLF correctly by scanning for '\n' bytes
  • Avoid byte offset drift caused by str::lines() removing line endings

Refactoring

  • Split highlight_line into focused functions:
    • select_highlights_and_offsets: Choose appropriate highlights and offsets
    • calculate_byte_offset: Compute byte offset with line offset
    • filter_line_highlights: Filter highlights for current line
    • apply_highlights: Apply highlighting with cursor support
    • get_char_color: Get color for character

Test Plan

  • cargo check
  • cargo test
  • cargo clippy --all-targets --all-features
  • cargo fmt

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor
    • Redesigned animation engine to pre-compute highlights and efficiently track content changes during file switching.
    • Enhanced editor rendering pipeline with improved line-by-line display, cursor positioning, and highlight application.

close: #20

- Pre-calculate highlights for old and new content at file switch
- Remove intermediate UpdateHighlights calls during animation
- Use cursor_line to determine which highlights to display:
  - Lines before cursor: new_highlights (edited)
  - Cursor line: no highlights (currently editing)
  - Lines after cursor: old_highlights (unedited, with line offset)
- Track line offset for correct highlight mapping
- Refactor editor.rs with smaller, focused functions

Performance improvement: O(n) → O(2) highlight calculations per file

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 9, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Refactors highlighting to precompute old/new file highlights and per-line byte offsets at SwitchFile. EditorBuffer gained fields for old/new highlights, content lines, and line offsets; AnimationStep::SwitchFile now carries old_content and new_content. UpdateHighlights was removed. EditorPane rendering rewritten to consume precomputed highlights and a line_offset tracked by AnimationEngine.

Changes

Cohort / File(s) Summary
Animation State Refactoring
src/animation.rs
Replaced per-edit tracking fields in EditorBuffer with diff-state fields (old_highlights, new_highlights, old_content_lines, new_content_lines, old_content_line_offsets, new_content_line_offsets). AnimationStep::SwitchFile now carries old_content and new_content. Removed UpdateHighlights. Added AnimationEngine::line_offset, calculate_line_offsets, and updated edit handlers to adjust line_offset instead of emitting highlight updates; initialize buffer from old_content on switch.
Editor Rendering Pipeline
src/panes/editor.rs
Added pub fn render(&self, f: &mut Frame, area: Rect, engine: &AnimationEngine) and refactored per-line rendering into build_line, render_line_number, highlight_line and helpers (select_highlights_and_offsets, calculate_byte_offset, filter_line_highlights, apply_highlights, get_char_color). Rendering now consumes precomputed old/new highlights and line offsets; cursor rendering updated to use byte offsets and line_offset.
Integration & Call-site Updates
src/*
Call sites updated to the new SwitchFile payload and new buffer fields; removed intermediate UpdateHighlights emissions. Buffer reset and initialization logic now precomputes highlights and line offsets (CRLF-safe) on file switch and resets line_offset.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant AnimationEngine
    participant Highlighter
    participant EditorBuffer
    participant EditorPane

    Note over App,AnimationEngine: New flow — highlights computed twice per file
    App->>AnimationEngine: SwitchFile(old_content, new_content, path)
    AnimationEngine->>Highlighter: calc highlights for old_content
    AnimationEngine->>Highlighter: calc highlights for new_content
    AnimationEngine->>EditorBuffer: store old/new highlights, lines, offsets
    EditorPane->>EditorBuffer: read precomputed highlights & lines

    loop Per-line edits (InsertLine/DeleteLine/InsertChar)
        App->>AnimationEngine: edit step
        AnimationEngine->>AnimationEngine: adjust line_offset
        AnimationEngine->>EditorBuffer: update visible content (no highlight recalculation)
        EditorPane->>EditorBuffer: select highlights by line & offset
        EditorPane->>EditorPane: render line with highlights & cursor
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Areas needing careful review:
    • src/animation.rs: correctness of line_offset updates across InsertLine/DeleteLine/InsertChar flows, SwitchFile payload changes, and CRLF-safe calculate_line_offsets.
    • src/panes/editor.rs: selection/filtering of highlights, byte-offset computation using precomputed offsets, and cursor placement at end-of-line.
    • Call-sites that previously emitted UpdateHighlights or relied on removed EditorBuffer fields.

Possibly related PRs

Poem

🐇 I hop through old and new, nibbling bytes with care,
Two pass colors tucked away, no recompute to spare,
Offsets counted true for CRLF and more,
Cursor gleams, highlights rest — I bound across the floor,
A rabbit cheers the tweak, light steps and faster air 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Title clearly identifies the main change as a syntax highlighting performance optimization, which aligns with the core objective of reducing redundant highlight recalculations.
Linked Issues check ✅ Passed Changes implement issue #20 requirements: pre-calculated old/new highlights at file switch, removed intermediate UpdateHighlights calls, line offset tracking for correct byte offsets, and refactored helper functions in editor.rs.
Out of Scope Changes check ✅ Passed All modifications directly support the optimization objective; no unrelated changes detected in the file structure, rendering pipeline, or performance improvements.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a1f6d22 and 4131a78.

📒 Files selected for processing (1)
  • src/panes/editor.rs (1 hunks)

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d2113d and 0c6f38d.

📒 Files selected for processing (2)
  • src/animation.rs (9 hunks)
  • src/panes/editor.rs (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/panes/editor.rs (2)
src/ui.rs (2)
  • render (173-210)
  • new (42-58)
src/animation.rs (2)
  • new (47-59)
  • new (189-209)
src/animation.rs (2)
src/ui.rs (1)
  • new (42-58)
src/syntax/mod.rs (1)
  • new (86-95)

Comment thread src/panes/editor.rs Resolved
Pre-calculate line byte offsets from original content to handle CRLF correctly.
str::lines() removes line endings, causing byte offset drift when using line.len() + 1.

Changes:
- Add old_content_line_offsets and new_content_line_offsets to EditorBuffer
- Implement calculate_line_offsets function that scans for '\n' bytes
- Update calculate_byte_offset to use pre-calculated offsets
- Rename select_highlights_and_content to select_highlights_and_offsets

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0c6f38d and a1f6d22.

📒 Files selected for processing (2)
  • src/animation.rs (9 hunks)
  • src/panes/editor.rs (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/panes/editor.rs (2)
src/ui.rs (2)
  • render (173-210)
  • new (42-58)
src/animation.rs (2)
  • new (50-64)
  • new (196-216)

Comment thread src/panes/editor.rs Resolved
Replace repeated chars().take(char_idx) iteration with cumulative
relative_byte tracking in apply_highlights function.

Before: O(n²) - recalculating byte offset for each character
After: O(n) - accumulating byte offset incrementally

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@unhappychoice
unhappychoice merged commit 17028b4 into main Nov 9, 2025
@unhappychoice
unhappychoice deleted the feat/optimize-syntax-highlighting-20 branch November 9, 2025 19:59
unhappychoice added a commit that referenced this pull request Apr 30, 2026
The file `-` at the repo root was a 533KB `cargo llvm-cov` text report
that landed in `gnhf #21` when the report was redirected to a literal
`-` filename (instead of stdout). It is not referenced by any code or
CI, and its contents are reproducible on demand from `cargo llvm-cov`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix byte offset calculation for CRLF line endings Optimize syntax highlighting performance

1 participant