forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown.ts
More file actions
271 lines (245 loc) · 8.04 KB
/
Copy pathmarkdown.ts
File metadata and controls
271 lines (245 loc) · 8.04 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
export function completePartialMarkdown(input: string): string {
let s = input;
// Handle code fences first - use FIRST unmatched fence for proper nesting
const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
if (fenceMatches.length % 2 === 1) {
const [, indent, fence] = fenceMatches[0]!;
s += `\n${indent}${fence}`;
}
// Identify incomplete links at the end and close them
const incompleteLinkMatch = s.match(/\[([^\]]*)\]\(([^)]*)$/);
if (incompleteLinkMatch) {
s += ")";
}
// State-based parsing
interface OpenElement {
type: string;
marker: string;
position: number;
}
const openElements: OpenElement[] = [];
const chars = Array.from(s);
// First pass: identify code block boundaries and inline code to avoid processing their content
const codeBlockRanges: Array<{ start: number; end: number }> = [];
const inlineCodeRanges: Array<{ start: number; end: number }> = [];
// Find code block ranges
let tempCodeFenceCount = 0;
let currentCodeBlockStart = -1;
for (let i = 0; i < chars.length; i++) {
if (i === 0 || chars[i - 1] === "\n") {
const lineMatch = s.substring(i).match(/^(\s*)(`{3,}|~{3,})/);
if (lineMatch) {
tempCodeFenceCount++;
if (tempCodeFenceCount % 2 === 1) {
currentCodeBlockStart = i;
} else if (currentCodeBlockStart !== -1) {
codeBlockRanges.push({
start: currentCodeBlockStart,
end: i + lineMatch[0].length,
});
currentCodeBlockStart = -1;
}
i += lineMatch[0].length - 1;
}
}
}
// Find inline code ranges
for (let i = 0; i < chars.length; i++) {
if (chars[i] === "`") {
// Check if escaped
let backslashCount = 0;
for (let j = i - 1; j >= 0 && chars[j] === "\\"; j--) {
backslashCount++;
}
if (backslashCount % 2 === 0) {
// Not escaped - find the closing backtick
for (let j = i + 1; j < chars.length; j++) {
if (chars[j] === "`") {
let closingBackslashCount = 0;
for (let k = j - 1; k >= 0 && chars[k] === "\\"; k--) {
closingBackslashCount++;
}
if (closingBackslashCount % 2 === 0) {
inlineCodeRanges.push({ start: i, end: j + 1 });
i = j;
break;
}
}
}
}
}
}
// Helper function to check if position is in code
const isInCode = (pos: number): boolean => {
return (
codeBlockRanges.some((range) => pos >= range.start && pos < range.end) ||
inlineCodeRanges.some((range) => pos >= range.start && pos < range.end)
);
};
// Second pass: process markdown elements, skipping code regions
for (let i = 0; i < chars.length; i++) {
const char = chars[i];
const nextChar = chars[i + 1];
const prevChar = chars[i - 1];
if (isInCode(i)) {
continue;
}
// Handle brackets (but not if they're part of already-complete links)
if (char === "[") {
// Check if this is part of a complete link [text](url)
let isCompleteLink = false;
let bracketDepth = 1;
let j = i + 1;
// Find the matching ]
while (j < chars.length && bracketDepth > 0) {
if (chars[j] === "[" && !isInCode(j)) bracketDepth++;
if (chars[j] === "]" && !isInCode(j)) bracketDepth--;
j++;
}
// Check if followed by (
if (bracketDepth === 0 && chars[j] === "(") {
// Find the closing )
let parenDepth = 1;
j++;
while (j < chars.length && parenDepth > 0) {
if (chars[j] === "(" && !isInCode(j)) parenDepth++;
if (chars[j] === ")" && !isInCode(j)) parenDepth--;
j++;
}
if (parenDepth === 0) {
isCompleteLink = true;
i = j - 1;
continue;
}
}
// This is a standalone bracket, treat as markdown
if (!isCompleteLink) {
const existingIndex = openElements.findIndex(
(el) => el.type === "bracket",
);
if (existingIndex !== -1) {
openElements.splice(existingIndex, 1);
} else {
openElements.push({ type: "bracket", marker: "[", position: i });
}
}
}
// Handle double emphasis first (**, __, ~~) - these take precedence
else if (char === "*" && nextChar === "*") {
const existingIndex = openElements.findIndex(
(el) => el.type === "bold_star",
);
if (existingIndex !== -1) {
openElements.splice(existingIndex, 1);
} else {
openElements.push({ type: "bold_star", marker: "**", position: i });
}
i++; // Skip next character
} else if (char === "_" && nextChar === "_") {
const existingIndex = openElements.findIndex(
(el) => el.type === "bold_underscore",
);
if (existingIndex !== -1) {
openElements.splice(existingIndex, 1);
} else {
openElements.push({
type: "bold_underscore",
marker: "__",
position: i,
});
}
i++; // Skip next character
} else if (char === "~" && nextChar === "~") {
const existingIndex = openElements.findIndex(
(el) => el.type === "strike",
);
if (existingIndex !== -1) {
openElements.splice(existingIndex, 1);
} else {
openElements.push({ type: "strike", marker: "~~", position: i });
}
i++; // Skip next character
}
// Handle single emphasis (*, _) - only if not part of double
else if (char === "*" && prevChar !== "*" && nextChar !== "*") {
const existingIndex = openElements.findIndex(
(el) => el.type === "italic_star",
);
if (existingIndex !== -1) {
openElements.splice(existingIndex, 1);
} else {
openElements.push({ type: "italic_star", marker: "*", position: i });
}
} else if (char === "_" && prevChar !== "_" && nextChar !== "_") {
const existingIndex = openElements.findIndex(
(el) => el.type === "italic_underscore",
);
if (existingIndex !== -1) {
openElements.splice(existingIndex, 1);
} else {
openElements.push({
type: "italic_underscore",
marker: "_",
position: i,
});
}
}
}
// Handle remaining unmatched backticks (outside of inline code ranges)
let backtickCount = 0;
for (let i = 0; i < chars.length; i++) {
if (chars[i] === "`" && !isInCode(i)) {
backtickCount++;
}
}
if (backtickCount % 2 === 1) {
s += "`";
}
// Close remaining open elements in reverse order (LIFO stack semantics)
openElements.sort((a, b) => b.position - a.position);
const closers = openElements.map((el) => {
switch (el.type) {
case "bracket":
return "]";
case "bold_star":
return "**";
case "bold_underscore":
return "__";
case "strike":
return "~~";
case "italic_star":
return "*";
case "italic_underscore":
return "_";
default:
return "";
}
});
let result = s + closers.join("");
// Handle parentheses ONLY if not inside code
const finalFenceMatches = Array.from(
result.matchAll(/^(\s*)(`{3,}|~{3,})/gm),
);
const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;
const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;
let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;
if (shouldCloseParens) {
const lastOpenParen = result.lastIndexOf("(");
if (lastOpenParen !== -1) {
// Check if this paren is inside a backtick pair
const beforeParen = result.substring(0, lastOpenParen);
const backticksBeforeParen = (beforeParen.match(/`/g) || []).length;
if (backticksBeforeParen % 2 === 1) {
shouldCloseParens = false;
}
}
}
if (shouldCloseParens) {
const openParens = (result.match(/\(/g) || []).length;
const closeParens = (result.match(/\)/g) || []).length;
if (openParens > closeParens) {
result += ")".repeat(openParens - closeParens);
}
}
return result;
}