Skip to content

Commit 1edacdb

Browse files
wildthink-pubclaude
andcommitted
Sync review fixes from nodes-app#158/nodes-app#159 into the integration branch
Takes the post-review directive sources, tests, and docs from feat/directives-completion; keeps AGENTS.md and AUTHORING.md, which only this branch carries. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent f746ce7 commit 1edacdb

11 files changed

Lines changed: 350 additions & 79 deletions

‎ARCHITECTURE.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Sources/
77
├── MarkdownEngine/ # core target — zero deps
88
│ ├── Configuration/ # MarkdownEditorConfiguration + MarkdownEditorTheme
99
│ ├── Extensions/ # the extension seam: MarkdownExtension + bundled opt-ins
10-
│ ├── Directives/ # the directive seam: @font(size: 18){…} — parsing, glyphs, completion
10+
│ ├── Directives/ # the directive seam: @font(size: 18){…} — parsing, styling, glyphs, completion
1111
│ ├── Services/ # 4 protocols, no-op defaults, WikiLinkService
1212
│ ├── Parser/ # two-phase AST: BlockParser → InlineParser → DocumentAST (+ token projection)
1313
│ ├── Styling/ # MarkdownASTStyler (AST walk) + MarkdownStyler facade for NSImage passes
@@ -153,7 +153,8 @@ produce a partial construct.
153153
directive NAME (`@fo|`) or one of its ARGUMENT VALUES (`@icon(sta|`). It cannot
154154
use the AST: mid-typing, `@ico` and `@icon(sta` are precisely what the parser
155155
REJECTS, so it is a separate, forgiving backwards scan over the current line,
156-
bounded to 256 characters per caret move.
156+
bounded to 256 characters per caret move. It reuses the parser's boundary rule,
157+
so it can never offer a directive the parser would refuse.
157158

158159
The engine owns the CANDIDATES because it owns the registry — names come from
159160
the registered directives, values from `MarkdownDirective.valueCompletions`,

‎CHANGELOG.md‎

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Added
11+
- **Directive glyph presentation**: a self-contained call (`@marker`,
12+
`@glyph(star.fill)`) collapses its source behind an SF Symbol, replacement
13+
text, or an image supplied by the directive's `presentation`, and reveals the
14+
real characters again under the caret. The source is never removed from the
15+
storage — it collapses to zero width the same way inline LaTeX does — so
16+
selection, find, copy, and undo still see it. `Demo/` gains `@icon`, `@flag`,
17+
`@emoji`, and `@pagebreak` as embedder-side directives — anything carrying
18+
curated data or document policy is an app concern, not an engine primitive.
19+
- **Directive autocomplete** for both directive names and argument values,
20+
riding the existing inline-preview seam (`onDirectiveCompletion`,
21+
`pendingDirectiveCompletion`); the engine detects the trigger, ranks the
22+
candidates from the registry and from the directive's own
23+
`valueCompletions`, routes ↑/↓/↵/Esc, and ships no picker UI. The default
24+
`valueCompletions` already answers anything the declared schema can — closed
25+
keyword sets and booleans — so a directive implements it only when its domain
26+
is dynamic or too large to declare.
27+
1028
### Fixed
1129
- A programmatic content swap — a document switch, or the SwiftUI `text` binding
1230
changing from outside the editor — left the code-block selection pass reading
@@ -48,19 +66,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
4866
`ColorDirective` ship as opt-in reference directives, off by default like the
4967
bundled extensions. `MarkdownHTMLRenderer.html(from:extensions:directives:)`
5068
takes the registered set so rich copy matches what is on screen.
51-
- **Directive glyph presentation**: a self-contained call (`@marker`,
52-
`@glyph(star.fill)`) collapses its source behind an SF Symbol, replacement
53-
text, or an image supplied by the directive's `presentation`, and reveals the
54-
real characters again under the caret. The source is never removed from the
55-
storage — it collapses to zero width the same way inline LaTeX does — so
56-
selection, find, copy, and undo still see it.
57-
- **Directive autocomplete** for both names and argument values, riding the
58-
existing inline-preview seam (`onDirectiveCompletion`,
59-
`pendingDirectiveCompletion`); the engine ranks candidates from the registry
60-
and from the directive's own `valueCompletions`, and ships no picker UI.
61-
`Demo/` shows `@icon`, `@flag`, `@emoji`, and `@pagebreak` as embedder-side
62-
directives — anything carrying curated data or document policy is an app
63-
concern, not an engine primitive.
6469
- `NativeTextViewWrapper.onTextMutation` reports exact, completed native edits
6570
for embedders that maintain their own source authority or mirror edits into
6671
another presentation.

‎Sources/MarkdownEngine/Directives/BuiltinDirectives.swift‎

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@
88
//
99
// configuration.directives = [FontDirective(), ColorDirective()]
1010
//
11-
// Both are PURE PRESENTATION — a font transform and a colour. Directives that
12-
// carry curated data (icons, flags, emoji) or encode document policy (page
13-
// breaks) are app concerns, not engine primitives, so they belong to the
14-
// embedder; `Demo/` shows what those look like.
11+
// Both are PURE PRESENTATION — a font transform and a colour. Both are
12+
// containers, so neither draws a glyph; directives that carry curated data
13+
// (icons, flags, emoji) or encode document policy (page breaks) are app
14+
// concerns, not engine primitives, so they belong to the embedder. `Demo/`
15+
// shows what those look like.
1516
//
1617

1718
import AppKit
@@ -87,25 +88,6 @@ public struct FontDirective: MarkdownDirective {
8788
}
8889
}
8990

90-
// MARK: - Shared colour resolution
91-
92-
/// Standard colour names resolved without an asset catalog, so
93-
/// `@color(red){…}` works with no setup. An unlisted name falls back to
94-
/// `NSColor(named:)`, so an embedder's own palette entries keep working.
95-
enum DirectivePalette {
96-
static let named: [String: NSColor] = [
97-
"red": .systemRed, "orange": .systemOrange, "yellow": .systemYellow,
98-
"green": .systemGreen, "mint": .systemMint, "teal": .systemTeal,
99-
"cyan": .systemCyan, "blue": .systemBlue, "indigo": .systemIndigo,
100-
"purple": .systemPurple, "pink": .systemPink, "brown": .systemBrown,
101-
"gray": .systemGray, "grey": .systemGray,
102-
]
103-
104-
static func color(_ name: String) -> NSColor? {
105-
named[name.lowercased()] ?? NSColor(named: name)
106-
}
107-
}
108-
10991
// MARK: - @color(red){…} — container, positional argument
11092

11193
public struct ColorDirective: MarkdownDirective {
@@ -116,6 +98,17 @@ public struct ColorDirective: MarkdownDirective {
11698

11799
public var id: String { Self.identifier }
118100

101+
/// Standard colour names, resolved without an asset catalog so
102+
/// `@color(red){…}` works out of the box. An unlisted name falls back to
103+
/// `NSColor(named:)`, so embedders can add their own palette entries.
104+
private static let named: [String: NSColor] = [
105+
"red": .systemRed, "orange": .systemOrange, "yellow": .systemYellow,
106+
"green": .systemGreen, "mint": .systemMint, "teal": .systemTeal,
107+
"cyan": .systemCyan, "blue": .systemBlue, "indigo": .systemIndigo,
108+
"purple": .systemPurple, "pink": .systemPink, "brown": .systemBrown,
109+
"gray": .systemGray, "grey": .systemGray,
110+
]
111+
119112
public var syntax: DirectiveSyntax {
120113
DirectiveSyntax(
121114
name: Self.identifier,
@@ -145,7 +138,7 @@ public struct ColorDirective: MarkdownDirective {
145138
guard let name = arguments.positional.first?.asString else { return .inherit }
146139
// An unresolvable name leaves the body alone rather than guessing —
147140
// the source stays readable and the mistake is visible.
148-
guard let color = DirectivePalette.color(name) else { return .inherit }
141+
guard let color = Self.named[name.lowercased()] ?? NSColor(named: name) else { return .inherit }
149142
return DirectiveStyle(attributes: [.foregroundColor: color])
150143
}
151144

‎Sources/MarkdownEngine/Directives/DirectiveCompletionScanner.swift‎

Lines changed: 83 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,12 @@ public struct DirectiveCompletionItem: Sendable, Equatable {
7575
subtitle: completion.subtitle,
7676
detail: nil,
7777
insertion: snippet.replacingOccurrences(of: "|", with: ""),
78-
caretOffset: caret.map { snippet.distance(from: snippet.startIndex, to: $0) },
78+
// In UTF-16 units, not Characters: `caretOffset` is added onto an
79+
// NSRange location (`applyDirectiveCompletion`), which counts
80+
// UTF-16 code units. A Character count lands the caret wrong —
81+
// possibly mid-surrogate — for a snippet carrying any character
82+
// outside the BMP before the `|` marker.
83+
caretOffset: caret.map { snippet.utf16.distance(from: snippet.utf16.startIndex, to: $0) },
7984
symbolName: completion.symbolName
8085
)
8186
}
@@ -194,15 +199,43 @@ enum DirectiveCompletionScanner {
194199
let nameRange = NSRange(location: markerIndex + 1, length: cursor - (markerIndex + 1))
195200
let name = ns.substring(with: nameRange)
196201

197-
// Still inside the name: complete the directive name itself.
202+
// Still inside the name: complete the directive name itself. The name
203+
// run above only looked at characters BEFORE the caret, so a pick
204+
// made with the caret in the middle of an existing name (`@fo|nt`)
205+
// would otherwise replace only the typed prefix and leave the rest
206+
// of the identifier dangling after the inserted snippet. Extend the
207+
// replacement to the end of the name token too.
198208
if cursor == caret {
199-
let candidates = nameCandidates(prefix: name, marker: marker, directives: directives, settings: settings)
209+
// A bare marker (`Ping @|`) offers no context: every registered
210+
// directive would otherwise match, which captures Enter for
211+
// "confirm" in ordinary prose whenever a marker precedes it —
212+
// the boundary rule keeps an email address safe, but a marker
213+
// after a plain space is not. Wait for at least one typed
214+
// character before showing anything.
215+
guard !name.isEmpty else { return nil }
216+
217+
var nameEnd = caret
218+
while nameEnd < ns.length, isNameChar(ns.character(at: nameEnd)) { nameEnd += 1 }
219+
220+
// An exact, finished match — the typed name matches a directive
221+
// that needs nothing more (no required parameters) — is a
222+
// completed call, not something still being typed. Keeping the
223+
// context open here captures Enter as "confirm" instead of a
224+
// newline break for a self-contained call like `@pagebreak`.
225+
if nameEnd == caret,
226+
let entry = table[name],
227+
let matched = directives.first(where: { $0.id == entry.id }),
228+
matched.syntax.parameters.allSatisfy({ !$0.isRequired }) {
229+
return nil
230+
}
231+
232+
let candidates = nameCandidates(prefix: name, table: table, directives: directives)
200233
guard !candidates.isEmpty else { return nil }
201234
return DirectiveCompletionContext(
202235
kind: .name,
203236
marker: Character(UnicodeScalar(marker) ?? "@"),
204237
prefix: name,
205-
replacementRange: NSRange(location: markerIndex, length: caret - markerIndex),
238+
replacementRange: NSRange(location: markerIndex, length: nameEnd - markerIndex),
206239
directiveID: nil,
207240
candidates: candidates
208241
)
@@ -301,6 +334,10 @@ enum DirectiveCompletionScanner {
301334
valueStart += 1
302335
}
303336
let prefix = ns.substring(with: NSRange(location: valueStart, length: caret - valueStart))
337+
// The value may continue past the caret (`@glyph(sta|r)`); a pick
338+
// there must replace the whole token or it leaves the tail dangling
339+
// behind the inserted candidate. Find where the value actually ends.
340+
let valueEnd = max(caret, valueTokenEnd(in: ns, from: valueStart))
304341

305342
// Resolve which parameter this is.
306343
let schema = directive.syntax.parameters
@@ -320,28 +357,62 @@ enum DirectiveCompletionScanner {
320357
kind: .argument(label: label, index: argumentIndex),
321358
marker: Character(UnicodeScalar(marker) ?? "@"),
322359
prefix: prefix,
323-
replacementRange: NSRange(location: valueStart, length: caret - valueStart),
360+
replacementRange: NSRange(location: valueStart, length: valueEnd - valueStart),
324361
directiveID: directive.id,
325362
candidates: candidates
326363
)
327364
}
328365

366+
/// Scan forward from `start` to find the end of the current argument
367+
/// value — the first unescaped, unquoted `,` or `)` at depth 0, a line
368+
/// break, or the end of the string. Mirrors the quote/depth tracking the
369+
/// backward scan in `argumentContext` already does, just forward.
370+
private static func valueTokenEnd(in ns: NSString, from start: Int) -> Int {
371+
var index = start
372+
var depth = 0
373+
var inQuote = false
374+
while index < ns.length {
375+
let c = ns.character(at: index)
376+
if c == 0x0A || c == 0x0D { return index }
377+
if c == quote, !isEscaped(index, ns) {
378+
inQuote.toggle()
379+
index += 1
380+
continue
381+
}
382+
if !inQuote, !isEscaped(index, ns) {
383+
if c == lparen { depth += 1 }
384+
if c == rparen {
385+
if depth == 0 { return index }
386+
depth -= 1
387+
}
388+
if c == comma, depth == 0 { return index }
389+
}
390+
index += 1
391+
}
392+
return ns.length
393+
}
394+
329395
// MARK: Name candidates
330396

331397
/// Registry-filtered directive names. The engine owns this ranking, so a
332398
/// newly registered directive shows up with no embedder change.
399+
///
400+
/// Candidates come from `table` — the registry's winning entries for
401+
/// this marker — not the raw configured `directives` list. The registry
402+
/// drops a directive with an empty name and resolves a duplicate name by
403+
/// "first registration wins"; sourcing candidates from the unfiltered
404+
/// list could offer a name the parser will never actually recognize.
333405
private static func nameCandidates(
334406
prefix: String,
335-
marker: unichar,
336-
directives: [any MarkdownDirective],
337-
settings: DirectiveRegistrySettings
407+
table: [String: DirectiveRegistry.Entry],
408+
directives: [any MarkdownDirective]
338409
) -> [DirectiveCompletionItem] {
339410
let needle = prefix.lowercased()
340-
let defaultMarker = settings.defaultMarker
341-
return directives
411+
let registered = table.values.compactMap { entry in
412+
directives.first { $0.id == entry.id }
413+
}
414+
return registered
342415
.filter { directive in
343-
let own = directive.syntax.marker ?? defaultMarker
344-
guard Array(String(own).utf16).first == marker else { return false }
345416
guard !needle.isEmpty else { return true }
346417
if directive.syntax.name.lowercased().hasPrefix(needle) { return true }
347418
return directive.completion.keywords.contains { $0.lowercased().hasPrefix(needle) }

‎Sources/MarkdownEngine/Directives/DirectiveScanner.swift‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ struct DirectiveMatch: Equatable {
4747
/// Inside the braces; `nil` for a self-contained call.
4848
let bodyRange: NSRange?
4949
/// Ranges that shrink when the caret leaves: `[prefix, closingBrace]` for
50-
/// a container, empty for a self-contained call (Phase 1 renders those
51-
/// literally — the glyph pass that collapses them lands in Phase 3).
50+
/// a container, empty for a self-contained call — there the whole call is
51+
/// the content, and the glyph pass collapses it at styling time.
5252
let markers: [NSRange]
5353
/// Range carrying the node's content: the body for a container, the whole
5454
/// call for a self-contained one.
@@ -150,11 +150,10 @@ enum DirectiveScanner {
150150
)
151151
}
152152

153-
// Self-contained: no markers in Phase 1, so the call renders as plain
154-
// literal text instead of collapsing to nothing. It is still CLAIMED,
155-
// so emphasis and autolinking can't fire inside it, and it still
156-
// projects a token — the glyph pass in Phase 3 only has to add
157-
// presentation.
153+
// Self-contained: no markers, so the whole call is the content. It is
154+
// CLAIMED, so emphasis and autolinking can't fire inside it, and it
155+
// projects a token like any other node — the glyph pass at styling
156+
// time only has to add presentation.
158157
return DirectiveMatch(
159158
nodeID: DirectiveRegistry.nodeID(for: entry.id),
160159
range: range,

‎Sources/MarkdownEngine/Directives/MarkdownDirective.swift‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@
1111
// Two forms, both TREE-SHAPED — a directive's effect never escapes its own
1212
// node:
1313
//
14-
// * self-contained — `@pagebreak`, `@date(format: iso)`. A leaf.
14+
// * self-contained — `@pagebreak`, `@date(format: iso)`. A leaf, drawn as
15+
// a glyph in place of its own source.
1516
// * container — `@font(size: 18){text}`. The body is re-parsed as
16-
// markdown and (from Phase 2) styled with the directive's font transform
17-
// COMPOSED over the inherited font, so `@font(size: 18){**bold**}` is
18-
// bold AND 18pt.
17+
// markdown and styled with the directive's font transform COMPOSED over
18+
// the inherited font, so `@font(size: 18){**bold**}` is bold AND 18pt.
1919
//
2020
// There is deliberately no "applies to everything after me" form. That would
2121
// make styling depend on document position rather than tree position, which
@@ -251,8 +251,8 @@ public struct DirectiveStyle {
251251
/// LaTeX uses), and the glyph is drawn by `MarkdownTextLayoutFragment`.
252252
/// "Markers shrink, they don't disappear" still holds.
253253
public enum DirectivePresentation {
254-
/// Style the source text only — no glyph. The default, and the only
255-
/// behaviour wired up in Phase 1.
254+
/// Style the source text only — no glyph. The default, and what a
255+
/// directive falls back to when its glyph can't be produced.
256256
case literal
257257
/// An SF Symbol drawn at the directive's position.
258258
case symbol(name: String, tint: NSColor?)
@@ -261,6 +261,14 @@ public enum DirectivePresentation {
261261
/// storage, so the source characters survive for selection and undo.
262262
case text(String)
263263
/// A pre-rendered image; `baselineOffset` matches the LaTeX convention.
264+
///
265+
/// Drawn at its own `image.size` — unlike `.symbol`/`.text`, which are
266+
/// always fit to `DirectiveContext.inheritedFont`, this case is not
267+
/// resized to the surrounding line. An image taller than the inherited
268+
/// font's line will overdraw neighbouring lines. Sizing it (typically
269+
/// to `inheritedFont.ascender - inheritedFont.descender`, or larger by
270+
/// deliberate choice, e.g. a thumbnail) is the directive's
271+
/// responsibility.
264272
case image(NSImage, baselineOffset: CGFloat)
265273
}
266274

0 commit comments

Comments
 (0)