SLOPSHOPPER

split-diff

터미널 폭이 120칸 이상이면 Edit와 Write 결과의 diff에서 원래 내용은 왼쪽에, 바뀐 내용은 오른쪽에 표시합니다. 바뀐 단어는 더 밝은 색으로 강조합니다

rows
★ 1v0.3.0MITupdated 2026-10-19oobg/claude-code-mods/mods/split-diff
A shopper browsing a rack in a slop shop
README

<img alt="claude-code-mods 로고" src="./docs/images/logo.png" width="160">

<h1 align="center">claude-code-mods</h1>

<a href="./LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-111111?style=flat-square"></a> <a href="https://claude.com/claude-code"><img alt="Claude Code 2.1.303" src="https://img.shields.io/badge/Claude%20Code-2.1.303-111111?style=flat-square"></a> <a href="#설치"><img alt="marketplace oobg" src="https://img.shields.io/badge/marketplace-oobg-111111?style=flat-square"></a> <img alt="6 mods" src="https://img.shields.io/badge/mods-6-D97757?style=flat-square"> <a href="https://github.com/oobg/claude-code-mods/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/oobg/claude-code-mods?style=flat-square&color=111111"></a>

<a href="#주요-기능"><b>주요 기능</b></a> &nbsp;|&nbsp; <a href="#설치"><b>설치</b></a> &nbsp;|&nbsp; <a href="#모드-목록"><b>모드 목록</b></a> &nbsp;|&nbsp; <a href="#상세-문서"><b>상세 문서</b></a> &nbsp;|&nbsp; <a href="https://oobg.github.io/claude-code-mods/"><b>문서 사이트</b></a>

claude-code-mods는 Claude Code의 입력창과 도구 결과에 기능을 추가하는 모드 6개를 모은 저장소입니다. 입력창 위에서는 다음 요청을 제안하고 자주 쓰는 문구 프리셋을 표시하며, 입력창 아래에서는 세션 상태를 보여 줍니다. Finder에서 복사한 파일을 붙여넣으면 파일 이름을 @경로 멘션으로 바꾸고, Cmd+Z로 입력 내용을 되돌릴 수 있습니다. 넓은 터미널에서는 Edit와 Write 결과의 diff를 좌우로 비교할 수 있습니다. 새 버전이 설치되면 알리고, Orca 탭에서는 기존 대화를 이어서 다시 엽니다. 필요한 모드만 골라 설치할 수 있습니다. relaunch의 자동 다시 열기에는 Orca가 필요합니다.

주요 기능

<table class="cards"> <tr> <td width="50%" valign="top"> <a href="./docs/next-prompts.md"><picture> <img alt="next-prompts: 턴이 끝나면 다음에 보낼 만한 요청이 하나씩 나타난다" src="./docs/images/showcase/suggest-light.gif" width="100%"> <sub>턴이 끝나면 다음에 보낼 만한 요청을 최대 3개 제안합니다. <code>$1</code>을 입력하고 스페이스를 누르거나 번호를 클릭하면 문구가 입력창에 들어가고, 문구를 클릭하면 바로 보냅니다</sub> </td> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="quick-replies: 입력창에 $1을 치고 스페이스를 누르면 $1이 1번 프리셋 문구로 바뀐다" src="./docs/images/showcase/preset-light.gif" width="100%"> <sub>자주 쓰는 문구를 전역 또는 저장소별 프리셋으로 저장합니다. 입력창에 <code>$4</code>를 치고 스페이스를 누르면 해당 문구로 바뀝니다</sub> </td> </tr> <tr> <td width="50%" valign="top"> <a href="./docs/dashboard.md"><picture> <img alt="dashboard: 컨텍스트 게이지가 차면서 색이 바뀐다" src="./docs/images/showcase/gauge-light.gif" width="100%"> <sub>모델, 컨텍스트, 사용 한도, 브랜치를 입력창 아래 두 줄에 표시합니다. 게이지가 찰수록 색이 노란색, 주황색, 빨간색 순으로 바뀝니다</sub> </td> <td width="50%" valign="top"> <a href="./docs/key-assist.md"><picture> <img alt="key-assist: 붙여넣은 파일 이름이 @경로로 바뀐다" src="./docs/images/showcase/paste-light.gif" width="100%"> <sub>Finder에서 복사한 파일을 붙여넣으면 파일 이름이 <code>@경로</code>로 바뀝니다. Cmd+Z로 입력 내용을 되돌릴 수 있습니다</sub> </td> </tr> <tr> <td colspan="2" valign="top"> <a href="./docs/split-diff.md"><picture> <img alt="split-diff: 터미널 폭이 120칸 이상이면 좌우 diff, 미만이면 원래 세로 diff로 전환된다" src="./docs/images/showcase/split-diff-light.gif" width="100%"> <sub>터미널 폭이 120칸 이상이면 Edit와 Write 결과의 diff에서 원래 내용은 왼쪽에, 바뀐 내용은 오른쪽에 표시합니다. 바뀐 단어는 더 밝은 색으로 강조합니다</sub> </td> </tr> <tr> <td colspan="2" valign="top"> <a href="./docs/relaunch.md"><picture> <img alt="relaunch: 업데이트 알림의 다시 열기를 누르면 같은 탭에서 새 버전으로 같은 대화가 열린다" src="./docs/images/showcase/relaunch-light.gif" width="49%"> <img alt="relaunch: 입력창에 /relaunch를 치고 Enter를 누르면 같은 탭에서 새 버전으로 같은 대화가 열린다" src="./docs/images/showcase/relaunch-type-light.gif" width="49%"> <sub>새 버전이 설치되면 입력창 위에 알립니다. Orca 탭에서 <code>다시 열기</code>를 누르거나(왼쪽) <code>/relaunch</code>를 입력하면(오른쪽) Claude Code를 다시 시작하고 기존 대화를 이어서 엽니다</sub> </td> </tr> </table>

특징

  • $번호로 문구를 불러옵니다. 다음 제안과 프리셋에 각각 번호가 붙습니다. 입력창에 $2를 치고 스페이스를 누르면 2번 문구가 그 자리에 들어가고, 이어서 쓸 수 있게 뒤에 스페이스가 하나 붙습니다. 스페이스 없이 바로 Enter를 눌러도 문구로 바꿔 보냅니다. $12처럼 두 자리 번호도 쓸 수 있습니다.
  • 프리셋도 입력창에서 편집합니다. 편집 화면에서 프리셋을 추가하거나 수정할 때는 입력창에 내용을 쓰고 Enter를 누르면 됩니다.
  • 상태 표시줄 대신 입력창 아래에 대시보드를 표시합니다. 컨텍스트 사용량, 5시간과 7일 한도, Fable 한도, 모델, 브랜치를 두 줄로 확인할 수 있습니다.
  • 파일을 경로 멘션으로 붙여넣습니다. Finder에서 복사한 파일을 붙여넣으면 파일 이름 대신 @경로 멘션이 입력됩니다.
  • 넓은 터미널에서는 diff를 좌우로 나눠 표시합니다. 원래 줄과 바뀐 줄이 같은 높이에 나란히 표시됩니다.
  • 업데이트 후 기존 대화를 이어서 엽니다. 새 버전이 설치되면 입력창 위에 알립니다. Orca 탭에서는 /relaunch로 다시 시작해 기존 대화를 이어서 엽니다.
  • 따로 설치할 프로그램이나 직접 고칠 설정 파일이 없습니다. 마켓플레이스에서 필요한 모드만 골라 설치합니다.

설치

요구 사항

  • Claude Code 2.1.296 이상이 필요합니다. 기존 모드는 2.1.296~2.1.303, relaunch는 2.1.303에서 테스트했습니다. 모드 기능은 아직 공개 초기 단계라 이후 버전에서는 동작이 달라질 수 있습니다.
  • key-assist는 macOS 전용입니다. Cmd+Z를 사용하려면 Command 키 입력을 Claude Code에 전달할 수 있는 터미널이 필요합니다. Orca, Ghostty, kitty, WezTerm처럼 Kitty 키보드 프로토콜을 지원하는 터미널이 해당합니다.
  • relaunch가 자동으로 다시 열려면 Orca 터미널 탭과 orca 명령이 필요합니다. 업데이트 알림은 다른 터미널에서도 나타납니다.

마켓플레이스에서 설치

이 저장소가 oobg 마켓플레이스입니다. 먼저 Claude Code 입력창에서 마켓플레이스를 등록합니다.

/plugin marketplace add oobg/claude-code-mods

그다음 필요한 모드만 골라 설치합니다.

/plugin install next-prompts@oobg
/plugin install quick-replies@oobg
/plugin install dashboard@oobg
/plugin install key-assist@oobg
/plugin install split-diff@oobg
/plugin install relaunch@oobg

설치한 모드는 Claude Code를 다시 시작하거나 /reload-plugins를 실행하면 적용됩니다. 설치 여부는 /plugin 화면에서 확인하거나 터미널에서 claude plugin list를 실행해 확인할 수 있습니다.

Claude Code를 시작하면 quick-replies의 기본 프리셋과 dashboard가 바로 표시됩니다. next-prompts의 제안은 첫 턴이 끝난 뒤에 나타납니다.

모드 목록

모드기능위치
next-prompts턴이 끝나면 다음에 보낼 만한 요청을 최대 3개 제안합니다입력창 위
quick-replies자주 쓰는 문구를 전역 프리셋이나 저장소별 프리셋에 저장합니다입력창 위
dashboard모델, 컨텍스트, 사용 한도, 브랜치를 두 줄로 표시합니다입력창 아래
key-assist붙여넣은 파일 이름을 @경로로 바꾸고, Cmd+Z로 입력한 내용을 되돌립니다입력창
split-diff넓은 터미널에서 Edit와 Write 결과의 diff를 좌우로 나눠 표시합니다도구 결과
relaunch새 버전 설치를 알리고, Orca 탭에서 기존 대화를 이어서 다시 엽니다입력창 위, /relaunch

$번호로 문구 입력하기

next-prompts와 quick-replies를 함께 쓰면 입력창 위에 표시되는 두 목록의 번호가 이어집니다. 다음 제안은 $1부터, 프리셋은 그다음 번호부터 시작합니다.

<table class="cards"> <tr> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="입력창에 $2를 치고 스페이스를 누르면 $2가 2번 문구로 바뀐다" src="./docs/images/showcase/substitute-light.gif" width="100%"> <sub>입력창에 <code>$2</code>를 치고 스페이스를 누르면 <code>$2</code>가 2번 문구로 바뀝니다. 문장 중간에서도 사용할 수 있습니다</sub> </td> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="번호를 클릭하면 입력창 내용이 그 문구로 바뀐다" src="./docs/images/showcase/pick-light.gif" width="100%"> <sub>번호(<code>$2:</code>)를 클릭하면 입력창의 기존 내용을 모두 2번 문구로 바꿉니다</sub> </td> </tr> <tr> <td width="50%" valign="top"> <a href="./docs/next-prompts.md"><picture> <img alt="문구를 클릭하면 그 문구만 바로 보내진다" src="./docs/images/showcase/send-light.gif" width="100%"> <sub>문구를 클릭하면 해당 문구만 바로 보냅니다. 입력창에 적어 둔 내용은 그대로 남습니다</sub> </td> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="$e를 입력하면 프리셋 편집 화면이 열린다" src="./docs/images/showcase/editor-light.gif" width="100%"> <sub>입력창에 <code>$e</code>를 입력하면 프리셋 편집 화면이 열립니다</sub> </td> </tr> <tr> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="$0을 입력하면 프리셋을 한 줄로 접고 다시 입력하면 펼친다" src="./docs/images/showcase/fold-light.gif" width="100%"> <sub>입력창에 <code>$0</code>을 입력하면 프리셋을 한 줄로 접고, 다시 입력하면 펼칩니다</sub> </td> <td width="50%"></td> </tr> </table>

입력창 맨 앞이나 공백 뒤에 $와 번호를 치고 스페이스를 누르면 그 자리에서 문구로 바뀝니다. 스페이스 없이 Enter를 누르면 입력창에는 보이지 않고 보내는 내용만 바뀝니다. 입력창에서 바뀐 내용은 ctrl+_로 되돌릴 수 있습니다.

업데이트와 삭제

먼저 마켓플레이스 목록을 갱신합니다.

/plugin marketplace update oobg

그다음 /plugin 화면에서 설치한 모드를 업데이트하거나, 터미널에서 claude plugin update <모드>@oobg를 실행합니다. 업데이트한 모드는 Claude Code를 다시 시작하면 적용됩니다.

모드를 삭제하려면 다음 명령을 실행합니다.

/plugin uninstall next-prompts@oobg
/plugin uninstall quick-replies@oobg
/plugin uninstall dashboard@oobg
/plugin uninstall key-assist@oobg
/plugin uninstall split-diff@oobg
/plugin uninstall relaunch@oobg

[!NOTE] key-assist를 삭제해도 키 설정에 추가된 cmd+z 항목은 남습니다. 필요하지 않으면 ~/.claude/keybindings.json에서 직접 지웁니다.

문제 해결

모드별 자세한 해결 방법은 각 상세 문서의 "문제 해결" 절에서 확인할 수 있습니다.

상세 문서

각 모드의 상세 문서는 문서 사이트에서도 볼 수 있습니다.

문서내용
next-prompts제안을 넣고 보내고 닫는 방법, quick-replies와 함께 쓰기, 알아 둘 점
quick-replies전역 프리셋과 로컬 프리셋, 불러오기, 스킬과 슬래시 명령, 접기, 편집 화면
dashboard표시하는 항목, 모양 바꾸기, 색 바꾸기, 상태줄과 함께 쓸 때
key-assist파일 붙여넣기, Cmd+Z로 되돌리기, 알아 둘 점
split-diff좌우로 나뉘는 조건, 실제 화면, 알아 둘 점
relaunch다시 열기 버튼과 /relaunch, 알아 둘 점

라이선스

Copyright (c) 2026 oobg

이 프로젝트는 MIT 라이선스에 따라 배포됩니다.

Source 1 files
hooks/register.tsx 397 lines
1import type { EngineInterface, Register, RenderInputOf } from 'claude-code'
2
3// 이 너비(칸)부터 좌우로 나눈다. 좁으면 엔진의 원래 diff를 그린다.
4export const MIN_COLUMNS = 120
5
6// 결과 블록 본문의 들여쓰기. 엔진의 diff처럼 `⎿` 표시 아래로 맞춘다.
7const INDENT = 4
8
9// Bash 결과에서 파일 하나에 그리는 최대 줄 수. 스크립트가 큰 파일을 만들어도 화면을 덮지 않게 나머지는 줄여 표시한다.
10export const BASH_MAX_ROWS = 40
11
12type Hunk = { oldStart: number; oldLines: number; newStart: number; newLines: number; lines: string[] }
13type FilePatch = { filePath: string; hunks: Hunk[]; kind: 'update' | 'create' | 'delete' }
14type Side = { no: number; text: string; kind: 'ctx' | 'del' | 'add' }
15export type Row = { kind: 'line'; left?: Side; right?: Side; spans?: { del: [number, number][]; add: [number, number][] } } | { kind: 'gap' }
16
17// 구간(hunk)들을 좌우 줄로 펼친다. 연달아 지운 줄과 추가한 줄은 순서대로 짝지어 같은 높이에 둔다.
18export function toRows(hunks: Hunk[]): Row[] {
19  const rows: Row[] = []
20  hunks.forEach((hunk, h) => {
21    if (h > 0) {
22      rows.push({ kind: 'gap' })
23    }
24    let oldNo = hunk.oldStart
25    let newNo = hunk.newStart
26    let dels: Side[] = []
27    let adds: Side[] = []
28    const flush = () => {
29      for (let i = 0; i < Math.max(dels.length, adds.length); i++) {
30        const left = dels[i]
31        const right = adds[i]
32        rows.push({ kind: 'line', left, right, spans: left && right ? changedSpans(left.text, right.text) : undefined })
33      }
34      dels = []
35      adds = []
36    }
37    for (const line of hunk.lines) {
38      const mark = line[0]
39      const text = line.slice(1)
40      if (mark === '-') {
41        dels.push({ no: oldNo++, text, kind: 'del' })
42      } else if (mark === '+') {
43        adds.push({ no: newNo++, text, kind: 'add' })
44      } else if (mark === ' ') {
45        flush()
46        rows.push({ kind: 'line', left: { no: oldNo++, text, kind: 'ctx' }, right: { no: newNo++, text, kind: 'ctx' } })
47      }
48      // `\ No newline at end of file` 같은 줄은 건너뛴다.
49    }
50    flush()
51  })
52  return rows
53}
54
55// 터미널 칸 폭. 한글, 한자, 전각 문자는 두 칸을 차지한다.
56export function cellWidth(ch: string): number {
57  const c = ch.codePointAt(0) ?? 0
58  return (c >= 0x1100 && c <= 0x115f) ||
59    (c >= 0x2e80 && c <= 0xa4cf) ||
60    (c >= 0xac00 && c <= 0xd7a3) ||
61    (c >= 0xf900 && c <= 0xfaff) ||
62    (c >= 0xfe30 && c <= 0xfe4f) ||
63    (c >= 0xff00 && c <= 0xff60) ||
64    (c >= 0xffe0 && c <= 0xffe6) ||
65    (c >= 0x1f300 && c <= 0x1faff) ||
66    (c >= 0x20000 && c <= 0x3fffd)
67    ? 2
68    : 1
69}
70
71// 두 줄을 단어, 공백, 기호 단위로 나눠 비교하고 바뀐 구간을 글자 위치 [시작, 끝)으로 돌려준다.
72// 바뀐 부분이 너무 많으면 줄 전체가 바뀐 것과 다르지 않으므로 강조하지 않는다.
73export function changedSpans(before: string, after: string): { del: [number, number][]; add: [number, number][] } {
74  const split = (t: string) => t.match(/\w+|\s+|[^\w\s]/gu) ?? []
75  const a = split(before)
76  const b = split(after)
77  const lcs: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0))
78  for (let i = a.length - 1; i >= 0; i--) {
79    for (let j = b.length - 1; j >= 0; j--) {
80      lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!)
81    }
82  }
83  const del: [number, number][] = []
84  const add: [number, number][] = []
85  const push = (spans: [number, number][], from: number, to: number) => {
86    const last = spans[spans.length - 1]
87    if (last !== undefined && last[1] === from) last[1] = to
88    else spans.push([from, to])
89  }
90  let i = 0
91  let j = 0
92  let at = 0
93  let bt = 0
94  let same = 0
95  while (i < a.length || j < b.length) {
96    if (i < a.length && j < b.length && a[i] === b[j]) {
97      same += a[i]!.trim().length
98      at += a[i++]!.length
99      bt += b[j++]!.length
100    } else if (j < b.length && (i >= a.length || lcs[i]![j + 1]! >= lcs[i + 1]![j]!)) {
101      push(add, bt, bt + b[j]!.length)
102      bt += b[j++]!.length
103    } else {
104      push(del, at, at + a[i]!.length)
105      at += a[i++]!.length
106    }
107  }
108  const total = Math.max(before.trim().length, after.trim().length)
109  if (total === 0 || same / total < 0.4) {
110    return { del: [], add: [] }
111  }
112  return { del, add }
113}
114
115// 글자 구간을 칸 위치로 바꾼다. 엔진의 Code는 내용 칸 너비(width)에서 글자 단위로 줄을 바꾼다.
116// 결과는 행마다 { row, col, text } 조각이다.
117export function placeSpans(text: string, spans: [number, number][], width: number): { row: number; col: number; text: string }[] {
118  const pieces: { row: number; col: number; text: string }[] = []
119  let row = 0
120  let col = 0
121  let index = 0
122  for (const ch of text) {
123    const w = cellWidth(ch)
124    if (col + w > width) {
125      row++
126      col = 0
127    }
128    const inside = spans.some(([from, to]) => index >= from && index < to)
129    if (inside) {
130      const last = pieces[pieces.length - 1]
131      if (last !== undefined && last.row === row && last.col + widthOf(last.text) === col) last.text += ch
132      else pieces.push({ row, col, text: ch })
133    }
134    col += w
135    index += ch.length
136  }
137  return pieces
138}
139
140function widthOf(text: string): number {
141  let w = 0
142  for (const ch of text) w += cellWidth(ch)
143  return w
144}
145
146export function counts(hunks: Hunk[]): { added: number; removed: number } {
147  let added = 0
148  let removed = 0
149  for (const hunk of hunks) {
150    for (const line of hunk.lines) {
151      if (line[0] === '+') added++
152      else if (line[0] === '-') removed++
153    }
154  }
155  return { added, removed }
156}
157
158function relative(path: string, cwd: string): string {
159  return path.startsWith(cwd + '/') ? path.slice(cwd.length + 1) : path
160}
161
162// Edit 결과, 그리고 기존 파일을 덮어쓴 Write 결과만 다룬다.
163function patchOf(tool: string, output: unknown): FilePatch | undefined {
164  if (tool !== 'Edit' && tool !== 'Write') {
165    return undefined
166  }
167  const out = output as { filePath?: unknown; structuredPatch?: unknown; type?: unknown } | null
168  if (!out || typeof out.filePath !== 'string' || !Array.isArray(out.structuredPatch) || out.structuredPatch.length === 0) {
169    return undefined
170  }
171  if (tool === 'Write' && out.type !== 'update') {
172    return undefined
173  }
174  return { filePath: out.filePath, hunks: out.structuredPatch as Hunk[], kind: 'update' }
175}
176
177function isCount(value: unknown): value is number {
178  return typeof value === 'number' && Number.isInteger(value) && value >= 0
179}
180
181// 구간 하나가 모양도 맞고, 머리의 줄 수가 실제 줄과도 맞는지 본다. 줄 번호가 어긋난 diff는 그리지 않는다.
182function isHunk(value: unknown): value is Hunk {
183  const h = value as Partial<Record<keyof Hunk, unknown>> | null
184  if (!h || typeof h !== 'object' || !isCount(h.oldStart) || !isCount(h.oldLines) || !isCount(h.newStart) || !isCount(h.newLines) || !Array.isArray(h.lines)) {
185    return false
186  }
187  let old = 0
188  let now = 0
189  for (const line of h.lines) {
190    if (typeof line !== 'string') return false
191    const mark = line[0]
192    if (mark === ' ') {
193      old++
194      now++
195    } else if (mark === '-') old++
196    else if (mark === '+') now++
197    else if (mark !== '\\') return false
198  }
199  return old === h.oldLines && now === h.newLines
200}
201
202// Bash 명령이 바꾼 파일들의 diff(`bashEditDiff`)를 읽는다. 엔진 내부 필드라 모양이 바뀔 수 있으므로,
203// 하나라도 예상과 다르거나 엔진이 diff를 다 갖지 못했다고 표시하면 통째로 엔진에 맡긴다.
204export function bashPatches(output: unknown): { files: FilePatch[]; moreFiles: number } | undefined {
205  const diff = (output as { bashEditDiff?: unknown } | null)?.bashEditDiff as
206    | { files?: unknown; moreFiles?: unknown; unavailable?: unknown; skipped?: unknown; shared?: unknown }
207    | null
208    | undefined
209  if (!diff || typeof diff !== 'object' || diff.unavailable || diff.skipped || diff.shared) {
210    return undefined
211  }
212  if (!Array.isArray(diff.files) || diff.files.length === 0 || !isCount(diff.moreFiles)) {
213    return undefined
214  }
215  const files: FilePatch[] = []
216  for (const file of diff.files as unknown[]) {
217    const f = file as { filePath?: unknown; hunks?: unknown; created?: unknown; deleted?: unknown } | null
218    if (!f || typeof f.filePath !== 'string' || f.filePath === '' || !Array.isArray(f.hunks) || !f.hunks.every(isHunk)) {
219      return undefined
220    }
221    if ((f.created !== undefined && f.created !== true) || (f.deleted !== undefined && f.deleted !== true) || (f.created && f.deleted)) {
222      return undefined
223    }
224    files.push({ filePath: f.filePath, hunks: f.hunks, kind: f.created ? 'create' : f.deleted ? 'delete' : 'update' })
225  }
226  return { files, moreFiles: diff.moreFiles }
227}
228
229export const register: Register = on => {
230  on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
231    const columns = e.viewport?.columns
232    if (e.surface !== 'terminal' || e.props.isErrored || columns === undefined || columns < MIN_COLUMNS) {
233      return next(e)
234    }
235    const patch = patchOf(e.props.tool, e.props.output)
236    if (patch !== undefined) {
237      return drawEdit($, e, patch, columns)
238    }
239    const bash = e.props.tool === 'Bash' ? bashPatches(e.props.output) : undefined
240    if (bash !== undefined) {
241      // 명령 출력은 엔진이 그리게 하고, 엔진의 diff만 빼서 그 자리에 좌우 diff를 붙인다.
242      const { bashEditDiff: _, ...rest } = e.props.output as Record<string, unknown>
243      const above = await next({ ...e, props: { ...e.props, output: rest } })
244      return drawBash($, e, above, bash, columns)
245    }
246    return next(e)
247  })
248}
249
250type Input = RenderInputOf<'ToolResult', 'terminal'>
251
252async function drawEdit($: EngineInterface, e: Input, patch: FilePatch, columns: number) {
253  const { Box } = $.ui.resolve(e)
254  const cwd = await $.session.cwd()
255  return (
256    <Box flexDirection="column">
257      {heading($, e, patch, cwd, true)}
258      {sideBySide($, e, patch, columns, Infinity)}
259    </Box>
260  )
261}
262
263async function drawBash($: EngineInterface, e: Input, above: unknown, bash: { files: FilePatch[]; moreFiles: number }, columns: number) {
264  const { Box } = $.ui.resolve(e)
265  const cwd = await $.session.cwd()
266  return (
267    <Box flexDirection="column">
268      {above as never}
269      {summary($, e, bash, cwd)}
270      {bash.files.map((patch, i) => (
271        <Box key={`file:${i}`} flexDirection="column">
272          {heading($, e, patch, cwd, false)}
273          {sideBySide($, e, patch, columns, BASH_MAX_ROWS)}
274        </Box>
275      ))}
276    </Box>
277  )
278}
279
280// 경로 칸은 가장 긴 경로에 맞추되, 이보다 긴 경로가 있어도 이 너비(칸)까지만 맞춘다.
281const SUMMARY_PATH_MAX = 60
282
283// 명령 하나가 파일을 둘 이상 바꿨으면 diff 위에 바뀐 파일 목록을 붙인다. 엔진이 diff를 넘기지 않은 파일은 개수만 적는다.
284function summary($: EngineInterface, e: Input, bash: { files: FilePatch[]; moreFiles: number }, cwd: string) {
285  const { Box, Text } = $.ui.resolve(e)
286  const total = bash.files.length + bash.moreFiles
287  if (total < 2) {
288    return null
289  }
290  const items = bash.files.map(patch => ({ patch, path: relative(patch.filePath, cwd), ...counts(patch.hunks) }))
291  const pathWidth = Math.min(SUMMARY_PATH_MAX, Math.max(...items.map(item => widthOf(item.path))))
292  const addWidth = Math.max(...items.map(item => (item.added > 0 ? `+${item.added}`.length : 0)))
293  const pad = ' '.repeat(INDENT)
294  const branch = (i: number) => (i === items.length - 1 && bash.moreFiles === 0 ? '└ ' : '├ ')
295  return (
296    <Box flexDirection="column">
297      <Text dimColor>{`${pad}${total} files changed`}</Text>
298      {items.map((item, i) => (
299        <Text key={`sum:${i}`}>
300          <Text dimColor>{pad + branch(i)}</Text>
301          {item.path + ' '.repeat(Math.max(0, pathWidth - widthOf(item.path)) + 2)}
302          <Text color="success">{(item.added > 0 ? `+${item.added}` : '').padEnd(addWidth)}</Text>
303          {item.removed > 0 ? <Text color="error">{` -${item.removed}`}</Text> : null}
304          {item.patch.kind === 'update' ? null : <Text dimColor>{item.patch.kind === 'create' ? '  (new)' : '  (deleted)'}</Text>}
305        </Text>
306      ))}
307      {bash.moreFiles > 0 ? <Text dimColor>{`${pad}└ … ${bash.moreFiles} more ${bash.moreFiles === 1 ? 'file' : 'files'}`}</Text> : null}
308    </Box>
309  )
310}
311
312function heading($: EngineInterface, e: Input, patch: FilePatch, cwd: string, arrow: boolean) {
313  const { Text } = $.ui.resolve(e)
314  const { added, removed } = counts(patch.hunks)
315  const verb = patch.kind === 'create' ? 'Created' : patch.kind === 'delete' ? 'Deleted' : 'Updated'
316  return (
317    <Text>
318      <Text dimColor>{arrow ? '  ⎿ ' : ' '.repeat(INDENT)}</Text>
319      {verb} <Text bold>{relative(patch.filePath, cwd)}</Text> <Text dimColor>{`(+${added} -${removed})`}</Text>
320    </Text>
321  )
322}
323
324// 새로 만든 파일은 왼쪽이, 지운 파일은 오른쪽이 빈 채로 그려진다. limit 줄을 넘으면 나머지는 줄 수만 적는다.
325function sideBySide($: EngineInterface, e: Input, patch: FilePatch, columns: number, limit: number) {
326  const { Box, Text, Code } = $.ui.resolve(e)
327  const all = toRows(patch.hunks)
328  const rows = all.slice(0, limit)
329  while (rows[rows.length - 1]?.kind === 'gap') rows.pop()
330  const hidden = all.slice(rows.length).filter(row => row.kind === 'line').length
331
332  // 들여쓰기와 가운데 구분선(" │ ") 몫을 빼고 반씩 나눈다.
333  const half = Math.floor((columns - INDENT - 3) / 2)
334  const lastNo = Math.max(1, ...patch.hunks.map(h => Math.max(h.oldStart + h.oldLines, h.newStart + h.newLines)))
335  const gutter = String(lastNo).length
336
337  // 칸마다 한 줄짜리 diff 구간을 만들어 엔진의 Code(diff 형식)에 맡긴다.
338  // 그러면 줄 번호, 표시, 배경색, 문법 색이 엔진의 diff와 똑같이 칠해진다.
339  const hunkLine = (side: Side) => {
340    const head =
341      side.kind === 'del' ? `@@ -${side.no},1 +${side.no},0 @@` : side.kind === 'add' ? `@@ -${side.no},0 +${side.no},1 @@` : `@@ -${side.no},1 +${side.no},1 @@`
342    const mark = side.kind === 'del' ? '-' : side.kind === 'add' ? '+' : ' '
343    return `${head}\n${mark}${side.text}`
344  }
345
346  // 바뀐 단어는 엔진의 단어 강조보다 눈에 띄도록, 엔진이 그린 줄 위의 같은 자리에 같은 글자를 밝은 배경으로 덮어 그린다.
347  // 엔진 diff 한 줄은 `빈칸, 줄 번호, 빈칸, 표시` 다음에 내용이 오고, 줄바꿈된 줄도 같은 열에서 이어진다.
348  const contentWidth = half - gutter - 3
349  const cell = (side: Side | undefined, spans: [number, number][], key: string) => {
350    if (side === undefined) {
351      return <Box key={key} width={half} />
352    }
353    const offset = String(side.no).length + 3
354    // 탭은 엔진이 몇 칸으로 그리는지 알 수 없어 강조를 건너뛴다.
355    const pieces = spans.length === 0 || side.text.includes('\t') ? [] : placeSpans(side.text, spans, contentWidth)
356    const color = side.kind === 'del' ? 'diffRemovedWord' : 'diffAddedWord'
357    // 엔진은 칸마다 줄 번호 폭을 그 칸의 번호에 맞춘다. 짧은 번호 앞을 비워 끝자리를 맞추면 내용 열도 맞는다.
358    return (
359      <Box key={key} width={half} paddingLeft={gutter - String(side.no).length}>
360        <Box position="relative" flexGrow={1}>
361          <Code source={hunkLine(side)} path={patch.filePath} format="diff" wrap="wrap" />
362          {pieces.map((piece, i) => (
363            <Box key={`hl:${i}`} position="absolute" top={piece.row} left={offset + piece.col}>
364              <Text backgroundColor={color} color="text" bold>
365                {piece.text}
366              </Text>
367            </Box>
368          ))}
369        </Box>
370      </Box>
371    )
372  }
373
374  return (
375    <Box flexDirection="column" paddingLeft={INDENT}>
376      {rows.map((row, i) =>
377        row.kind === 'gap' ? (
378          <Text key={`gap:${i}`} dimColor>
379            {' '.repeat(gutter)}...
380          </Text>
381        ) : (
382          <Box key={`row:${i}`} flexDirection="row">
383            {cell(row.left, row.spans?.del ?? [], 'left')}
384            <Text dimColor> │ </Text>
385            {cell(row.right, row.spans?.add ?? [], 'right')}
386          </Box>
387        ),
388      )}
389      {hidden > 0 ? (
390        <Text dimColor>
391          {' '.repeat(gutter)}… {hidden} more {hidden === 1 ? 'line' : 'lines'}
392        </Text>
393      ) : null}
394    </Box>
395  )
396}
397