Skip to content

Commit 72ff697

Browse files
committed
fix(web): keep Windows path autolinks out of emphasis and tasks
Task checkbox offsets were taken from the rewritten markdown source, so toggles could miss the original file. Bare-path autolinks also ate emphasis stars and rewrote indented or mid-line-fenced code. Search markers in the original text, stop paths at *, and skip indented code plus fence closers that are not on their own line.
1 parent 097c0d2 commit 72ff697

5 files changed

Lines changed: 176 additions & 19 deletions

File tree

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ import {
8181
rewriteMarkdownFileUriHref,
8282
type MarkdownFileLinkMeta,
8383
} from "../markdown-links";
84+
import { findTaskListMarkerOffset } from "../markdown-task-list";
8485
import { readLocalApi } from "../localApi";
8586
import { cn } from "../lib/utils";
8687
import { useRightPanelStore } from "../rightPanelStore";
@@ -146,17 +147,6 @@ const highlightedCodeCache = new LRUCache<string>(
146147
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
147148
);
148149

149-
function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {
150-
const firstLineEnd = markdown.indexOf("\n", listItemStart);
151-
const firstLine = markdown.slice(
152-
listItemStart,
153-
firstLineEnd === -1 ? markdown.length : firstLineEnd,
154-
);
155-
const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/);
156-
if (!match?.[1]) return null;
157-
return listItemStart + firstLine.indexOf(match[1]);
158-
}
159-
160150
/**
161151
* The default `1.25rem` marker gutter (`.chat-markdown ol`) fits two-digit
162152
* decimal markers. Once a list's last item reaches three digits (item 100+),
@@ -1592,7 +1582,7 @@ function ChatMarkdown({
15921582
const listItemStart = node?.position?.start.offset;
15931583
const markerOffset =
15941584
typeof listItemStart === "number"
1595-
? findTaskListMarkerOffset(markdownSource, listItemStart)
1585+
? findTaskListMarkerOffset(text, listItemStart, markdownSource)
15961586
: null;
15971587
return (
15981588
<li {...props} data-task-marker-offset={markerOffset ?? undefined}>
@@ -1777,6 +1767,7 @@ function ChatMarkdown({
17771767
markdownFileLinkMetaByHref,
17781768
markdownSource,
17791769
onTaskListChange,
1770+
text,
17801771
openFileInPanel,
17811772
openInPreferredEditor,
17821773
openExternalLinkInPreview,

‎apps/web/src/markdown-links.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,27 @@ describe("normalizeWindowsMarkdownFileLinks", () => {
243243
"See [M:\\batches\\issue-40-v1\\docs\\prompt.md](file:///M:/batches/issue-40-v1/docs/prompt.md).",
244244
);
245245
});
246+
247+
it("does not consume emphasis markers around a bare windows path", () => {
248+
expect(normalizeWindowsMarkdownFileLinks("**D:\\foo.md**")).toBe(
249+
"**[D:\\foo.md](file:///D:/foo.md)**",
250+
);
251+
});
252+
253+
it("does not rewrite indented code or fenced code with a mid-line fence sequence", () => {
254+
const indented = " D:\\tmp\\file.md";
255+
const tabIndented = "\tD:\\tmp\\file.md";
256+
const fencedMidline = '```\nconst s = "```";\nD:\\tmp\\file.md\n```';
257+
expect(normalizeWindowsMarkdownFileLinks(indented)).toBe(indented);
258+
expect(normalizeWindowsMarkdownFileLinks(tabIndented)).toBe(tabIndented);
259+
expect(normalizeWindowsMarkdownFileLinks(fencedMidline)).toBe(fencedMidline);
260+
});
261+
262+
it("still autolinks a path after a closed fence", () => {
263+
expect(normalizeWindowsMarkdownFileLinks("```\ncode\n```\nD:\\tmp\\file.md")).toBe(
264+
"```\ncode\n```\n[D:\\tmp\\file.md](file:///D:/tmp/file.md)",
265+
);
266+
});
246267
});
247268

248269
describe("resolveInlineCodeFileLinkMeta", () => {

‎apps/web/src/markdown-links.ts‎

Lines changed: 67 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -140,13 +140,13 @@ const MARKDOWN_LINK_DEFINITION_PATTERN =
140140
const ANGLE_AUTOLINK_PATTERN = /<([^<>\n]+)>/g;
141141
const PROTECTED_MARKDOWN_SPAN_PATTERN = /!?\[[^\]]*]\([^)]*\)|!?\[[^\]]*]\[[^\]]*]|<[^>\n]+>/g;
142142
const BARE_WINDOWS_PATH_PATTERN =
143-
/(?<![A-Za-z0-9_/])(?:[A-Za-z]:[\\/][^\s<>[\]()`]+|\\\\[^\s<>[\]()`\\/]+(?:[\\/][^\s<>[\]()`]+)+)/g;
143+
/(?<![A-Za-z0-9_/])(?:[A-Za-z]:[\\/][^\s<>[\]()`*]+|\\\\[^\s<>[\]()`*\\/]+(?:[\\/][^\s<>[\]()`*]+)+)/g;
144144
const AUTOLINK_TRAILING_PUNCTUATION_PATTERN = /[.,;:!?')\]}"]+$/;
145145

146146
/**
147147
* Rewrites Windows drive/UNC markdown destinations and bare paths to `file://`
148148
* URLs so rehype-sanitize does not treat `D:` as an unknown protocol.
149-
* Leaves fenced code, inline code, and non-file links alone.
149+
* Leaves fenced code, indented code, inline code, and non-file links alone.
150150
*/
151151
export function normalizeWindowsMarkdownFileLinks(markdown: string): string {
152152
if (markdown.length === 0 || !HAS_WINDOWS_FILESYSTEM_PATH_PATTERN.test(markdown)) {
@@ -258,8 +258,9 @@ function rewriteWindowsMarkdownInText(text: string): string {
258258
return autolinkBareWindowsPaths(rewriteWindowsAngleAutolinks(withDestinations));
259259
}
260260

261-
const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$))/;
262261
const INLINE_CODE_SEGMENT_PATTERN = /(`[^`\n]+`)/;
262+
const OPEN_FENCE_PATTERN = /^( {0,3})(`{3,}|~{3,})(.*)$/;
263+
const CLOSE_FENCE_PATTERN = /^( {0,3})(`{3,}|~{3,})[ \t]*$/;
263264

264265
function mapOutsideInlineCode(text: string, transform: (chunk: string) => string): string {
265266
return text
@@ -268,11 +269,70 @@ function mapOutsideInlineCode(text: string, transform: (chunk: string) => string
268269
.join("");
269270
}
270271

272+
function lineWithoutCarriageReturn(line: string): string {
273+
return line.endsWith("\r") ? line.slice(0, -1) : line;
274+
}
275+
276+
function openingFenceMarker(line: string): string | null {
277+
const match = OPEN_FENCE_PATTERN.exec(line);
278+
if (!match?.[2]) return null;
279+
const marker = match[2];
280+
const info = match[3] ?? "";
281+
if (marker.startsWith("`") && info.includes("`")) return null;
282+
return marker;
283+
}
284+
285+
function isClosingFenceLine(line: string, openMarker: string): boolean {
286+
const match = CLOSE_FENCE_PATTERN.exec(line);
287+
if (!match?.[2]) return false;
288+
const marker = match[2];
289+
return marker[0] === openMarker[0] && marker.length >= openMarker.length;
290+
}
291+
292+
function isIndentedCodeLine(line: string): boolean {
293+
return line.startsWith(" ") || line.startsWith("\t");
294+
}
295+
271296
function mapMarkdownOutsideCode(markdown: string, transform: (text: string) => string): string {
272-
return markdown
273-
.split(FENCED_CODE_SEGMENT_PATTERN)
274-
.map((segment, index) => (index % 2 === 1 ? segment : mapOutsideInlineCode(segment, transform)))
275-
.join("");
297+
let output = "";
298+
let index = 0;
299+
let openFence: string | null = null;
300+
301+
while (index < markdown.length) {
302+
const lineEnd = markdown.indexOf("\n", index);
303+
const lineLimit = lineEnd === -1 ? markdown.length : lineEnd;
304+
const line = markdown.slice(index, lineLimit);
305+
const newline = lineEnd === -1 ? "" : "\n";
306+
const matchLine = lineWithoutCarriageReturn(line);
307+
308+
if (openFence !== null) {
309+
output += line + newline;
310+
if (isClosingFenceLine(matchLine, openFence)) {
311+
openFence = null;
312+
}
313+
index = lineLimit + newline.length;
314+
continue;
315+
}
316+
317+
const fence = openingFenceMarker(matchLine);
318+
if (fence !== null) {
319+
openFence = fence;
320+
output += line + newline;
321+
index = lineLimit + newline.length;
322+
continue;
323+
}
324+
325+
if (isIndentedCodeLine(matchLine)) {
326+
output += line + newline;
327+
index = lineLimit + newline.length;
328+
continue;
329+
}
330+
331+
output += mapOutsideInlineCode(line, transform) + newline;
332+
index = lineLimit + newline.length;
333+
}
334+
335+
return output;
276336
}
277337

278338
function looksLikePosixFilesystemPath(path: string): boolean {
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { setMarkdownTaskChecked } from "./components/files/filePreviewMode";
4+
import { normalizeWindowsMarkdownFileLinks } from "./markdown-links";
5+
import { findTaskListMarkerOffset } from "./markdown-task-list";
6+
7+
describe("findTaskListMarkerOffset", () => {
8+
it("uses the original text when a windows rewrite shifts later offsets", () => {
9+
const original = "See D:\\tmp\\file.md\n- [ ] later";
10+
const parsed = normalizeWindowsMarkdownFileLinks(original);
11+
const parsedListItemStart = parsed.indexOf("- [ ]");
12+
expect(parsedListItemStart).toBeGreaterThan(original.indexOf("- [ ]"));
13+
14+
const markerOffset = findTaskListMarkerOffset(original, parsedListItemStart, parsed);
15+
expect(markerOffset).toBe(original.indexOf("["));
16+
expect(setMarkdownTaskChecked(original, markerOffset!, true)).toBe(
17+
"See D:\\tmp\\file.md\n- [x] later",
18+
);
19+
});
20+
21+
it("keeps the checkbox offset when the rewrite is after the marker", () => {
22+
const original = "- [ ] Open D:\\tmp\\file.md";
23+
const parsed = normalizeWindowsMarkdownFileLinks(original);
24+
const markerOffset = findTaskListMarkerOffset(original, 0, parsed);
25+
expect(markerOffset).toBe(2);
26+
expect(setMarkdownTaskChecked(original, markerOffset!, true)).toBe(
27+
"- [x] Open D:\\tmp\\file.md",
28+
);
29+
});
30+
});

‎apps/web/src/markdown-task-list.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
function lineIndexAtOffset(source: string, offset: number): number {
2+
let line = 0;
3+
const limit = Math.min(Math.max(offset, 0), source.length);
4+
for (let i = 0; i < limit; i++) {
5+
if (source.charCodeAt(i) === 10) line++;
6+
}
7+
return line;
8+
}
9+
10+
function lineStartOffset(source: string, lineIndex: number): number {
11+
if (lineIndex <= 0) return 0;
12+
let line = 0;
13+
for (let i = 0; i < source.length; i++) {
14+
if (source.charCodeAt(i) === 10) {
15+
line++;
16+
if (line === lineIndex) return i + 1;
17+
}
18+
}
19+
return source.length;
20+
}
21+
22+
function taskListMarkerStart(markdown: string, listItemStart: number): number | null {
23+
const firstLineEnd = markdown.indexOf("\n", listItemStart);
24+
const firstLine = markdown.slice(
25+
listItemStart,
26+
firstLineEnd === -1 ? markdown.length : firstLineEnd,
27+
);
28+
const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/);
29+
if (!match?.[1]) return null;
30+
return listItemStart + firstLine.indexOf(match[1]);
31+
}
32+
33+
/**
34+
* Task clicks mutate `markdown` (the raw message/file). `listItemStart` comes
35+
* from the parsed tree, which may be a rewritten source whose earlier offsets
36+
* no longer match.
37+
*/
38+
export function findTaskListMarkerOffset(
39+
markdown: string,
40+
listItemStart: number,
41+
parsedMarkdown: string = markdown,
42+
): number | null {
43+
if (
44+
parsedMarkdown === markdown ||
45+
(listItemStart <= markdown.length &&
46+
markdown.startsWith(parsedMarkdown.slice(0, listItemStart)))
47+
) {
48+
return taskListMarkerStart(markdown, listItemStart);
49+
}
50+
51+
return taskListMarkerStart(
52+
markdown,
53+
lineStartOffset(markdown, lineIndexAtOffset(parsedMarkdown, listItemStart)),
54+
);
55+
}

0 commit comments

Comments
 (0)