Repository navigation
Expand file tree
/
Copy pathMarkdownInputHandler.swift
More file actions
162 lines (147 loc) · 7.23 KB
/
Copy pathMarkdownInputHandler.swift
File metadata and controls
162 lines (147 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
//
// MarkdownInputHandler.swift
// MarkdownEngine
//
// Created by Luca Chen on 18.02.26.
//
// Handles Markdown typing shortcuts, like continuing lists and keeping block
// LaTeX on its own line while you type.
import AppKit
enum MarkdownInputHandler {
/// `codeTokens` (codeBlock + inlineCode, from the keystroke's existing
/// parse) answers "is the caret in code?" without the O(doc) document
/// scan the handler otherwise runs on every space/Enter/Tab.
static func handleListInsertion(textView: NSTextView, affectedCharRange: NSRange, replacementString: String?, codeTokens: [MarkdownToken]? = nil) -> Bool {
let isInsideCodeBlock = codeTokens.map {
MarkdownDetection.isInsideCodeBlock(location: affectedCharRange.location, codeTokens: $0)
}
return MarkdownLists.handleInsertion(textView: textView, affectedCharRange: affectedCharRange,
replacementString: replacementString, isInsideCodeBlock: isInsideCodeBlock)
}
// MARK: - Block LaTeX Auto-Wrap
private static func insertTextProgrammatically(_ textView: NSTextView, text: String, at range: NSRange, cursorAfter: Int) {
if let coord = textView.delegate as? NativeTextViewWrapper.Coordinator {
coord.isProgrammaticEdit = true
// Replaces a suppressed keystroke that never applied — reset its
// pending count so this edit registers as the cycle's single
// tracked edit and textDidChange keeps the trusted fast paths.
coord.pendingEditCount = 0
}
textView.insertText(text, replacementRange: range)
if let coord = textView.delegate as? NativeTextViewWrapper.Coordinator {
coord.isProgrammaticEdit = false
}
textView.setSelectedRange(NSRange(location: cursorAfter, length: 0))
}
/// Keeps block LaTeX ($$...$$) on its own line by inserting newlines; returns true if handled.
static func handleBlockLatexAutoWrap(
textView: NSTextView,
affectedCharRange: NSRange,
replacementString: String?,
blockLatexTokens: [MarkdownToken]? = nil
) -> Bool {
let resolvedTokens: [MarkdownToken]
if let blockLatexTokens {
resolvedTokens = blockLatexTokens
} else {
resolvedTokens = MarkdownTokenizer.parseTokensViaAST(
in: textView.string,
registry: (textView as? NativeTextView)?.configuration.extensionRegistry ?? .empty
).filter { $0.kind == .blockLatex }
}
return handleBlockAutoWrap(textView: textView, affectedCharRange: affectedCharRange,
replacementString: replacementString, tokens: resolvedTokens)
}
/// Return inside a table row inserts `<br>` instead of splitting the row.
///
/// A GFM row is ONE source line, so a bare newline tears the table in half.
/// `<br>` is the format's only in-cell line break, and the renderer draws
/// it as one. Covers ⇧↵ too: AppKit sends the same `insertNewline:` for
/// both, so both arrive here as a `"\n"` replacement.
///
/// Deliberately NOT handled at the token's outer edges — Return at the very
/// start or end of the table stays a normal newline, which is the only way
/// out of a table that reaches the end of the document.
static func handleTableCellNewline(
textView: NSTextView,
affectedCharRange: NSRange,
replacementString: String?,
tableTokens: [MarkdownToken]
) -> Bool {
guard replacementString == "\n" else { return false }
let start = affectedCharRange.location
let end = NSMaxRange(affectedCharRange)
guard tableTokens.contains(where: { start > $0.range.location && end < NSMaxRange($0.range) })
else { return false }
let insertion = "<br>"
insertTextProgrammatically(
textView,
text: insertion,
at: affectedCharRange,
cursorAfter: start + (insertion as NSString).length
)
return true
}
/// Ensures image embeds (![[...]]) stay on their own line by automatically inserting newlines.
static func handleImageEmbedAutoWrap(
textView: NSTextView,
affectedCharRange: NSRange,
replacementString: String?,
imageEmbedTokens: [MarkdownToken]? = nil
) -> Bool {
let resolvedTokens: [MarkdownToken]
if let imageEmbedTokens {
resolvedTokens = imageEmbedTokens
} else {
resolvedTokens = MarkdownTokenizer.parseTokensViaAST(
in: textView.string,
registry: (textView as? NativeTextView)?.configuration.extensionRegistry ?? .empty
).filter { $0.kind == .imageEmbed }
}
return handleBlockAutoWrap(textView: textView, affectedCharRange: affectedCharRange,
replacementString: replacementString, tokens: resolvedTokens)
}
/// Shared auto-wrap logic: ensures a block-level token stays on its own line.
private static func handleBlockAutoWrap(
textView: NSTextView,
affectedCharRange: NSRange,
replacementString: String?,
tokens: [MarkdownToken]
) -> Bool {
guard let replacement = replacementString,
!replacement.isEmpty,
replacement != "\n" else { return false }
let text = textView.string as NSString
let newlineChar = UInt16(("\n" as Character).asciiValue!)
for token in tokens {
let tokenEnd = NSMaxRange(token.range)
// Typing right after closing marker
if affectedCharRange.location == tokenEnd {
if tokenEnd < text.length && text.character(at: tokenEnd) == newlineChar {
insertTextProgrammatically(textView, text: replacement,
at: NSRange(location: tokenEnd + 1, length: 0),
cursorAfter: tokenEnd + 1 + replacement.utf16.count)
} else {
insertTextProgrammatically(textView, text: "\n" + replacement,
at: affectedCharRange,
cursorAfter: affectedCharRange.location + 1 + replacement.utf16.count)
}
return true
}
// Typing right before opening marker
if affectedCharRange.location == token.range.location {
if token.range.location > 0 && text.character(at: token.range.location - 1) == newlineChar {
insertTextProgrammatically(textView, text: replacement,
at: NSRange(location: token.range.location - 1, length: 0),
cursorAfter: token.range.location - 1 + replacement.utf16.count)
} else {
insertTextProgrammatically(textView, text: replacement + "\n",
at: affectedCharRange,
cursorAfter: affectedCharRange.location + replacement.utf16.count)
}
return true
}
}
return false
}
}