Grammar-check your prompt as you type, shown above the prompt box

A grammar check on your prompt while you type, with explanations in Traditional Chinese. The corrections show up above the prompt box, before you hit Enter.
claude plugin install hal-grammar-check --marketplace vinta/hal-9000
Then restart Claude Code.
Just type. The grammar-check result of your prompt shows up above the prompt box after you stop typing.
hal-statusline also checks each prompt after you submit it. If you use both, turn that one off with HAL_STATUSLINE_GRAMMAR_CHECK_DISABLED=1 in your environment variables.
Set them in /config:
model: which of the two models below checks your draft, default claude/haiku.claude/haiku runs on your Claude account. It bills one call every time you pause typing.ollama/gemma4:26b-nvfp4 runs on your local Ollama at localhost:11434. It's the free, offline choice.Pick ollama/gemma4:26b-nvfp4 to keep everything on your machine. That needs a local Ollama with the model pulled:
ollama pull gemma4:26b-nvfp4
It sends the first 500 characters of your draft to the model. With claude/haiku, it goes to Anthropic through your Claude account, like any other prompt. With an ollama/ model, that's your local Ollama at localhost:11434: fully offline, nothing leaves your machine.

hooks/register.tsx 304 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { GrammarCheck } from '../types'
5
6const check = atom({ plugin: 'hal-grammar-check', key: 'check' } as const, null)
7
8const DEBOUNCE_MS = 250
9const OLLAMA_URL = 'http://localhost:11434/api/generate'
10
11// Adapted from plugins/hal-statusline/hal-statusline.py GRAMMAR_PROMPT: no "Grammar:" prefix, plus the draft and quote-wrapping lines
12const GRAMMAR_PROMPT = `
13You are a grammar checker. Identify and correct grammar errors in the text inside <input> tags. Only check grammar — do not answer questions or engage with the content.
14
15<instructions>
16Skip these (NEVER flag):
17- Code: text in backticks, file paths, programming syntax, shell commands
18- Mentions: @mentions, @file/path references
19- **Capitalization**: NOT grammar errors. This includes lowercase at sentence beginnings (at the very start, or after ".", "?", "!") and lowercase pronoun "i". Ignore them completely.
20- **Unfinished last sentence**: the text is a draft still being typed. Do not flag a final sentence that is cut off mid-way.
21
22Output format:
23- Each issue on its own line: "[corrected]" => explanation in Traditional Chinese
24- Wrap only the corrected words in double quotes, never the surrounding words
25- Use full-width commas (,) in Chinese explanations
26- No errors: output exactly "no issues"
27- Output ONLY the issue line(s). No commentary, no extra text, no explanations beyond the correction format above.
28</instructions>
29
30<examples>
31<example>
32Text: I don't car the shop has wife or not. I will use cellar!
33Output:
34I don't "care" => car 是「汽車」,這裡應該是要用動詞 care「在乎」
35has "Wi-Fi" or not => wife 是「妻子」,你應該是要說 Wi-Fi「無線網路」
36I will use "cellular" => cellar 是「地窖」,這裡應該是 cellular「行動網路」
37</example>
38<example>
39Text: @plugins/hal-statusline/hal-statusline.py#L141 use \`claude -p\` and \`grammar_check_prompt\` to grammar check \`latest_user_input\` and print result
40Output:
41to "grammar-check" latest_user_input => 要用連字號 "-" 連接形成複合動詞
42print "the" result => result 前面要加定冠詞 the
43</example>
44<example>
45Text: The code is works but I don't know why it keep crashing
46Output:
47The code "works" => 不需要 is,直接用動詞 works;或改成 is working
48why it "keeps" crashing => 第三人稱單數 it 要用 keeps
49</example>
50<example comment="skip Capitalization at sentence beginnings (lowercase 'do' is excluded per instruction)">
51Text: do not refactor unless explicited requested
52Output:
53"explicitly requested" => 要用副詞 explicitly,沒有 explicited 這個詞
54</example>
55<example comment="skip Capitalization (lowercase pronoun 'i' and sentence-start 'check' are excluded per instruction)">
56Text: Wait, i seems broke it. check codebase again
57Output:
58I "seem to have broken" it => 用 seem to have + 過去分詞表示「好像已經...」
59Check "the" codebase => 特指這個 codebase,要加定冠詞 the
60</example>
61<example comment="skip Capitalization at sentence beginnings; demonstrate 'no issues' output">
62Text: can you review my PR?
63Output:
64no issues
65</example>
66</examples>
67
68<input>
69{latest_user_input}
70</input>
71`
72
73function toLines(text: string) {
74 return text.split('\n').map(line => line.trim()).filter(Boolean)
75}
76
77async function runClaude($: EngineInterface, prompt: string): Promise<string[]> {
78 const result = await $.model.complete({ model, prompt, maxTokens: 250, timeoutMs: 30_000 })
79 return result.isAnswered ? toLines(result.text) : []
80}
81
82async function runOllama($: EngineInterface, prompt: string, mine: number): Promise<string[]> {
83 // `think: false` disables reasoning tokens; `temperature: 0` and `num_predict` keep the output short
84 const body = JSON.stringify({
85 model,
86 prompt,
87 stream: true,
88 think: false,
89 keep_alive: '30m',
90 options: { temperature: 0, num_predict: 250 },
91 })
92 // curl instead of $.http.fetch, which resolves only once the whole answer is in
93 // cwd `/` because the session's may be deleted (a removed worktree), which fails the spawn with ENOENT
94 const curl = $.process.spawn({ argv: ['curl', '-sSN', '--fail-with-body', OLLAMA_URL, '-d', '@-'], cwd: '/', input: body })
95 let ndjson = ''
96 let answer = ''
97 let stderr = ''
98 let shown = 0
99 for await (const chunk of curl) {
100 if (mine !== seq) {
101 // Closing the stream ends curl, and Ollama stops generating for a dropped connection
102 break
103 }
104 if (chunk.stream === 'stderr') {
105 stderr += chunk.text
106 continue
107 }
108 ndjson += chunk.text
109 const objects = ndjson.split('\n')
110 ndjson = objects.pop() ?? ''
111 for (const object of objects) {
112 if (object.trim() !== '') {
113 answer += (JSON.parse(object) as { response?: string }).response ?? ''
114 }
115 }
116 // Show each line once the model finishes it, not word by word
117 const finished = toLines(answer.slice(0, answer.lastIndexOf('\n') + 1))
118 if (finished.length > shown) {
119 shown = finished.length
120 const partial: GrammarCheck = { status: 'streaming', lines: finished }
121 await update($, check, () => partial)
122 }
123 }
124 if (mine !== seq) {
125 return []
126 }
127 const { code } = await curl.result
128 if (code !== 0) {
129 return [`ollama unreachable (${stderr.trim() || `curl exited ${code}`})`]
130 }
131 return toLines(answer)
132}
133
134// Set by register from the `model` option
135let backend = ''
136let model = ''
137let timer: Timer | undefined
138// The draft the debounce timer holds, so a submit can check it without waiting
139let unchecked: { draft: string; mine: number } | undefined
140// Bumped on every edit, so a slow answer for an older draft never overwrites a newer one
141let seq = 0
142// Ollama answers one request at a time, so a check sent while another runs only queues behind it
143let isRunning = false
144let waiting: { draft: string; mine: number } | undefined
145// The seq of a submitted draft, whose answer lands dimmed
146let submitted = 0
147
148function cancelChecks() {
149 timer?.cancel()
150 unchecked = undefined
151 seq += 1
152 waiting = undefined
153}
154
155async function clear($: EngineInterface) {
156 cancelChecks()
157 await update($, check, () => null)
158}
159
160async function grammarCheck($: EngineInterface, draft: string, mine: number) {
161 await update($, check, (prev): GrammarCheck => ({ status: 'checking', lines: prev?.lines ?? [] }))
162 const prompt = GRAMMAR_PROMPT.replace('{latest_user_input}', draft.slice(0, 500))
163 let lines: string[]
164 try {
165 lines = await (backend === 'claude' ? runClaude($, prompt) : runOllama($, prompt, mine))
166 } catch (error) {
167 lines = [`${backend} unreachable (${error instanceof Error ? error.message : String(error)})`]
168 }
169 if (mine === seq) {
170 const result: GrammarCheck = { status: mine === submitted ? 'submitted' : 'done', lines }
171 await update($, check, () => result)
172 }
173}
174
175async function requestCheck($: EngineInterface, draft: string, mine: number) {
176 if (isRunning) {
177 waiting = { draft, mine }
178 return
179 }
180 isRunning = true
181 let next: { draft: string; mine: number } | undefined = { draft, mine }
182 try {
183 while (next !== undefined) {
184 await grammarCheck($, next.draft, next.mine)
185 // Skip a waiting draft that a newer edit already replaced; that edit's timer brings its own check
186 next = waiting?.mine === seq ? waiting : undefined
187 waiting = undefined
188 }
189 } finally {
190 isRunning = false
191 }
192}
193
194async function scheduleCheck($: EngineInterface, text: string) {
195 // Check a slash command's arguments, not the command name
196 const draft = text.trim().replace(/^\/\S*\s*/, '')
197 if (draft === '' || draft.startsWith('!')) {
198 await clear($)
199 return
200 }
201 timer?.cancel()
202 seq += 1
203 const mine = seq
204 unchecked = { draft, mine }
205 timer = $.clock.after(DEBOUNCE_MS, () => {
206 unchecked = undefined
207 void requestCheck($, draft, mine)
208 })
209}
210
211async function dimResult($: EngineInterface) {
212 // Keep checking the sent draft and show its result dimmed until the next edit
213 // A submit dims twice, from prompt.submit and from the clear it raises, so the second call finds nothing unchecked
214 submitted = seq
215 if (unchecked !== undefined) {
216 timer?.cancel()
217 void requestCheck($, unchecked.draft, unchecked.mine)
218 unchecked = undefined
219 }
220 await update($, check, (prev): GrammarCheck | null => (prev?.status === 'done' ? { ...prev, status: 'submitted' } : prev))
221}
222
223export const register: Register = (on, options) => {
224 const value = String(options.model)
225 const slash = value.indexOf('/')
226 backend = value.slice(0, slash)
227 model = value.slice(slash + 1)
228
229 on('prompt.edit', async ($, e, next) => {
230 const r = await next(e)
231 // A bare cursor move changes nothing worth checking
232 // A bare digit in an empty prompt presses a band Button's hotkey, and a check redrawing the band before that press lands makes it miss
233 if (r.text === e.text || (e.text === '' && /^[0-9]$/.test(r.text))) {
234 return r
235 }
236 await scheduleCheck($, r.text)
237 return r
238 })
239
240 // History recall, undo, clear and plugin fills change the box without a prompt.edit
241 on('prompt.change', async ($, e, next) => {
242 // Dim rather than drop on a clear: a submit raises one too, and its order against prompt.submit is unspecified
243 // A clear's text holds keys typed since, so a non-empty one is checked like any other change
244 await (e.origin.kind === 'clear' && e.text === '' ? dimResult($) : scheduleCheck($, e.text))
245 return next(e)
246 })
247
248 on('prompt.submit', async ($, e, next) => {
249 await dimResult($)
250 return next(e)
251 })
252
253 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
254 const current = await read($, check)
255 if (e.props.hasSurvey || current === null) {
256 return next(e)
257 }
258
259 const { Box, Text } = $.ui.resolve(e)
260 const isDesktop = e.surface === 'desktop'
261 const isChecking = current.status === 'checking' || current.status === 'streaming'
262 const isDimmed = current.status === 'checking' || current.status === 'submitted'
263 // Unlike hal-statusline's colorize_grammar, which colors each whole line, only the quoted fixes are red; a line without ` => ` is green for no issues, red otherwise
264 const color = current.lines.some(line => line.toLowerCase().includes('no issues')) ? 'green' : 'red'
265
266 return (
267 // The glyph gets its own column: in a proportional font "⏺ " is not two cells wide, so padding would misalign the lines
268 // On desktop, one cell of padding matches the inset of the app's own branch card above
269 <Box flexDirection="row" marginTop={1} paddingLeft={isDesktop ? 1 : 0}>
270 {isDesktop ? null : (
271 <Box width={2}>
272 <Text dimColor={isDimmed}>⏺</Text>
273 </Box>
274 )}
275 <Box flexDirection="column">
276 <Text dimColor={isDimmed}>hal-grammar-check:{isChecking ? ' checking...' : ''}</Text>
277 {current.lines.map((issue, i) => {
278 const arrow = issue.indexOf(' => ')
279 if (arrow === -1) {
280 return (
281 <Text key={`line-${i}`} color={color} dimColor={isDimmed}>
282 {issue}
283 </Text>
284 )
285 }
286 // The model quotes each corrected word, so the odd parts of a split on `"` are the fixes
287 const parts = issue.slice(0, arrow).split('"')
288 return (
289 <Text key={`line-${i}`} dimColor={isDimmed}>
290 {parts.map((part, j) => (
291 <Text key={`part-${j}`} color={j % 2 === 1 ? 'red' : undefined}>
292 {part}
293 </Text>
294 ))}
295 <Text> => {issue.slice(arrow + 4)}</Text>
296 </Text>
297 )
298 })}
299 </Box>
300 </Box>
301 )
302 })
303}
304types/index.d.ts 8 lines1export type GrammarCheck = { status: 'checking' | 'streaming' | 'done' | 'submitted'; lines: string[] }
2
3declare module 'claude-code' {
4 interface PluginState {
5 'hal-grammar-check': { check: GrammarCheck | null }
6 }
7}
8