opencode-quill 0.3.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,18 @@ All notable changes are documented in this file using
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [0.5.0] - 2026-10-22
8
+
9
+ ### Added
10
+
11
+ - **prediction:** Complete learned slash tokens and preserve prior weight
12
+
13
+ ## [0.4.0] - 2026-10-21
14
+
15
+ ### Added
16
+
17
+ - Add logical-line-end completion and suggestion cycling
18
+
7
19
  ## [0.3.4] - 2026-10-21
8
20
 
9
21
  ### Fixed
@@ -103,6 +115,8 @@ All notable changes are documented in this file using
103
115
  - `/quill` command and command palette action to toggle autocomplete.
104
116
  - Local installer script, full test suite, CI workflows, and release tooling.
105
117
 
118
+ [0.5.0]: https://github.com/ozandogrultan/opencode-quill/compare/v0.4.0...v0.5.0
119
+ [0.4.0]: https://github.com/ozandogrultan/opencode-quill/compare/v0.3.4...v0.4.0
106
120
  [0.3.4]: https://github.com/ozandogrultan/opencode-quill/compare/v0.3.3...v0.3.4
107
121
  [0.3.3]: https://github.com/ozandogrultan/opencode-quill/compare/v0.3.2...v0.3.3
108
122
  [0.3.2]: https://github.com/ozandogrultan/opencode-quill/compare/v0.3.1...v0.3.2
package/README.md CHANGED
@@ -45,13 +45,16 @@ Press <kbd>Tab</kbd> or <kbd>→</kbd> to accept it, or <kbd>Esc</kbd> to dismis
45
45
  and modal dialogs. Attachment and pasted-text chips are treated as non-prose:
46
46
  words are still suggested after them, but never inside them, and typo
47
47
  replacements are not offered while a chip is present.
48
- - **End-of-draft only:** Suggestions appear when the cursor is at the end of the
49
- draft, either on a partial word or after a space.
48
+ - **End-of-draft by default:** Suggestions appear on a partial word or after a
49
+ space at the end of the draft. Opt-in logical-line-end completion can also
50
+ append a suffix or next word immediately before a newline, preserving later
51
+ lines. It never suggests in the middle of a line or at a visual wrap boundary.
50
52
 
51
53
  ## What suggestions look like
52
54
 
53
- The suggestion appears dimmed at the end of the draft. It is not part of the
54
- editable text until you press <kbd>Tab</kbd> or <kbd>→</kbd>.
55
+ The suggestion appears dimmed at the cursor, at the end of the draft or an
56
+ opt-in logical line end. It is not part of the editable text until you press
57
+ <kbd>Tab</kbd> or <kbd>→</kbd>.
55
58
 
56
59
  | Kind | Your draft | Dimmed suggestion | Draft after acceptance |
57
60
  | --- | --- | --- | --- |
@@ -147,6 +150,7 @@ To pass custom options:
147
150
  "package": "/absolute/path/to/opencode-quill/src",
148
151
  "options": {
149
152
  "enabled": true,
153
+ "completeAtLineEnd": true,
150
154
  "acceptKeys": ["tab", "right"],
151
155
  "dismissKeys": ["escape"]
152
156
  }
@@ -161,9 +165,26 @@ Restart OpenCode after editing `cli.json`.
161
165
 
162
166
  | Option | Type | Default | Description |
163
167
  | --- | --- | --- | --- |
164
- | `enabled` | `boolean` | `true` | Enables or disables suggestions; can also be toggled with `/quill`. |
168
+ | `enabled` | `boolean` | `true` | Initial default for suggestions and learning; a persisted `/quill` toggle takes precedence. |
169
+ | `completeAtLineEnd` | `boolean` | `false` | Also append completions or next words immediately before a newline within a draft. |
165
170
  | `acceptKeys` | `string[]` | `["tab", "right"]` | Keys that accept and insert the active word suggestion. |
166
171
  | `dismissKeys` | `string[]` | `["escape"]` | Keys that dismiss the visible suggestion without inserting. |
172
+ | `cycleNextKeys` | `string[]` | `[]` | Optional keys for the next confident word suggestion. |
173
+ | `cyclePreviousKeys` | `string[]` | `[]` | Optional keys for the previous confident word suggestion. |
174
+
175
+ `completeAtLineEnd` uses prose context only up to the cursor while checking
176
+ code and attachment ranges across the full draft. It inserts only missing
177
+ letters or a next word, without replacing typed text. Typo and casing
178
+ replacements remain limited to chip-free draft ends. The suggestion must fit
179
+ the visible cursor row; it never overwrites the next line. Acceptance preserves
180
+ later lines, attachment metadata, host callbacks, and native undo/redo.
181
+
182
+ Cycling changes only the ghost text; Tab still accepts the selected suggestion.
183
+ Alternatives use the same confidence and typo guards as the best suggestion.
184
+ The ranked list is capped at five, wraps in either direction, and resets when
185
+ the draft, cursor, attachment ranges, or learned model changes. Alternatives
186
+ that do not fit the visible cursor row are skipped. Without a visible,
187
+ eligible alternative, cycle keys fall through to OpenCode.
167
188
 
168
189
  Custom keybindings can also be overridden using OpenCode's standard
169
190
  `keybinds` map in `cli.json`:
@@ -172,16 +193,28 @@ Custom keybindings can also be overridden using OpenCode's standard
172
193
  {
173
194
  "keybinds": {
174
195
  "quill.accept": "ctrl+y",
175
- "quill.dismiss": "ctrl+g"
196
+ "quill.dismiss": "ctrl+g",
197
+ "quill.next": "alt+n",
198
+ "quill.previous": "alt+p"
176
199
  }
177
200
  }
178
201
  ```
179
202
 
203
+ Quill's accept/dismiss/cycle layer runs in base mode at priority `2`, only in
204
+ the focused normal composer. A visible suggestion takes Tab/Right for
205
+ acceptance and Escape for dismissal. With no eligible visible suggestion,
206
+ commands return `false` or are disabled so host dispatch continues. Host
207
+ autocomplete that captures navigation suppresses Quill; its Tab and Escape
208
+ handlers remain in control. Dialogs and selections also suppress Quill.
209
+
180
210
  ## Commands
181
211
 
182
212
  - `/quill` — Toggle word autocomplete on or off (persisted across sessions).
183
213
  - `/quill on` / `/quill off` — Set autocomplete explicitly.
184
214
  - `/quill clear` (alias `/quill reset`) — Erase everything Quill has learned from your prompts.
215
+ - `quill.next` / `quill.previous` — Keymap commands for cycling visible word
216
+ alternatives; no default bindings. Configure the cycle options above or
217
+ OpenCode's `keybinds` map.
185
218
  - **Command Palette (`Ctrl+P`)** — Includes **Word autocomplete: on/off** and
186
219
  **Clear word autocomplete history**.
187
220
 
@@ -246,9 +279,12 @@ state directory (`$XDG_STATE_HOME` when set, otherwise `~/.local/state`):
246
279
  | Learned model | `opencode/<channel>/tui/plugin.quill.learning.json` |
247
280
  | Settings | `opencode/<channel>/tui/plugin.quill.settings.json` |
248
281
 
249
- The learned model holds only word, bigram, trigram and word-casing counts plus
250
- processed message IDs. Raw prompt text is never written to disk. These files stay on your
251
- machine and are never tracked in Git or published to npm.
282
+ The learned model holds word, bigram, trigram and word-casing counts plus
283
+ processed message IDs. These include local one-to-three-word fragments from
284
+ your prose, so the model can reveal parts of your prompts. Quill does not store
285
+ raw prompts or full message bodies. These files stay on your machine and are
286
+ never tracked in Git or published to npm. `/quill clear` erases the learned
287
+ model; the persisted on/off setting is separate.
252
288
 
253
289
  ## Development
254
290
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-quill",
3
- "version": "0.3.4",
3
+ "version": "0.5.0",
4
4
  "description": "OpenCode prompt autocomplete: local n-gram word and next-word prediction shown as inline ghost text in the TUI composer, accepted with Tab.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/ghost.ts CHANGED
@@ -39,9 +39,9 @@ export function findComposer(marker: Renderable | undefined, isEditor: (node: Re
39
39
  }
40
40
 
41
41
  export class ComposerGhost {
42
- private shown: { text: string; offset: number; prediction: Prediction } | undefined
43
- private dismissed: string | undefined
44
- private memo: { text: string; offset: number; marks: string; prediction: Prediction | undefined } | undefined
42
+ private shown: { text: string; offset: number; prediction: Prediction; marks: string; revision: number } | undefined
43
+ private dismissed: { text: string; offset: number } | undefined
44
+ private memo: { text: string; offset: number; marks: string; revision: number; predictions: Prediction[]; index: number } | undefined
45
45
  private disposed = false
46
46
  private readonly draw: (buffer: OptimizedBuffer, delta: number) => void
47
47
 
@@ -51,6 +51,7 @@ export class ComposerGhost {
51
51
  private readonly view: () => Composer,
52
52
  private readonly color: () => RGBA,
53
53
  private readonly renderer: CliRenderer,
54
+ private readonly completeAtLineEnd = false,
54
55
  ) {
55
56
  this.draw = (buffer) => { if (!this.disposed) this.paint(buffer) }
56
57
  renderer.addPostProcessFn(this.draw)
@@ -67,6 +68,23 @@ export class ComposerGhost {
67
68
  ])
68
69
  }
69
70
 
71
+ private marksKey(): string {
72
+ return this.editor.extmarks.getAll().map((mark) => `${mark.id}:${mark.start}:${mark.end}:${mark.virtual}:${mark.typeId}:${mark.styleId}:${mark.priority}`).join()
73
+ }
74
+
75
+ private room(): number {
76
+ const cursor = this.editor.visualCursor
77
+ const x = this.editor.screenX + cursor.visualCol
78
+ const y = this.editor.screenY + cursor.visualRow
79
+ if (x < 0 || y < 0 || y >= this.renderer.height || cursor.visualRow < 0 || cursor.visualRow >= this.editor.height) return 0
80
+ return Math.min(this.editor.width - cursor.visualCol, this.renderer.width - x)
81
+ }
82
+
83
+ private fits(prediction: Prediction): boolean {
84
+ const room = this.room()
85
+ return room > 0 && this.editor.editBuffer.measureText(prediction.replace ? ` → ${prediction.suffix}` : prediction.suffix) <= room
86
+ }
87
+
70
88
  invalidate(): void {
71
89
  this.memo = undefined
72
90
  this.shown = undefined
@@ -74,23 +92,25 @@ export class ComposerGhost {
74
92
  }
75
93
 
76
94
  private prediction(text: string, offset: number): Prediction | undefined {
77
- if (this.dismissed !== undefined && this.dismissed !== text) this.dismissed = undefined
78
- if (this.dismissed === text || !eligibleComposer(this.view(), text)) return
95
+ if (this.dismissed && (this.dismissed.text !== text || this.dismissed.offset !== offset)) this.dismissed = undefined
96
+ if (this.dismissed || !eligibleComposer(this.view(), text)) return
79
97
  const marks = this.editor.extmarks.getAll()
80
- const signature = marks.map((mark) => `${mark.start}:${mark.end}`).join()
81
- if (this.memo?.text === text && this.memo.offset === offset && this.memo.marks === signature) return this.memo.prediction
82
- const query = completionQuery(text, offset, this.protectedRanges(marks))
83
- let prediction = query && this.predictor.complete(query)
84
- if (marks.length && prediction?.replace) prediction = undefined
98
+ const signature = this.marksKey()
99
+ const revision = this.predictor.modelRevision
100
+ if (this.memo?.text === text && this.memo.offset === offset && this.memo.marks === signature && this.memo.revision === revision) return this.memo.predictions[this.memo.index]
101
+ const query = completionQuery(text, offset, this.protectedRanges(marks), this.completeAtLineEnd)
102
+ const predictions = query ? this.predictor.candidates(query) : []
103
+ if ((marks.length || offset !== text.length) && predictions[0]?.replace) predictions.length = 0
104
+ else if (marks.length || offset !== text.length) predictions.splice(0, predictions.length, ...predictions.filter((prediction) => !prediction.replace))
85
105
  const last = this.shown
86
- if (query && !query.next && last && !last.prediction.replace && text.startsWith(last.text)) {
106
+ if (query && !query.next && offset === text.length && last && last.offset === last.text.length && this.memo?.index === 0 && last.revision === revision && last.marks === signature && !last.prediction.replace && text.startsWith(last.text)) {
87
107
  const typed = text.slice(last.text.length)
88
108
  if (typed && last.prediction.suffix.startsWith(typed) && typed.length < last.prediction.suffix.length) {
89
- prediction = { ...last.prediction, suffix: last.prediction.suffix.slice(typed.length) }
109
+ predictions[0] = { ...last.prediction, suffix: last.prediction.suffix.slice(typed.length) }
90
110
  }
91
111
  }
92
- this.memo = { text, offset, marks: signature, prediction }
93
- return prediction
112
+ this.memo = { text, offset, marks: signature, revision, predictions, index: 0 }
113
+ return predictions[0]
94
114
  }
95
115
 
96
116
  private paint(buffer: OptimizedBuffer): void {
@@ -106,9 +126,9 @@ export class ComposerGhost {
106
126
  return
107
127
  }
108
128
  const cursor = this.editor.visualCursor
109
- const room = this.editor.width - cursor.visualCol
129
+ const room = this.room()
110
130
  const ghost = prediction.replace ? ` → ${prediction.suffix}` : prediction.suffix
111
- if (room <= 0 || cursor.visualRow < 0 || cursor.visualRow >= this.editor.height || this.editor.editBuffer.measureText(ghost) > room) {
131
+ if (!this.fits(prediction)) {
112
132
  this.shown = undefined
113
133
  return
114
134
  }
@@ -120,16 +140,15 @@ export class ComposerGhost {
120
140
  } finally {
121
141
  buffer.popScissorRect()
122
142
  }
123
- this.shown = { text, offset, prediction }
143
+ this.shown = { text, offset, prediction, marks: this.memo!.marks, revision: this.memo!.revision }
124
144
  }
125
145
 
126
146
  accept(): boolean {
127
147
  const shown = this.shown
128
- if (this.disposed || !shown || !eligibleComposer(this.view()) ||
129
- this.editor.plainText !== shown.text || this.offset() !== shown.offset) return false
148
+ if (!shown || !this.visible()) return false
130
149
  const marks = this.editor.extmarks.getAll()
131
- if (!completionQuery(shown.text, shown.offset, this.protectedRanges(marks))) return false
132
- if (marks.length && shown.prediction.replace) return false
150
+ if (!completionQuery(shown.text, shown.offset, this.protectedRanges(marks), this.completeAtLineEnd)) return false
151
+ if ((marks.length || shown.offset !== shown.text.length) && shown.prediction.replace) return false
133
152
  this.shown = undefined
134
153
  if (shown.prediction.replace) {
135
154
  this.editor.replaceText(shown.text.slice(0, shown.text.length - shown.prediction.replace) + shown.prediction.suffix)
@@ -142,9 +161,8 @@ export class ComposerGhost {
142
161
  }
143
162
 
144
163
  dismiss(): boolean {
145
- if (this.disposed || !this.shown || !eligibleComposer(this.view()) ||
146
- this.editor.plainText !== this.shown.text || this.offset() !== this.shown.offset) return false
147
- this.dismissed = this.editor.plainText
164
+ if (!this.visible()) return false
165
+ this.dismissed = { text: this.shown!.text, offset: this.shown!.offset }
148
166
  this.shown = undefined
149
167
  this.editor.requestRender()
150
168
  return true
@@ -152,7 +170,23 @@ export class ComposerGhost {
152
170
 
153
171
  visible(): boolean {
154
172
  return !this.disposed && !!this.shown && eligibleComposer(this.view()) &&
155
- this.editor.plainText === this.shown.text && this.offset() === this.shown.offset
173
+ this.editor.plainText === this.shown.text && this.offset() === this.shown.offset &&
174
+ this.marksKey() === this.shown.marks && this.predictor.modelRevision === this.shown.revision && this.fits(this.shown.prediction)
175
+ }
176
+
177
+ canCycle(): boolean {
178
+ return this.visible() && this.memo!.predictions.some((prediction, index) => index !== this.memo!.index && this.fits(prediction))
179
+ }
180
+
181
+ cycle(direction: 1 | -1): boolean {
182
+ if (!this.canCycle()) return false
183
+ const memo = this.memo!
184
+ do {
185
+ memo.index = (memo.index + direction + memo.predictions.length) % memo.predictions.length
186
+ } while (!this.fits(memo.predictions[memo.index]))
187
+ this.shown = undefined
188
+ this.editor.requestRender()
189
+ return true
156
190
  }
157
191
 
158
192
  dispose(): void {
package/src/keymap.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { KeymapLayer } from "@opencode/plugin/tui/context"
2
2
  import type { Options } from "./options"
3
3
 
4
- type Suggestion = { visible(): boolean; accept(): boolean; dismiss(): boolean }
4
+ type Suggestion = { visible(): boolean; accept(): boolean; dismiss(): boolean; canCycle(): boolean; cycle(direction: 1 | -1): boolean }
5
5
 
6
6
  export function completionLayer(options: Options, suggestion: () => Suggestion | undefined): KeymapLayer {
7
7
  return {
@@ -22,6 +22,13 @@ export function completionLayer(options: Options, suggestion: () => Suggestion |
22
22
  enabled: () => suggestion()?.visible() === true,
23
23
  run: () => suggestion()?.dismiss() ? undefined : false,
24
24
  },
25
+ ...([["next", 1, options.cycleNextKeys], ["previous", -1, options.cyclePreviousKeys]] as const).map(([name, direction, keys]) => ({
26
+ id: `quill.${name}`,
27
+ title: `${name === "next" ? "Next" : "Previous"} word suggestion`,
28
+ bind: keys.length ? keys.join(",") : false as const,
29
+ enabled: () => suggestion()?.canCycle() === true,
30
+ run: () => suggestion()?.cycle(direction) ? undefined : false,
31
+ })),
25
32
  ],
26
33
  }
27
34
  }
package/src/options.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type Options = { enabled: boolean; acceptKeys: string[]; dismissKeys: string[] }
1
+ export type Options = { enabled: boolean; completeAtLineEnd: boolean; acceptKeys: string[]; dismissKeys: string[]; cycleNextKeys: string[]; cyclePreviousKeys: string[] }
2
2
 
3
3
  function keys(value: unknown, fallback: string[], name: string): string[] {
4
4
  if (value === undefined) return fallback
@@ -10,10 +10,14 @@ function keys(value: unknown, fallback: string[], name: string): string[] {
10
10
 
11
11
  export function resolveOptions(input: Readonly<Record<string, unknown>>): Options {
12
12
  if (input.enabled !== undefined && typeof input.enabled !== "boolean") throw new Error("Quill enabled must be a boolean")
13
+ if (input.completeAtLineEnd !== undefined && typeof input.completeAtLineEnd !== "boolean") throw new Error("Quill completeAtLineEnd must be a boolean")
13
14
  return {
14
15
  enabled: input.enabled !== false,
16
+ completeAtLineEnd: input.completeAtLineEnd === true,
15
17
  acceptKeys: keys(input.acceptKeys, ["tab", "right"], "acceptKeys"),
16
18
  dismissKeys: keys(input.dismissKeys, ["escape"], "dismissKeys"),
19
+ cycleNextKeys: keys(input.cycleNextKeys, [], "cycleNextKeys"),
20
+ cyclePreviousKeys: keys(input.cyclePreviousKeys, [], "cyclePreviousKeys"),
17
21
  }
18
22
  }
19
23
 
@@ -31,4 +35,3 @@ export function parseQuillCommand(input: string | undefined): QuillCommand {
31
35
  if (raw === "off") return { type: "enable", value: false }
32
36
  return { type: "invalid" }
33
37
  }
34
-
package/src/predictor.ts CHANGED
@@ -192,6 +192,10 @@ function applyCase(source: string, word: string): string {
192
192
  }
193
193
 
194
194
  export class WordPredictor {
195
+ private revision = 0
196
+
197
+ get modelRevision(): number { return this.revision }
198
+
195
199
  readonly prior = new Map<string, number>()
196
200
  private priorTotal = 0
197
201
  private personal = new PersonalModel()
@@ -213,6 +217,7 @@ export class WordPredictor {
213
217
  }
214
218
 
215
219
  setPersonal(snapshot: Snapshot): void {
220
+ this.revision++
216
221
  this.personal = new PersonalModel(snapshot)
217
222
  this.personalTotal = [...this.personal.words.values()].reduce((sum, count) => sum + count, 0)
218
223
  this.bigramTotals = totals(this.personal.bigrams)
@@ -224,7 +229,7 @@ export class WordPredictor {
224
229
  const word = learned[index]
225
230
  if (this.prior.has(word)) continue
226
231
  for (let next = index + 1; next < learned.length && learned[next].startsWith(word); next++) {
227
- if (counts.get(learned[next])! >= counts.get(word)!) {
232
+ if (learned[next][word.length] !== "/" && counts.get(learned[next])! >= counts.get(word)!) {
228
233
  fragments.add(word)
229
234
  break
230
235
  }
@@ -247,7 +252,7 @@ export class WordPredictor {
247
252
  for (let index = lowerBound(this.vocabulary, head); index < this.vocabulary.length; index++) {
248
253
  const word = this.vocabulary[index]
249
254
  if (!word.startsWith(head)) break
250
- if (word.length >= prefix.length - 1 && word.length <= maxLength) yield word
255
+ if (!word.includes("/") && word.length >= prefix.length - 1 && word.length <= maxLength) yield word
251
256
  }
252
257
  }
253
258
  }
@@ -255,7 +260,7 @@ export class WordPredictor {
255
260
  private score(word: string, context: readonly string[]): number {
256
261
  const prior = (this.prior.get(word) ?? 0) / (this.priorTotal || 1)
257
262
  const personal = (this.personal.words.get(word) ?? 0) / (this.personalTotal || 1)
258
- const weight = this.personalTotal / (this.personalTotal + 100)
263
+ const weight = this.priorTotal ? Math.min(0.7, this.personalTotal / (this.personalTotal + 100)) : 1
259
264
  let score = weight * personal + (1 - weight) * prior
260
265
  const previous = context.at(-1)
261
266
  const bigram = previous && this.bigramTotals.get(previous)
@@ -299,57 +304,69 @@ export class WordPredictor {
299
304
  }
300
305
 
301
306
  complete(query: CompletionQuery): Prediction | undefined {
307
+ return this.candidates(query, 1)[0]
308
+ }
309
+
310
+ candidates(query: CompletionQuery, limit = 5): Prediction[] {
311
+ const maximum = Number.isFinite(limit) ? Math.max(0, Math.min(5, Math.floor(limit))) : 5
312
+ if (!maximum) return []
302
313
  const prefix = normalizeWord(query.prefix)
303
314
  const words = query.words ?? proseWords(query.before)
304
315
  const local = new Map<string, number>()
305
316
  for (const word of words) increment(local, word.text)
306
317
  const context = this.resolveContext(leftContext(query.before, words), local)
307
318
  const evidence = this.bigramTotals.get(context.at(-1) ?? "")?.total ?? 0
308
- if (query.next && evidence < 2) return
309
- if (!query.next && [...prefix].length < 2 && evidence < 2) return
319
+ if (query.next && evidence < 2) return []
320
+ if (!query.next && [...prefix].length < 2 && evidence < 2) return []
321
+ const slash = prefix.includes("/")
310
322
  const candidates = new Map<string, number>()
311
323
  for (let index = lowerBound(this.vocabulary, prefix); index < this.vocabulary.length; index++) {
312
324
  const word = this.vocabulary[index]
313
325
  if (!word.startsWith(prefix)) break
314
- candidates.set(word, 1)
326
+ if (query.next || slash === word.includes("/")) candidates.set(word, 1)
315
327
  }
316
- for (const word of local.keys()) if (word.startsWith(prefix)) candidates.set(word, 1)
317
- const suggest = (): Prediction | undefined => {
318
- let best = ""
319
- let bestScore = 0
320
- let bestWeight = 1
328
+ for (const word of local.keys()) if (!word.includes("/") && word.startsWith(prefix) && (query.next || !slash)) candidates.set(word, 1)
329
+ const suggest = (): Prediction[] => {
330
+ const ranked: { word: string; score: number; weight: number }[] = []
321
331
  let sum = 0
322
332
  for (const [word, weight] of candidates) {
323
333
  const base = this.score(word, context) + (query.next ? 0 : 0.003 * Math.min(local.get(word) ?? 0, 3))
324
334
  const score = base * weight
325
335
  sum += score
326
- if (score > bestScore) {
327
- best = word
328
- bestScore = score
329
- bestWeight = weight
330
- }
336
+ ranked.push({ word, score, weight })
337
+ ranked.sort((a, b) => b.score - a.score)
338
+ if (ranked.length > maximum) ranked.pop()
331
339
  }
332
- const confidence = bestWeight < 1 ? typoConfidence(bestScore, sum) : query.next ? bestScore : bestScore / (sum || 1)
333
- if (!best || best === prefix || confidence === undefined || (bestWeight === 1 && confidence < (query.next ? 0.55 : 0.3))) return
334
- const form = this.forms.get(best) ?? best
335
- const shouting = query.prefix.length > 1 && query.prefix === query.prefix.toUpperCase()
336
- if (bestWeight < 1 || (!query.next && best.startsWith("i'") && query.prefix[0] === "i") ||
337
- (!query.next && !shouting && form !== best && !form.startsWith(query.prefix))) {
338
- return { suffix: applyCase(query.prefix, form), word: best, confidence, replace: query.prefix.length }
340
+ const predictions: Prediction[] = []
341
+ for (const { word: best, score: bestScore, weight: bestWeight } of ranked) {
342
+ const confidence = bestWeight < 1 ? typoConfidence(bestScore, sum) : query.next ? bestScore : bestScore / (sum || 1)
343
+ if (!bestScore || best === prefix || confidence === undefined || (bestWeight === 1 && confidence < (query.next ? 0.55 : 0.3))) {
344
+ if (!predictions.length) return []
345
+ continue
346
+ }
347
+ const form = this.forms.get(best) ?? best
348
+ const shouting = query.prefix.length > 1 && query.prefix === query.prefix.toUpperCase()
349
+ if (bestWeight < 1 || (!query.next && best.startsWith("i'") && query.prefix[0] === "i") ||
350
+ (!query.next && !shouting && form !== best && !form.startsWith(query.prefix))) {
351
+ predictions.push({ suffix: applyCase(query.prefix, form), word: best, confidence, replace: query.prefix.length })
352
+ } else if (query.next) {
353
+ predictions.push({ suffix: applyCase("", form), word: best, confidence })
354
+ } else {
355
+ const suffix = form.slice(prefix.length)
356
+ predictions.push({ suffix: shouting ? suffix.toUpperCase() : suffix, word: best, confidence })
357
+ }
339
358
  }
340
- if (query.next) return { suffix: applyCase("", form), word: best, confidence }
341
- const suffix = form.slice(prefix.length)
342
- return { suffix: shouting ? suffix.toUpperCase() : suffix, word: best, confidence }
359
+ return predictions
343
360
  }
344
361
  const completion = suggest()
345
- if (completion || query.next || prefix.length < 3 || candidates.has(prefix)) return completion
362
+ if (completion.length || query.next || prefix.length < 3 || slash || candidates.has(prefix)) return completion
346
363
  for (const word of this.nearbyWords(prefix)) {
347
364
  if (candidates.has(word)) continue
348
365
  const weight = typoWeight(prefix, word)
349
366
  if (weight > 0) candidates.set(word, weight)
350
367
  }
351
368
  for (const word of local.keys()) {
352
- if (candidates.has(word)) continue
369
+ if (candidates.has(word) || word.includes("/")) continue
353
370
  const weight = typoWeight(prefix, word)
354
371
  if (weight > 0) candidates.set(word, weight)
355
372
  }
package/src/prose.ts CHANGED
@@ -1,6 +1,8 @@
1
- const WORD = /[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*/gu
2
- const WHOLE_WORD = /^[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*$/u
3
- const WORD_END = /[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*$/u
1
+ const PART = "[\\p{L}\\p{M}]+(?:['’][\\p{L}\\p{M}]+)*"
2
+ const WORD = new RegExp(`${PART}(?:\\/${PART})?`, "gu")
3
+ const WHOLE_WORD = new RegExp(`^${PART}(?:\\/${PART})?$`, "u")
4
+ const WORD_PREFIX = new RegExp(`^${PART}(?:\\/(?:${PART})?)?$`, "u")
5
+ const WORD_END = new RegExp(`${PART}(?:\\/(?:${PART})?)?$`, "u")
4
6
 
5
7
  export type Word = { text: string; start: number; end: number }
6
8
  export type CompletionQuery = { before: string; prefix: string; next: boolean; words?: readonly Word[] }
@@ -13,6 +15,10 @@ export function isWord(word: string): boolean {
13
15
  return WHOLE_WORD.test(word) && [...word].length <= 32
14
16
  }
15
17
 
18
+ function isPrefix(prefix: string): boolean {
19
+ return WORD_PREFIX.test(prefix) && [...prefix].length <= 32
20
+ }
21
+
16
22
  function blank(text: string): string {
17
23
  return text.replace(/[^\n]/g, " ")
18
24
  }
@@ -25,7 +31,8 @@ export function maskProse(text: string): string {
25
31
  masked = masked.replace(/^ {4,}.*$/gm, blank)
26
32
  masked = masked.replace(/\S+/g, (token) => {
27
33
  const core = token.replace(/^["“‘([{]+|["”’),;:!?}\]]+$/g, "")
28
- if (/[\/_@=\\<>-]|\d|[\p{Ll}][\p{Lu}]/u.test(core) || /^[.~]/.test(core)) return blank(token)
34
+ if (/[_@=\\<>-]|\d|[\p{Ll}][\p{Lu}]/u.test(core) || /^[.~]/.test(core)) return blank(token)
35
+ if (core.includes("/") && !(core.endsWith(".") ? WHOLE_WORD.test(core.slice(0, -1)) : WORD_PREFIX.test(core))) return blank(token)
29
36
  if (/[^.]+\.[^.]+|\.\.|--/.test(core)) return blank(token)
30
37
  return token
31
38
  })
@@ -34,7 +41,7 @@ export function maskProse(text: string): string {
34
41
 
35
42
  export function proseWords(text: string, masked = maskProse(text)): Word[] {
36
43
  return [...masked.matchAll(WORD)]
37
- .filter((match) => isWord(match[0]))
44
+ .filter((match) => isWord(match[0]) && masked[match.index + match[0].length] !== "/")
38
45
  .map((match) => ({ text: normalizeWord(match[0]), start: match.index, end: match.index + match[0].length }))
39
46
  }
40
47
 
@@ -72,14 +79,16 @@ function blankRanges(text: string, ranges: readonly TextRange[]): string {
72
79
  return result
73
80
  }
74
81
 
75
- export function completionQuery(text: string, characterOffset: number, protectedRanges: readonly TextRange[] = []): CompletionQuery | undefined {
76
- if (!text.trim() || characterOffset !== text.length || text.length > 16_000) return
77
- const masked = maskProse(protectedRanges.length ? blankRanges(text, protectedRanges) : text)
82
+ export function completionQuery(draft: string, characterOffset: number, protectedRanges: readonly TextRange[] = [], completeAtLineEnd = false): CompletionQuery | undefined {
83
+ if (!draft.trim() || draft.length > 16_000 || characterOffset < 0 || characterOffset > draft.length ||
84
+ (characterOffset !== draft.length && (!completeAtLineEnd || draft[characterOffset] !== "\n"))) return
85
+ const masked = maskProse(protectedRanges.length ? blankRanges(draft, protectedRanges) : draft).slice(0, characterOffset)
86
+ const text = draft.slice(0, characterOffset)
78
87
  const prefix = WORD_END.exec(text)?.[0]
79
88
  let end = text.length
80
89
  if (prefix) {
81
90
  const start = text.length - prefix.length
82
- if (masked.slice(start) !== prefix || !isWord(prefix)) return
91
+ if (masked.slice(start) !== prefix || !isPrefix(prefix)) return
83
92
  const preceding = text[start - 1]
84
93
  if (preceding && !/[ \t\n"“([{]/.test(preceding)) return
85
94
  end = start
package/src/tui.tsx CHANGED
@@ -55,12 +55,15 @@ export default Plugin.define({
55
55
  selected: context.renderer.hasSelection,
56
56
  enabled: !disposed && settings.enabled && currentEditor() === editor,
57
57
  }
58
- }, () => dimGhostColor(context.theme.text.muted), context.renderer)
58
+ }, () => dimGhostColor(context.theme.text.muted), context.renderer, options.completeAtLineEnd)
59
59
  }
60
60
 
61
+ const sessionInfo = (sessionID: string) =>
62
+ context.data.session.get?.(sessionID) ?? context.data.session.list().find((session) => session.id === sessionID)
63
+
61
64
  const learn = async (sessionID: string, announce = true) => {
62
65
  if (disposed || !settings.enabled) return
63
- if (context.data.session.list().find((session) => session.id === sessionID)?.parentID) return
66
+ if (sessionInfo(sessionID)?.parentID) return
64
67
  const active = inFlight.get(sessionID)
65
68
  if (active) {
66
69
  if (announce) {
@@ -78,9 +81,9 @@ export default Plugin.define({
78
81
  const shouldAnnounce = state.announce
79
82
  state.announce = false
80
83
  try {
81
- await context.data.session.message.sync(sessionID)
84
+ await Promise.all([context.data.session.sync?.(sessionID), context.data.session.message.sync(sessionID)])
82
85
  if (disposed || !settings.enabled) return
83
- if (context.data.session.list().find((session) => session.id === sessionID)?.parentID) return
86
+ if (sessionInfo(sessionID)?.parentID) return
84
87
  if (version !== resetVersion) continue
85
88
  const candidates = context.data.session.message.list(sessionID)
86
89
  .filter((message) => message.type === "user")
@@ -97,7 +100,8 @@ export default Plugin.define({
97
100
  if (model.observe(prompts)) {
98
101
  await setLearning((draft) => {
99
102
  if (disposed || !settings.enabled || version !== resetVersion) return
100
- if (context.data.session.list().find((session) => session.id === sessionID)?.parentID) return
103
+ const session = sessionInfo(sessionID)
104
+ if (!session || session.parentID) return
101
105
  const latest = new PersonalModel(unwrap(draft.snapshot))
102
106
  if (latest.observe(promptsFor(latest.clearedAt))) draft.snapshot = latest.snapshot()
103
107
  })