Orca のペインを上下に分割してエディタでプロンプトを書く

Claude Code の mod(画面や動きを変える hooks プラグイン)を置くリポジトリです。リポジトリ全体がプラグインのマーケットプレイスになっているので、mod ごとに 1 行で入れられます。
| mod | できること | 前提 |
|---|---|---|
| orca-split-editor | Ctrl+G か /edit で Orca のペインを上下に分割し、下側のエディタでプロンプトを書く。保存して閉じると書いた文がプロンプト欄に入る。[Pasted text #N] に折りたたまれた最後の貼り付けは、クリップボードと行数が合えば戻して開く | Orca 上の Claude Code、$VISUAL か $EDITOR |
Claude Code のプロンプト欄で次の 1 行を入力します。
/plugin install orca-split-editor --marketplace Kyo1M/claude-mods
マーケットプレイスの追加を聞かれたら y を押し、スコープは user を選びます。
対話なしで入れるとき(セットアップを Claude に任せるとき等)は、ターミナルで次の 2 行を実行します。
claude plugin marketplace add Kyo1M/claude-mods
claude plugin install orca-split-editor@claude-mods --scope user
更新は claude plugin marketplace update claude-mods → claude plugin update orca-split-editor@claude-mods → Claude Code で /reload-plugins です。
mod は本体の Ctrl+G(外部エディタ)を横取りできないため、~/.claude/keybindings.json で Ctrl+G を本体から外し、mod に回します。標準の外部エディタは既定の Ctrl+X Ctrl+E で引き続き使えます。
{
"$schema": "https://www.schemastore.org/claude-code-keybindings.json",
"$docs": "https://code.claude.com/docs/en/keybindings",
"bindings": [
{ "context": "Chat", "bindings": { "ctrl+g": null } },
{ "context": "Global", "bindings": { "ctrl+g": "app:toggleReplTab" } }
]
}
app:toggleReplTab は、プロンプト欄の上の帯にある mod のボタンを Ctrl+G で押すための割り当てです。キー割り当てを変えなくても /edit で使えます。
このリポジトリのフォルダをマーケットプレイスとして登録すると、インストールした mod はこのフォルダから直接読み込まれます。
claude plugin marketplace add ~/Developer/claude-mods
claude plugin install orca-split-editor@claude-mods --scope user
ファイルを直したら、Claude Code で /reload-plugins を実行すると反映されます。GitHub から入れている環境に届けるときは、<mod 名>/.claude-plugin/plugin.json の version を上げてから push します(入れた側は版の番号で入れ替わるため)。
確認は mod ごとに次の 2 つで行います。
claude plugin validate orca-split-editor
claude plugin test orca-split-editor
新しい mod は <mod 名>/ にフォルダを作り、.claude-plugin/marketplace.json の plugins とこの README の一覧に追記します。設計書は docs/superpowers/specs/ に置きます。
hooks/register.tsx 102 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Editing } from '../types'
5import { readHostEnv, startEdit } from './editor'
6import type { Deps } from './editor'
7
8const editing = atom({ plugin: 'orca-split-editor', key: 'editing' } as const, null as Editing | null)
9const inOrca = atom({ plugin: 'orca-split-editor', key: 'inOrca' } as const, false)
10const editor = atom({ plugin: 'orca-split-editor', key: 'editor' } as const, 'vi')
11
12// keybindings.json で Global の ctrl+g をこの action に割り当てる。
13// 本体の処理が常駐しない action なので、帯の Button が Ctrl+G で押される。
14const KEY_ACTION = 'app:toggleReplTab'
15
16function depsOf($: EngineInterface): Deps {
17 return {
18 run: argv => $.process.run(argv),
19 runLong: async argv => {
20 // $.process.run は最長 10 分で切れるので spawn で読み切る
21 const stream = $.process.spawn({ argv })
22 let stdout = ''
23 let stderr = ''
24 for await (const chunk of stream) {
25 if (chunk.stream === 'stdout') stdout += chunk.text
26 else stderr += chunk.text
27 }
28 const { code } = await stream.result
29 return { exitCode: code ?? 1, stdout, stderr }
30 },
31 readPrompt: async () => (await $.prompt.read()).text,
32 readClipboard: async () => {
33 // ロケールが UTF-8 でないと pbpaste は日本語を化けさせる
34 const r = await $.process.run(['/usr/bin/pbpaste'], {
35 env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' },
36 timeoutMs: 5_000,
37 })
38 // 途中で切れた中身は行数が合っても戻さない
39 if (r.exitCode !== 0 || r.isStdoutTruncated) throw new Error('pbpaste')
40 return r.stdout
41 },
42 fillPrompt: async text => (await $.prompt.fill({ text, mode: 'replace' })).isFilled,
43 readFile: async path => String(await $.fs.read(path)),
44 writeFile: (path, text) => $.fs.write(path, text),
45 now: () => $.clock.now(),
46 toast: text => $.ui.toast(text),
47 getEditing: () => read($, editing),
48 setEditing: async value => {
49 await update($, editing, () => value)
50 },
51 }
52}
53
54function launch($: EngineInterface): void {
55 void startEdit(depsOf($)).catch(error => $.ui.toast(`エディタを開けませんでした: ${String(error)}`))
56}
57
58export const register: Register = on => {
59 on('session.start', async ($, e, next) => {
60 // 読み直しで待ちの処理は切れるので、編集中の印を消しておく
61 await update($, editing, () => null)
62 const env = await readHostEnv(argv => $.process.run(argv))
63 await update($, inOrca, () => env.handle !== null)
64 await update($, editor, () => env.editor)
65 await $.command.register({
66 name: 'edit',
67 description: 'Orca を上下に分割し、エディタでプロンプトを書く',
68 })
69 return next(e)
70 })
71
72 on('command.run', { command: 'edit' }, $ => {
73 launch($)
74 return {}
75 })
76
77 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
78 if (e.props.hasSurvey || !(await read($, inOrca))) return next(e)
79
80 const { Box, Button, Text } = $.ui.resolve(e)
81 const name = (await read($, editor)).split(' ')[0]?.split('/').pop() ?? 'editor'
82 const isEditing = (await read($, editing)) !== null
83
84 // 待機中のボタンは隠す。Ctrl+G で押すために描画には残す
85 return (
86 <Box>
87 <Box display={isEditing ? 'flex' : 'none'}>
88 <Button
89 key="edit"
90 label="Ctrl+G: 編集中のペインへ"
91 action={KEY_ACTION}
92 plain
93 dimColor
94 onPress={() => launch($)}
95 />
96 <Text dimColor> {name} で編集中(保存して閉じるとプロンプト欄に入ります)</Text>
97 </Box>
98 </Box>
99 )
100 })
101}
102hooks/editor.ts 186 lines1import type { Editing } from '../types'
2
3export const ORCA = '/Applications/Orca.app/Contents/Resources/bin/orca'
4export const DRAFT_DIR = '/tmp/claude-orca-split-editor'
5
6export type RunResult = { exitCode: number; stdout: string; stderr: string }
7
8/** 外の世界との接点。register.tsx が $ でつなぎ、テストは差し替える */
9export type Deps = {
10 run: (argv: readonly string[]) => Promise<RunResult>
11 /** run と同じだが時間制限なし(エディタの終了待ちに使う) */
12 runLong: (argv: readonly string[]) => Promise<RunResult>
13 readPrompt: () => Promise<string>
14 readClipboard: () => Promise<string>
15 /** 入れられたら true */
16 fillPrompt: (text: string) => Promise<boolean>
17 readFile: (path: string) => Promise<string>
18 writeFile: (path: string, text: string) => Promise<void>
19 now: () => Promise<number>
20 toast: (text: string) => void
21 getEditing: () => Promise<Editing | null>
22 setEditing: (editing: Editing | null) => Promise<void>
23}
24
25export type HostEnv = { handle: string | null; editor: string }
26
27/** `env` の出力から Orca のハンドルとエディタを読む */
28export async function readHostEnv(run: Deps['run']): Promise<HostEnv> {
29 const { stdout } = await run(['/usr/bin/env'])
30 const vars = new Map<string, string>()
31 for (const line of stdout.split('\n')) {
32 const at = line.indexOf('=')
33 if (at > 0) vars.set(line.slice(0, at), line.slice(at + 1))
34 }
35 return {
36 handle: vars.get('ORCA_TERMINAL_HANDLE') || null,
37 editor: vars.get('VISUAL') || vars.get('EDITOR') || 'vi',
38 }
39}
40
41/** 1 回の待ちの上限。切れたら待ち直す */
42export const WAIT_SLICE_MS = 600_000
43
44/** エディタが終わるまで待つ。終了を確認できたら true、確認できない失敗なら false */
45export async function waitForEditor(deps: Deps, handle: string): Promise<boolean> {
46 for (;;) {
47 const r = await deps.runLong([
48 ORCA, 'terminal', 'wait', '--terminal', handle,
49 '--for', 'exit', '--timeout-ms', String(WAIT_SLICE_MS), '--json',
50 ])
51 let json: any
52 try {
53 json = JSON.parse(r.stdout)
54 } catch {
55 return false
56 }
57 if (json?.ok === true && json.result?.wait?.satisfied === true) return true
58 const isTimeout =
59 (json?.ok === false && json.error?.code === 'timeout') ||
60 (json?.ok === true && json.result?.wait?.satisfied === false)
61 if (!isTimeout) return false
62 }
63}
64
65/** 本体が長い貼り付けを折りたたんだ印。中身は mod から読めない */
66const PASTE_MARK = /\[Pasted text #(\d+)(?: \+(\d+) lines)?\]/g
67
68/** 本体はこの長さを超えるか、3 行以上の貼り付けを折りたたむ */
69const PASTE_FOLD_CHARS = 800
70const ANSI_ESCAPE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]/g
71
72/** 本体の貼り付け処理と同じく、色などの制御文字を除き、改行を \n に、タブを空白 4 つにそろえる */
73export function normalizePaste(text: string): string {
74 return text.replace(ANSI_ESCAPE, '').replace(/\r\n|\r/g, '\n').replaceAll('\t', ' ')
75}
76
77export type Expanded = {
78 text: string
79 /** 最後の貼り付けがクリップボードと合わず、戻せなかったか */
80 isMismatched: boolean
81 /** 戻す対象にならない、それより前の貼り付けの数 */
82 older: number
83}
84
85/**
86 * 折りたたまれた貼り付けのうち最後のもの(番号が最大)を、クリップボードの中身に戻す。
87 * 貼り付けた後に別のものをコピーしていることがあるので、行数が印と合い、
88 * 本体が折りたたむ大きさのときだけ戻す。
89 */
90export function expandPaste(draft: string, clipboard: string): Expanded {
91 const marks = [...draft.matchAll(PASTE_MARK)]
92 const last = marks.reduce<RegExpMatchArray | undefined>(
93 (a, b) => (a && Number(a[1]) > Number(b[1]) ? a : b),
94 undefined,
95 )
96 if (!last) return { text: draft, isMismatched: false, older: 0 }
97 const older = marks.length - 1
98 const content = normalizePaste(clipboard)
99 const lines = content.match(/\n/g)?.length ?? 0
100 const isFoldable = lines > 2 || content.length > PASTE_FOLD_CHARS
101 if (!isFoldable || lines !== Number(last[2] ?? 0)) return { text: draft, isMismatched: true, older }
102 const at = last.index!
103 return {
104 text: draft.slice(0, at) + content + draft.slice(at + last[0].length),
105 isMismatched: false,
106 older,
107 }
108}
109
110function firstLine(r: RunResult): string {
111 return (r.stderr.trim() || r.stdout.trim()).split('\n')[0] ?? ''
112}
113
114/**
115 * 今の下書きを一時ファイルに書き、Orca を上下に分割してエディタで開く。
116 * エディタが閉じたら分割ペインを閉じ、ファイルの中身でプロンプト欄を置き換える。
117 */
118export async function startEdit(deps: Deps): Promise<void> {
119 const current = await deps.getEditing()
120 if (current) {
121 deps.toast('すでに編集中です')
122 await deps.run([ORCA, 'terminal', 'focus', '--terminal', current.handle, '--json'])
123 return
124 }
125
126 const env = await readHostEnv(deps.run)
127 if (!env.handle) {
128 deps.toast('Orca の外では使えません(Ctrl+X Ctrl+E で標準の外部エディタ)')
129 return
130 }
131
132 let draft = await deps.readPrompt()
133 if (draft.includes('[Pasted text #')) {
134 const expanded = expandPaste(draft, await deps.readClipboard().catch(() => ''))
135 draft = expanded.text
136 const notes = [
137 expanded.isMismatched ? '最後の貼り付けはクリップボードと合わない' : '',
138 expanded.older > 0 ? `前の貼り付け ${expanded.older} 件は戻せない` : '',
139 ].filter(Boolean)
140 if (notes.length > 0) deps.toast(`${notes.join('・')}ため、折りたたんだまま開きます`)
141 }
142 const file = `${DRAFT_DIR}/draft-${await deps.now()}.md`
143 await deps.writeFile(file, draft)
144
145 const split = await deps.run([
146 ORCA, 'terminal', 'split',
147 '--terminal', env.handle,
148 '--direction', 'horizontal',
149 '--command', `exec ${env.editor} ${file}`,
150 '--json',
151 ])
152 let handle: string | undefined
153 try {
154 handle = JSON.parse(split.stdout)?.result?.split?.handle
155 } catch {
156 handle = undefined
157 }
158 if (split.exitCode !== 0 || !handle) {
159 deps.toast(`分割できませんでした: ${firstLine(split)}`)
160 return
161 }
162
163 await deps.setEditing({ handle, file })
164 try {
165 if (!(await waitForEditor(deps, handle))) {
166 // 書きかけを失わないよう、ペインは閉じず取り込みもしない
167 deps.toast(`エディタの終了を確認できませんでした。下書き: ${file}`)
168 return
169 }
170 await deps.run([ORCA, 'terminal', 'close', '--terminal', handle, '--json']).catch(() => undefined)
171 await deps.run([ORCA, 'terminal', 'focus', '--terminal', env.handle, '--json']).catch(() => undefined)
172
173 let text: string
174 try {
175 text = await deps.readFile(file)
176 } catch {
177 deps.toast(`下書きを読めませんでした: ${file}`)
178 return
179 }
180 const isFilled = await deps.fillPrompt(text.replace(/\n$/, ''))
181 if (!isFilled) deps.toast(`プロンプト欄に入れられませんでした: ${file}`)
182 } finally {
183 await deps.setEditing(null)
184 }
185}
186types/index.d.ts 16 lines1/** 分割ペインで編集中の下書き */
2export type Editing = { handle: string; file: string }
3
4declare module 'claude-code' {
5 interface PluginState {
6 'orca-split-editor': {
7 /** 編集中なら分割ペインのハンドルと一時ファイル、待機中は null */
8 editing: Editing | null
9 /** Orca の中で動いているか(帯を出すかどうか) */
10 inOrca: boolean
11 /** 開くエディタのコマンド($VISUAL → $EDITOR → vi) */
12 editor: string
13 }
14 }
15}
16