SLOPSHOPPER

cc-split-diff-view

Draws Edit and Write diffs in two side-by-side columns: removed lines on the left, added lines on the right, in Claude Code's own diff colors. Adds /diffsplit…

panerowsguardcommandprocesstimer
★ 14v1.1.0Apache-2.0updated 2026-10-26neteye-platform/cc-split-diff-view
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cc-split-diff-view
│ ┃ Split Diff ✕ › fix the failing auth test and add an audit log call │ ┃ Uncommitted changes · 0 files · +0 -0 │ ┃ ↑↓ move · Enter jump to a file, or fold it · ⏺ Read(src/auth.ts) │ ┃ r refresh · Esc close ⎿ Read 6 lines │ ┃ Working tree clean. ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ [ Refresh ] ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /diffsplit │ ⎿ cc-split-diff-view: No uncommitted changes. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Split Diff
Uncommitted changes · 0 files · +0 -0 ↑↓ move · Enter jump to a file, or fold it · r refresh · Esc close Working tree clean. [ Refresh ]
README

Split diff view for Claude Code

reach validates

A Claude Code mod that draws the diff of every Edit and Write in two side-by-side columns instead of one stacked -/+ list:

Split diff of an Edit: removed lines on the left, added lines on the right, each with its own line numbers

  • removed lines on the left, added lines on the right
  • each side keeps its real line numbers
  • a changed line sits next to the line that replaced it
  • long runs between hunks collapse to ⋯ N unchanged lines
  • colors are Claude Code's own diff colors (diffRemoved / diffAdded theme keys), so they follow your /theme
  • syntax highlighting comes from Claude Code's own highlighter (the Code element), with the language taken from the file's extension

Errors, edits held for review, brand-new files and anything without a diff keep Claude Code's normal drawing.

/diffsplit

Reviews all the uncommitted changes in one pane, with every diff in two columns. It opens a pane titled Split Diff with the changes of the working directory against HEAD, untracked files included:

  • a list of the changed files comes first, each row ending with its +n -n counts; click a file, or press Enter on it, to jump to its diff
  • under the list, every file is open: its name sits between two lines, with the counts at the end of the row, and its diff follows in two columns
  • click a file's name, or press Enter on it, to fold or unfold that file
  • r reloads the changes
  • Esc closes the pane

The /diffsplit pane: the list of the changed files with their counts, then each file open under its name, between two lines, with its diff in two columns

Binary files are listed with binary and no diff. The pane reads the diff of the first 100 files and draws a limited number of rows (at most 500 per file and about 1200 in all); when a diff is cut it says … N more rows, and folding other files makes room for it.

Requirements

  • Claude Code v2.1.287 or later (the version that introduced mods; they are on by default). Check with claude --version.
  • Mods must be allowed to load: not started with --safe-mode or --bare, and not blocked by your organization's managed settings.

Install

From a terminal:

claude plugin marketplace add neteye-platform/cc-split-diff-view
claude plugin install cc-split-diff-view@neteye-platform

Or from inside a Claude Code session:

/plugin marketplace add neteye-platform/cc-split-diff-view
/plugin install cc-split-diff-view@neteye-platform

No download or build step is needed: Claude Code fetches the repository and loads the TypeScript directly. Start a new session (or run /reload-plugins), then ask Claude to edit a file.

To check it loaded, run /plugin and look for cc-split-diff-view under Installed.

Update

Claude Code caches an installed plugin by version, so updates arrive when the version in .claude-plugin/plugin.json is bumped:

claude plugin marketplace update neteye-platform

Uninstall

claude plugin uninstall cc-split-diff-view@neteye-platform

You can also turn it off without removing it from the Installed tab of /plugin.

Try it for one session without installing

git clone https://github.com/neteye-platform/cc-split-diff-view.git
claude --plugin-dir ./cc-split-diff-view

The mod hot-reloads when you save a file in that directory.

Limitations

  • Only Edit and Write are redrawn. The permission prompt is not a render site, so a mod cannot change it.
  • Each line is highlighted on its own, so something that spans lines (a block comment or a template string) can be colored as plain code when only part of it is in the diff.
  • Hooks stay active in the VS Code extension, claude -p and cloud sessions, but the interface part only draws in the terminal and the Desktop app's Code tab.
  • Mod events and render-site props can change between Claude Code releases. If the diff suddenly looks like the default again, run claude plugin validate . and check the debug log.

Credits

Developed by Oscar Zambotti (@oskarnrk) in the NetEye Platform development team, with Claude Code.

Listed on Awesome Claude Code Mods.

Source 6 files
hooks/register.ts 45 lines
1import type { On } from 'claude-code'
2
3import { registerDiffSplit } from './diff-command.js'
4import { TEXT_BUDGET, drawDiff, rowsWithin } from './draw.js'
5import type { Kit } from './draw.js'
6import { splitRows } from './split-rows.js'
7
8/** Tools whose result is a diff this mod redraws. */
9const TOOLS = ['Edit', 'Write']
10
11/** Rows drawn before "… N more rows". */
12const MAX_ROWS = 200
13
14const isRecord = (value: unknown): value is Record<string, unknown> =>
15  typeof value === 'object' && value !== null
16
17/**
18 * Draws the result block of an Edit or Write call as a split diff: removed
19 * lines in the left column and added lines in the right, with line numbers.
20 *
21 * @param on the engine's registrar
22 */
23export function register(on: On) {
24  registerDiffSplit(on)
25
26  on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
27    const { tool, output, isErrored } = e.props
28    if (!TOOLS.includes(tool) || isErrored || !isRecord(output)) return next(e)
29    // An edit held for review wrote nothing, so there is no diff to show.
30    if (output.staged === true) return next(e)
31
32    const diff = splitRows(output.structuredPatch)
33    // No hunks (a new file, an identical write): leave Claude Code's drawing alone.
34    if (diff === null) return next(e)
35
36    const kit: Kit = $.ui.resolve(e)
37    const path = typeof output.filePath === 'string' ? output.filePath : undefined
38
39    // The same limits as the pane: rows, and the characters the engine draws of a tree.
40    const { count } = rowsWithin(diff, MAX_ROWS, TEXT_BUDGET)
41
42    return drawDiff(kit, diff, { path, maxRows: count, layout: 'tool-result' })
43  })
44}
45
hooks/diff-command.ts 316 lines
1import { atom, read, update } from 'claude-code'
2import type { ElementTable, Hook, On } from 'claude-code'
3
4import { TEXT_BUDGET, drawFit, fitHunks } from './draw.js'
5import type { Fit, Kit as DrawKit } from './draw.js'
6import { parseChanges, parseHunks, parseUntracked } from './git-diff.js'
7import type { Change, FileDiff, Snapshot } from '../types'
8
9const COMMAND = 'diffsplit'
10const PANE = 'diffsplit'
11
12/** Rows drawn for one file before "… N more rows"; the pane scrolls. */
13const MAX_ROWS = 500
14
15/**
16 * Rows drawn in all the files together. A row is about ten nodes of the tree
17 * and the engine refuses a tree of more than 20000, which leaves the pane blank.
18 */
19const MAX_TOTAL_ROWS = 1200
20
21/** Characters a file's row takes besides its path: the folding mark, the counts and the label. */
22const FILE_ROW_CHARS = 30
23
24/** Files whose diff is read, all at once on load; the rest are counted, not shown. */
25const MAX_FILES = 100
26
27/** How often the open pane looks for changes made outside the tools Claude runs. */
28const POLL_MS = 3000
29
30/** Tools that can change the working tree: the open pane reloads when one ends. */
31const WRITING_TOOLS = ['Edit', 'Write', 'NotebookEdit', 'Bash'] as const
32
33/** Git's name for an empty tree, the base of a repository with no commit yet. */
34const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
35
36const GIT = ['git', '--no-pager', '-c', 'core.quotepath=off']
37const DIFF = ['diff', '--no-color', '--no-ext-diff', '--no-renames']
38
39/**
40 * The same for the tracked files. Git names them from the root of the
41 * repository, but the untracked ones (`ls-files --others`) from the working
42 * directory; `--relative` names both from the working directory, so a path
43 * from one list works as a pathspec of the diff in the other. It also keeps the
44 * list to the working directory, as `ls-files` does.
45 */
46const TRACKED = [...DIFF, '--relative']
47
48// Change the tag when the fields of a value change: it declines what an
49// earlier version stored, which outlives a reload.
50const snapshot = atom({ plugin: 'cc-split-diff-view', key: 'snapshot' } as const, null, { shape: 'snapshot-2' })
51const folded = atom({ plugin: 'cc-split-diff-view', key: 'folded' } as const, [], { shape: 'folded-1' })
52
53/** The engine interface a hook receives as `$`. */
54type Engine = Parameters<Hook<'command.run'>>[0]
55
56type Kit = DrawKit & Pick<ElementTable<'terminal'>, 'Button'>
57
58// The module's own, so a reload of the code starts them over: what the pane
59// drew last (see `fingerprint`), the timer that watches the tree, and whether
60// a refresh is under way.
61let seen = ''
62let timer: { cancel: () => void } | undefined
63let isRefreshing = false
64
65/**
66 * Registers `/diffsplit`: a pane that lists the uncommitted changes of the
67 * working directory, each file open under its name as a split diff.
68 *
69 * @param on the engine's registrar
70 */
71export function registerDiffSplit(on: On) {
72  on('session.start', async ($, e, next) => {
73    await $.command.register({
74      name: COMMAND,
75      description: 'Show the uncommitted changes in a split diff pane',
76    })
77    return next(e)
78  })
79
80  on('command.run', { command: COMMAND }, async $ => {
81    const loaded = await load($, { isReload: false })
82    seen = await fingerprint($).catch(() => '')
83    await $.ui.open({ id: PANE, title: 'Split Diff', focus: true, closeOnEscape: true, rows: 30, columns: 120 })
84
85    // While the pane is open, look at the tree now and then: it ends itself when the pane closes.
86    timer?.cancel()
87    timer = $.clock.every(POLL_MS, () => void refresh($))
88    if (loaded.kind === 'error') return { text: loaded.message }
89    const n = loaded.files.length + loaded.hiddenFiles
90    return { text: n === 0 ? 'No uncommitted changes.' : `Split diff opened: ${n} changed ${n === 1 ? 'file' : 'files'}.` }
91  })
92
93  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
94    const kit: Kit = $.ui.resolve(e)
95    const current = await read($, snapshot)
96    const closed = await read($, folded)
97
98    if (current === null) return kit.Text({ dimColor: true, children: ['Run /diffsplit to load the changes.'] })
99    if (current.kind === 'error') return kit.Text({ color: 'error', children: [current.message] })
100
101    return drawFiles($, kit, current.files, current.hiddenFiles, closed, e.props.bodyColumns)
102  })
103
104  // A tool that may have written files: the open pane shows it at once.
105  on('tool.call', { tool: WRITING_TOOLS }, async ($, e, next) => {
106    const ran = await next(e)
107    void refresh($)
108    return ran
109  })
110}
111
112/**
113 * Asks git for the changes against HEAD, plus the untracked files, and keeps
114 * them. A reload from the pane itself keeps the files the person folded.
115 */
116async function load($: Engine, { isReload }: { isReload: boolean }): Promise<Snapshot> {
117  const result = await ask($)
118  await update($, snapshot, () => result)
119  if (!isReload) await update($, folded, () => [])
120  return result
121}
122
123/** Git's base for the diff: HEAD, or the empty tree in a repository with no commit yet. */
124async function baseOf($: Engine) {
125  const head = await $.process.run([...GIT, 'rev-parse', '--verify', '--quiet', 'HEAD'])
126  return head.exitCode === 0 ? 'HEAD' : EMPTY_TREE
127}
128
129/**
130 * A stand-in for the state of the working tree: the diff of the tracked files,
131 * and the names and content hashes of the untracked ones. Two equal strings
132 * mean nothing changed, and the pane is not drawn again.
133 */
134async function fingerprint($: Engine): Promise<string> {
135  const git = (args: string[], stdin?: string) => $.process.run([...GIT, ...args], stdin === undefined ? undefined : { stdin })
136  const [diff, others] = await Promise.all([git([...TRACKED, await baseOf($)]), git(['ls-files', '--others', '--exclude-standard', '-z'])])
137  const paths = others.stdout.split('\0').filter(path => path !== '')
138  const hashes = paths.length === 0 ? '' : (await git(['hash-object', '--stdin-paths'], paths.join('\n'))).stdout
139  return [diff.stdout, others.stdout, hashes].join('\u0001')
140}
141
142/** Reloads the pane whether or not the tree changed: the person asked. */
143async function reloadNow($: Engine) {
144  await load($, { isReload: true })
145  seen = await fingerprint($).catch(() => seen)
146}
147
148/**
149 * Reloads the pane if it is open and the working tree is not what it drew.
150 * Never throws and never runs twice at once; a failure is tried again on the
151 * next tick.
152 */
153async function refresh($: Engine) {
154  if (isRefreshing) return
155  isRefreshing = true
156  try {
157    if (!(await $.ui.panes()).some(pane => pane.id === PANE)) {
158      timer?.cancel()
159      timer = undefined
160      return
161    }
162    const now = await fingerprint($)
163    if (now === seen) return
164    await load($, { isReload: true })
165    seen = now
166  } catch {
167    // The next tick tries again.
168  } finally {
169    isRefreshing = false
170  }
171}
172
173async function ask($: Engine): Promise<Snapshot> {
174  const git = (args: string[]) => $.process.run([...GIT, ...args])
175
176  const inside = await git(['rev-parse', '--is-inside-work-tree']).catch(() => null)
177  if (inside === null || inside.exitCode !== 0) return { kind: 'error', message: 'Not inside a git repository.' }
178
179  const base = await baseOf($)
180  const [nameStatus, numstat, others] = await Promise.all([
181    git([...TRACKED, '--name-status', '-z', base]),
182    git([...TRACKED, '--numstat', '-z', base]),
183    git(['ls-files', '--others', '--exclude-standard', '-z']),
184  ])
185  if (nameStatus.exitCode !== 0) return { kind: 'error', message: nameStatus.stderr.trim() || 'git diff failed.' }
186
187  const all = [...parseChanges(nameStatus.stdout, numstat.stdout), ...parseUntracked(others.stdout)]
188  const files = await Promise.all(all.slice(0, MAX_FILES).map(change => diffOf($, change, base)))
189  return { kind: 'changes', files, hiddenFiles: Math.max(0, all.length - MAX_FILES) }
190}
191
192/** One file with its hunks. An untracked file gets its counts from them. */
193async function diffOf($: Engine, change: Change, base: string): Promise<FileDiff> {
194  if (change.isBinary) return { ...change, hunks: [] }
195
196  const git = (args: string[]) => $.process.run([...GIT, ...args])
197  // `--no-index` exits 1 when the files differ, which an untracked file always does.
198  const shown =
199    change.status === 'untracked'
200      ? await git([...DIFF, '--no-index', '--', '/dev/null', change.path])
201      : await git([...TRACKED, base, '--', change.path])
202  const hunks = parseHunks(shown.stdout)
203  if (change.status !== 'untracked') return { ...change, hunks }
204
205  const added = hunks.reduce((sum, hunk) => sum + hunk.lines.filter(line => line.startsWith('+')).length, 0)
206  return { ...change, added, hunks }
207}
208
209function drawFiles($: Engine, kit: Kit, files: FileDiff[], hidden: number, closed: string[], columns: number) {
210  const { Box, Text, Button } = kit
211  const added = files.reduce((sum, file) => sum + file.added, 0)
212  const removed = files.reduce((sum, file) => sum + file.removed, 0)
213  const count = files.length + hidden
214
215  // The list, and the name and two rules of each file, come off the character budget first.
216  const frame = files.reduce((sum, file) => sum + 2 * (file.path.length + FILE_ROW_CHARS) + 2 * columns, 0)
217
218  // Each open file draws what is left of the row and character budgets.
219  let rowsLeft = MAX_TOTAL_ROWS
220  let charsLeft = Math.max(0, TEXT_BUDGET - frame)
221  const drawn = files.map(file => {
222    const isFolded = closed.includes(file.path)
223    const isShown = !isFolded && !file.isBinary && file.hunks.length > 0
224    const fit = isShown ? fitHunks(file.hunks, Math.min(MAX_ROWS, rowsLeft), charsLeft) : null
225    rowsLeft -= fit?.count ?? 0
226    charsLeft -= fit?.chars ?? 0
227    return drawFile($, kit, file, isFolded, fit, columns)
228  })
229
230  return Box({
231    flexDirection: 'column',
232    children: [
233      Box({
234        flexDirection: 'row',
235        children: [
236          Text({ bold: true, children: ['Uncommitted changes'] }),
237          Text({ dimColor: true, children: [` · ${count} ${count === 1 ? 'file' : 'files'} · `] }),
238          Text({ color: 'success', children: ['+' + added] }),
239          Text({ children: [' '] }),
240          Text({ color: 'error', children: ['-' + removed] }),
241        ],
242      }),
243      Text({ dimColor: true, children: ['↑↓ move · Enter jump to a file, or fold it · r refresh · Esc close'] }),
244      count === 0 ? Text({ dimColor: true, children: ['Working tree clean.'] }) : null,
245      // The list: a click takes the pane to the file.
246      ...files.map(file =>
247        fileRow(kit, file, {
248          key: 'jump:' + file.path,
249          label: file.path,
250          // A pane that is not drawn cannot scroll; that is no error.
251          onPress: () => void $.ui.scroll({ to: { key: 'file:' + file.path }, in: PANE, block: 'start' }).catch(() => undefined),
252        }),
253      ),
254      ...drawn,
255      hidden > 0 ? Text({ dimColor: true, children: [`… ${hidden} more files not shown`] }) : null,
256      Box({
257        flexDirection: 'row',
258        marginTop: 1,
259        children: [Button({ key: 'refresh', hotkey: 'r', onPress: () => void reloadNow($), children: ['Refresh'] })],
260      }),
261    ],
262  })
263}
264
265function drawFile($: Engine, kit: Kit, file: FileDiff, isFolded: boolean, fit: Fit | null, columns: number) {
266  const { Box, Text } = kit
267  const toggle = () =>
268    void update($, folded, list => (list.includes(file.path) ? list.filter(path => path !== file.path) : [...list, file.path]))
269  // The name sits between two lines, the whole width of the pane.
270  const rule = () => Text({ dimColor: true, wrap: 'truncate-end', children: ['─'.repeat(columns)] })
271
272  return Box({
273    flexDirection: 'column',
274    marginTop: 1,
275    children: [
276      rule(),
277      fileRow(kit, file, { key: 'file:' + file.path, label: (isFolded ? '▸ ' : '▾ ') + file.path, onPress: toggle }),
278      rule(),
279      isFolded ? null : body(kit, file, fit),
280    ],
281  })
282}
283
284/** A file's row: its name is the button, and its counts sit at the end of the row. */
285function fileRow({ Box, Text, Button }: Kit, file: FileDiff, { key, label, onPress }: { key: string; label: string; onPress: () => void }) {
286  return Box({
287    flexDirection: 'row',
288    children: [
289      Box({ flexGrow: 1, flexShrink: 1, children: [Button({ key, plain: true, onPress, children: [label] })] }),
290      Box({ flexShrink: 0, flexDirection: 'row', children: counts(Text, file) }),
291    ],
292  })
293}
294
295function counts(Text: Kit['Text'], file: FileDiff) {
296  const label = file.status === 'untracked' ? [Text({ dimColor: true, children: ['untracked '] })] : []
297  if (file.isBinary) return [...label, Text({ dimColor: true, children: ['binary'] })]
298  return [
299    ...label,
300    Text({ color: 'success', children: ['+' + file.added] }),
301    Text({ children: [' '] }),
302    Text({ color: 'error', children: ['-' + file.removed] }),
303  ]
304}
305
306function body(kit: Kit, file: FileDiff, fit: Fit | null) {
307  const { Text } = kit
308  if (file.isBinary) return Text({ dimColor: true, children: ['Binary file.'] })
309  if (fit === null) {
310    const empty = file.status === 'deleted' ? 'Empty file deleted.' : 'No changes to show.'
311    return Text({ dimColor: true, children: [empty] })
312  }
313
314  return drawFit(kit, fit, file.path)
315}
316
hooks/draw.ts 287 lines
1import type { ElementTable } from 'claude-code'
2
3import type { Hunk } from '../types'
4import { drawable, splitRows } from './split-rows.js'
5import type { Cell, SplitDiff, SplitRow } from './split-rows.js'
6
7export type Kit = Pick<ElementTable<'terminal'>, 'Box' | 'Text' | 'Code'>
8
9/**
10 * Where a split diff sits. The rows are the same everywhere; only what
11 * surrounds them differs.
12 */
13const LAYOUTS = {
14  /** Under a tool call in the transcript: the summary line with the built-in's response marker, and a frame. */
15  'tool-result': { lead: '  ⎿  ', indent: 5, isFramed: true },
16  /** In the pane: no summary (the file's row has the counts), no frame, the rule between the columns alone. */
17  pane: { lead: null, indent: 0, isFramed: false },
18} as const
19
20export type DiffLayout = keyof typeof LAYOUTS
21
22/**
23 * Characters of diff text drawn in one tree. The engine draws only the first
24 * 100000 and cuts the rest, the "… more rows" with it; the margin is for the
25 * text around the diff.
26 */
27export const TEXT_BUDGET = 80_000
28
29/** Lines of the rule between the columns; a row that wraps past it shows a gap in the rule. */
30const RULE_LENGTH = 16
31
32/** Characters of a one-line hunk header (`@@ -12,1 +12,1 @@` and the mark). */
33const HEADER_LENGTH = 22
34
35/**
36 * The characters of text a row puts in the tree. The engine draws only the
37 * first 100000 of a tree, so a long diff has to be counted before it is drawn.
38 */
39function rowChars(row: SplitRow) {
40  if (row.kind === 'gap') return 60
41  const text = (cell: Cell | null) => (cell === null ? 1 : HEADER_LENGTH + cell.text.length)
42  // A changed pair is drawn as one hunk in each column.
43  if (row.changed && row.left !== null && row.right !== null) {
44    return 2 * (HEADER_LENGTH + row.left.text.length + row.right.text.length) + RULE_LENGTH
45  }
46  return text(row.left) + text(row.right) + RULE_LENGTH
47}
48
49/**
50 * How many of the first rows of a diff fit in `maxRows` rows and `maxChars`
51 * characters of text, and the characters those rows take.
52 */
53export function rowsWithin(diff: SplitDiff, maxRows: number, maxChars: number) {
54  let count = 0
55  let chars = 0
56  for (const row of diff.rows.slice(0, maxRows)) {
57    const next = chars + rowChars(row)
58    if (next > maxChars) break
59    chars = next
60    count++
61  }
62  return { count, chars }
63}
64
65export type DiffOptions = {
66  /** The file's path, for the language of the highlighting. */
67  path: string | undefined
68  /** Rows drawn before "… N more rows". */
69  maxRows: number
70  layout: DiffLayout
71}
72
73/**
74 * A split diff: the removed lines in the left column and the added ones in the
75 * right, with line numbers, under a "Added 3 lines, removed 1 line" summary
76 * where the layout has one. Every place that draws a diff goes through here.
77 */
78export function drawDiff(kit: Kit, diff: SplitDiff, { path, maxRows, layout }: DiffOptions) {
79  const { Box, Text } = kit
80  const { lead, indent, isFramed } = LAYOUTS[layout]
81
82  return Box({
83    flexDirection: 'column',
84    children: [
85      lead === null
86        ? null
87        : Box({
88            flexDirection: 'row',
89            children: [Text({ dimColor: true, children: [lead] }), ...summary(Text, diff.added, diff.removed)],
90          }),
91      Box({
92        flexDirection: 'column',
93        marginLeft: indent,
94        ...(isFramed ? { borderStyle: 'round', borderDimColor: true } : {}),
95        children: drawRows(kit, diff, path, maxRows),
96      }),
97    ],
98  })
99}
100
101/**
102 * What fits of a file's hunks in the rows and characters left: the split rows,
103 * or, for what has no split form (a final newline on one side only), the lines
104 * of git's own diff. Either way `count` rows and `chars` characters are spent.
105 */
106export type Fit =
107  | { kind: 'split'; diff: SplitDiff; count: number; chars: number }
108  | { kind: 'unified'; lines: string[]; total: number; count: number; chars: number }
109
110/**
111 * The one place that shares the row and character budgets out, for the split
112 * rows and the unified lines alike. Lines are made drawable as the split rows
113 * are: tabs laid out, control characters dropped, cut at the engine's limit.
114 */
115export function fitHunks(hunks: readonly Hunk[], maxRows: number, maxChars: number): Fit {
116  const diff = splitRows(hunks)
117  if (diff !== null) return { kind: 'split', diff, ...rowsWithin(diff, maxRows, maxChars) }
118
119  const all = hunks.flatMap(hunk => [`@@ -${hunk.oldStart} +${hunk.newStart} @@`, ...hunk.lines].map(drawable))
120  const lines: string[] = []
121  let chars = 0
122  for (const line of all.slice(0, maxRows)) {
123    // The line break is a character of the source too.
124    if (chars + line.length + 1 > maxChars) break
125    chars += line.length + 1
126    lines.push(line)
127  }
128  return { kind: 'unified', lines, total: all.length, count: lines.length, chars }
129}
130
131/**
132 * Draws a fit: the split diff in the pane's layout, or git's own diff, in the
133 * engine's drawing, with "… N more rows" after what was cut.
134 */
135export function drawFit(kit: Kit, fit: Fit, path: string | undefined) {
136  if (fit.kind === 'split') return drawDiff(kit, fit.diff, { path, maxRows: fit.count, layout: 'pane' })
137
138  const { Box, Text, Code } = kit
139  const hidden = fit.total - fit.count
140  return Box({
141    flexDirection: 'column',
142    children: [
143      fit.count === 0
144        ? null
145        : Code({ source: fit.lines.join('\n'), format: 'diff', wrap: 'wrap', ...(path === undefined ? {} : { path }) }),
146      hidden > 0 ? Text({ dimColor: true, children: ['… ' + hidden + ' more rows'] }) : null,
147    ],
148  })
149}
150
151/**
152 * The rows of a split diff, ready to sit in a column, with "… N more rows"
153 * after the first `maxRows`.
154 */
155function drawRows(kit: Kit, diff: SplitDiff, path: string | undefined, maxRows: number) {
156  const shown = diff.rows.slice(0, maxRows)
157  const hidden = diff.rows.length - shown.length
158  return [
159    ...shown.map(row => drawRow(kit, row, path)),
160    hidden > 0 ? kit.Text({ dimColor: true, children: ['… ' + hidden + ' more rows'] }) : null,
161  ]
162}
163
164function drawRow(kit: Kit, row: SplitRow, path: string | undefined) {
165  const { Box, Text } = kit
166  if (row.kind === 'gap') {
167    // The label sits in both columns, so a wide screen doesn't leave the right one blank.
168    const label = () => Text({ dimColor: true, children: ['⋯ ' + row.hidden + ' unchanged lines'] })
169    // A blank line above and below sets the label apart; an empty 1-wide Box takes the separator's place so the columns line up.
170    const column = { width: '50%', flexShrink: 1, paddingY: 1 } as const
171    return Box({
172      flexDirection: 'row',
173      children: [Box({ ...column, children: [label()] }), Box({ width: 1, flexShrink: 0 }), Box({ ...column, children: [label()] })],
174    })
175  }
176  if (row.changed && row.left !== null && row.right !== null) {
177    return drawPair(kit, row.left, row.right, path)
178  }
179  return Box({
180    flexDirection: 'row',
181    alignItems: 'stretch',
182    children: [
183      drawCell(kit, row.left, row.changed ? 'removed' : 'same', path),
184      separator(kit),
185      drawCell(kit, row.right, row.changed ? 'added' : 'same', path),
186    ],
187  })
188}
189
190function drawCell(
191  { Box, Text, Code }: Kit,
192  cell: Cell | null,
193  kind: 'removed' | 'added' | 'same',
194  path: string | undefined,
195) {
196  const column = { width: '50%', flexShrink: 1, flexDirection: 'row' } as const
197
198  // Nothing on this side of the row: keep the column, draw nothing in it.
199  if (cell === null) return Box({ ...column, children: [Text({ children: [' '] })] })
200
201  // One-line hunk through the engine's diff renderer, so gutter, marker and
202  // add/remove colors are exactly the built-in diff's.
203  const n = cell.no
204  const header =
205    kind === 'removed' ? `@@ -${n},1 +${n},0 @@` : kind === 'added' ? `@@ -${n},0 +${n},1 @@` : `@@ -${n},1 +${n},1 @@`
206  const sign = kind === 'removed' ? '-' : kind === 'added' ? '+' : ' '
207
208  return Box({
209    ...column,
210    children: [
211      Code({
212        source: header + '\n' + sign + cell.text,
213        format: 'diff',
214        wrap: 'wrap',
215        ...(path === undefined ? {} : { path }),
216      }),
217    ],
218  })
219}
220
221/**
222 * A removed line next to the line that replaced it. The engine draws the two as
223 * one hunk, which is what makes it tint the words that changed; each column
224 * then shows its own line of that hunk. Long lines are cut with an ellipsis, as
225 * a column clipped to one row cannot wrap.
226 */
227function drawPair(kit: Kit, left: Cell, right: Cell, path: string | undefined) {
228  const { Box, Code } = kit
229  const hunk = () =>
230    Code({
231      source: `@@ -${left.no},1 +${right.no},1 @@\n-${left.text}\n+${right.text}`,
232      format: 'diff',
233      wrap: 'truncate-end',
234      ...(path === undefined ? {} : { path }),
235    })
236  const column = { width: '50%', flexShrink: 1, height: 1, overflow: 'hidden' } as const
237  return Box({
238    flexDirection: 'row',
239    children: [
240      Box({ ...column, children: [hunk()] }),
241      separator(kit),
242      Box({
243        ...column,
244        children: [Box({ position: 'absolute', top: -1, left: 0, right: 0, children: [hunk()] })],
245      }),
246    ],
247  })
248}
249
250/**
251 * A dim vertical rule between the columns. It stretches to the row's height
252 * (wrapped lines make rows taller), so it draws a tall line out of flow and
253 * lets the clipped box cut it to the row.
254 */
255function separator({ Box, Text }: Kit) {
256  return Box({
257    width: 1,
258    flexShrink: 0,
259    overflow: 'hidden',
260    children: [
261      Box({
262        position: 'absolute',
263        top: 0,
264        bottom: 0,
265        width: 1,
266        // One node: the glyphs wrap at the box's one column, a line each.
267        children: [Text({ dimColor: true, children: ['│'.repeat(RULE_LENGTH)] })],
268      }),
269    ],
270  })
271}
272
273/** "Added 3 lines, removed 1 line", the counts bold, as the built-in diff words it. */
274function summary(Text: Kit['Text'], added: number, removed: number) {
275  const noun = (n: number) => (n > 1 ? ' lines' : ' line')
276  const parts: ReturnType<Kit['Text']>[] = []
277  if (added > 0) {
278    parts.push(Text({ children: ['Added '] }), Text({ bold: true, children: [String(added)] }))
279    parts.push(Text({ children: [noun(added) + (removed > 0 ? ', ' : '')] }))
280  }
281  if (removed > 0) {
282    parts.push(Text({ children: [added === 0 ? 'Removed ' : 'removed '] }))
283    parts.push(Text({ bold: true, children: [String(removed)] }), Text({ children: [noun(removed)] }))
284  }
285  return parts
286}
287
hooks/split-rows.ts 141 lines
1/** One side of a split row: the line's number in its file and its text. */
2export type Cell = { no: number; text: string }
3
4export type SplitRow =
5  | {
6      kind: 'row'
7      /** The removed (or unchanged) line; null when this row only adds. */
8      left: Cell | null
9      /** The added (or unchanged) line; null when this row only removes. */
10      right: Cell | null
11      changed: boolean
12    }
13  | { kind: 'gap'; hidden: number }
14
15export type SplitDiff = {
16  rows: SplitRow[]
17  added: number
18  removed: number
19  /** Digits of the largest line number, for the number gutters. */
20  numberWidth: number
21}
22
23type Hunk = { oldStart: number; newStart: number; lines: string[] }
24
25const TAB = '    '
26
27/** The most characters the engine takes in one drawn leaf. */
28const MAX_TEXT = 10_000
29
30/**
31 * A line made safe to draw: tabs laid out as spaces, every control, format and
32 * invisible character dropped (a stray '\r' from a CRLF file would otherwise
33 * get the whole tree refused), and cut to the engine's cap.
34 */
35export const drawable = (text: string) =>
36  text
37    .replace(/\t/g, TAB)
38    .replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, '')
39    .slice(0, MAX_TEXT)
40
41const isRecord = (value: unknown): value is Record<string, unknown> =>
42  typeof value === 'object' && value !== null
43
44/** A tool result's `structuredPatch`, keeping only entries shaped like a hunk. */
45const hunksOf = (patch: unknown): Hunk[] =>
46  (Array.isArray(patch) ? patch : []).flatMap((hunk: unknown): Hunk[] => {
47    if (!isRecord(hunk)) return []
48    const { oldStart, newStart, lines } = hunk
49    if (typeof oldStart !== 'number' || typeof newStart !== 'number') return []
50    if (!Array.isArray(lines)) return []
51    return [
52      {
53        oldStart,
54        newStart,
55        lines: lines.filter((line): line is string => typeof line === 'string'),
56      },
57    ]
58  })
59
60/**
61 * Turns a tool result's `structuredPatch` (unified hunks whose lines start with
62 * ' ', '-' or '+') into side-by-side rows. Each run of removed lines is paired
63 * with the added lines that follow it. A side that is null has no line in that
64 * row; a cell with empty text is a real blank line.
65 *
66 * @returns null when the patch holds no hunks, or when one side lacks a
67 * trailing newline the other has (the default renderer shows that marker)
68 */
69export function splitRows(patch: unknown): SplitDiff | null {
70  const hunks = hunksOf(patch)
71  if (hunks.length === 0) return null
72
73  const rows: SplitRow[] = []
74  let added = 0
75  let removed = 0
76  let largest = 0
77  let previousOldEnd: number | null = null
78
79  for (const hunk of hunks) {
80    if (previousOldEnd !== null) {
81      const hidden = hunk.oldStart - previousOldEnd
82      if (hidden > 0) rows.push({ kind: 'gap', hidden })
83    }
84
85    let oldNo = hunk.oldStart
86    let newNo = hunk.newStart
87    let dels: Cell[] = []
88    let adds: Cell[] = []
89    let previous = ''
90    let oldLacksNewline = false
91    let newLacksNewline = false
92    const flush = () => {
93      const count = Math.max(dels.length, adds.length)
94      for (let i = 0; i < count; i++) {
95        rows.push({
96          kind: 'row',
97          left: dels[i] ?? null,
98          right: adds[i] ?? null,
99          changed: true,
100        })
101      }
102      dels = []
103      adds = []
104    }
105
106    for (const line of hunk.lines) {
107      const mark = line.charAt(0)
108      const text = drawable(line.slice(1))
109      if (mark === '\\') {
110        // "\ No newline at end of file" refers to the line before it
111        if (previous !== '+') oldLacksNewline = true
112        if (previous !== '-') newLacksNewline = true
113        continue
114      }
115      previous = mark
116      if (mark === '-') {
117        dels.push({ no: oldNo++, text })
118        removed++
119      } else if (mark === '+') {
120        adds.push({ no: newNo++, text })
121        added++
122      } else {
123        flush()
124        rows.push({
125          kind: 'row',
126          left: { no: oldNo++, text },
127          right: { no: newNo++, text },
128          changed: false,
129        })
130      }
131    }
132    flush()
133    if (oldLacksNewline !== newLacksNewline) return null
134
135    previousOldEnd = oldNo
136    largest = Math.max(largest, oldNo, newNo)
137  }
138
139  return { rows, added, removed, numberWidth: String(largest).length }
140}
141
hooks/git-diff.ts 61 lines
1import type { Change, ChangeStatus, Hunk } from '../types'
2
3const STATUS: Record<string, ChangeStatus> = { A: 'added', D: 'deleted' }
4
5const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/
6
7/**
8 * Joins the output of `git diff --name-status -z --no-renames` and
9 * `git diff --numstat -z --no-renames` into one list, in git's order.
10 */
11export function parseChanges(nameStatus: string, numstat: string): Change[] {
12  const counts = new Map<string, { added: number; removed: number; isBinary: boolean }>()
13  for (const record of numstat.split('\0')) {
14    const [added, removed, ...path] = record.split('\t')
15    if (path.length === 0) continue
16    // A binary file counts as '-' on both sides.
17    const isBinary = added === '-'
18    counts.set(path.join('\t'), {
19      added: isBinary ? 0 : Number(added),
20      removed: isBinary ? 0 : Number(removed),
21      isBinary,
22    })
23  }
24
25  const tokens = nameStatus.split('\0')
26  const changes: Change[] = []
27  for (let i = 0; i + 1 < tokens.length; i += 2) {
28    const path = tokens[i + 1] as string
29    const count = counts.get(path) ?? { added: 0, removed: 0, isBinary: false }
30    changes.push({ path, status: STATUS[(tokens[i] as string).charAt(0)] ?? 'modified', ...count })
31  }
32  return changes
33}
34
35/** The files of `git ls-files --others -z`, as changes. */
36export function parseUntracked(output: string): Change[] {
37  return output
38    .split('\0')
39    .filter(path => path !== '')
40    .map(path => ({ path, status: 'untracked', added: 0, removed: 0, isBinary: false }))
41}
42
43/**
44 * The hunks of the unified diff of one file. Everything before the first
45 * `@@` (the `diff --git`, mode and `---`/`+++` lines) is skipped.
46 */
47export function parseHunks(diff: string): Hunk[] {
48  const hunks: Hunk[] = []
49  let current: Hunk | null = null
50  for (const line of diff.split('\n')) {
51    const header = HUNK_HEADER.exec(line)
52    if (header !== null) {
53      current = { oldStart: Number(header[1]), newStart: Number(header[2]), lines: [] }
54      hunks.push(current)
55      continue
56    }
57    if (current !== null && line !== '' && ' +-\\'.includes(line.charAt(0))) current.lines.push(line)
58  }
59  return hunks
60}
61
types/index.d.ts 43 lines
1/** How git sees a changed file. */
2export type ChangeStatus = 'modified' | 'added' | 'deleted' | 'untracked'
3
4/** One changed file in the `/diffsplit` pane. */
5export type Change = {
6  path: string
7  status: ChangeStatus
8  added: number
9  removed: number
10  /** Git cannot show a text diff of the file. */
11  isBinary: boolean
12}
13
14/** One hunk of a unified diff; `lines` keep their ' ', '-', '+' or '\' mark. */
15export type Hunk = {
16  oldStart: number
17  newStart: number
18  lines: string[]
19}
20
21/** A changed file with the diff git gave for it. */
22export type FileDiff = Change & { hunks: Hunk[] }
23
24/** What `git` reported when the pane was last loaded. */
25export type Snapshot =
26  | {
27      kind: 'changes'
28      files: FileDiff[]
29      /** Changed files past the limit: counted, not shown. */
30      hiddenFiles: number
31    }
32  | { kind: 'error'; message: string }
33
34declare module 'claude-code' {
35  interface PluginState {
36    'cc-split-diff-view': {
37      snapshot: Shaped<Snapshot | null>
38      /** Paths of the files the person folded. */
39      folded: Shaped<string[]>
40    }
41  }
42}
43