Adding syntax colors without changing the diff
Someone trying the pull request reading guide I'm building pointed out that the code was hard to read because most of it appeared in one color. The diff already had green backgrounds for additions, red for deletions, li
Someone trying the pull request reading guide I'm building pointed out that the code was hard to read because most of it appeared in one color.
The diff already had green backgrounds for additions, red for deletions, line numbers, and links to selected definitions. Those cues showed where the changes were. Keywords, strings, and comments still looked much alike.
I added syntax highlighting to the diff and the definition previews. Here is the same method before and after the change. The example code is from Starlette PR #2041.
Before
After
The added-line backgrounds stay green. Syntax colors provide another set of cues within each line.
Adding those colors also meant preserving the source and the clickable names. Three implementation details mattered:
- Highlight the old and new files separately. A diff mixes deleted and added lines, but those lines belong to different versions of the file. Parsing each complete snapshot, including collapsed context, keeps a multiline string on one side from affecting the other side.
- Keep the original text. The renderer uses highlight.js to obtain token ranges, checks that its decoded text matches the source, and applies those ranges to the original text. It does not insert the highlighter's HTML directly into the page.
- Keep reading possible when highlighting fails. Unknown file types, lexer errors, or a text mismatch fall back to plain code. A color feature should not prevent the diff from rendering.
Definition links use character offsets in the same source text, so preserving whitespace and Unicode positions matters too. The regression tests cover multiline strings, collapsed context, renamed files, and text containing emoji or HTML-like characters.
The screenshots show a presentation change, not a measured improvement in review speed. What the feedback exposed was a gap in the original UI: marking changed lines did not give readers the familiar syntax cues they expected inside those lines.
Written with AI assistance from Codex.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.
