Elffuss BraidHub

kikocis/continue public

Merge pull request #5624 from chezsmithy/fix-markdown-creation

fix: :bug: fixing issues with creating markdown files
Changesetf0151a205aa04efd24aa0b6eed9d36c8c19ff0686e03f94c749699bfa078ca89
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-05-13 13:14 -07:00
CommitterGitHub <noreply@github.com> · 2025-05-13 13:14 -07:00
Parentsbc51ed747091, b3745c83ccc6

Browse the files at this changeset

6 files changed

modified core/autocomplete/filtering/streamTransforms/lineStream.test.ts +81 −1
@@ -2,6 +2,7 @@
22
33 import * as lineStream from "./lineStream";
44
5+// eslint-disable-next-line max-lines-per-function
56 describe("lineStream", () => {
67 let mockFullStop: jest.Mock;
78
@@ -204,6 +205,33 @@
204205 });
205206
206207 describe("filterCodeBlockLines", () => {
208+ it("should handle unfenced code", async () => {
209+ const linesGenerator = await getLineGenerator(["const x = 5;"]);
210+
211+ const result = lineStream.filterCodeBlockLines(linesGenerator);
212+ const filteredLines = await getFilteredLines(result);
213+
214+ expect(filteredLines).toEqual(["const x = 5;"]);
215+ });
216+
217+ it("should handle unfenced code with a code block", async () => {
218+ const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]);
219+
220+ const result = lineStream.filterCodeBlockLines(linesGenerator);
221+ const filteredLines = await getFilteredLines(result);
222+
223+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
224+ });
225+
226+ it("should handle unfenced code with two code blocks", async () => {
227+ const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
228+
229+ const result = lineStream.filterCodeBlockLines(linesGenerator);
230+ const filteredLines = await getFilteredLines(result);
231+
232+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
233+ });
234+
207235 it("should remove lines before the first valid line", async () => {
208236 const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
209237
@@ -213,7 +241,59 @@
213241 expect(filteredLines).toEqual(["const x = 5;"]);
214242 });
215243
216- it.todo("Need some sample inputs to properly test this");
244+ it("should remove outer blocks", async () => {
245+ const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]);
246+
247+ const result = lineStream.filterCodeBlockLines(linesGenerator);
248+ const filteredLines = await getFilteredLines(result);
249+
250+ expect(filteredLines).toEqual(["const x = 5;"]);
251+ });
252+
253+ it("should leave inner blocks intact", async () => {
254+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]);
255+
256+ const result = lineStream.filterCodeBlockLines(linesGenerator);
257+ const filteredLines = await getFilteredLines(result);
258+
259+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
260+ });
261+
262+ it("should handle included inner ticks", async () => {
263+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]);
264+
265+ const result = lineStream.filterCodeBlockLines(linesGenerator);
266+ const filteredLines = await getFilteredLines(result);
267+
268+ expect(filteredLines).toEqual(["const x = 5;","```bash","echo ```test```","```"]);
269+ });
270+
271+ it("should leave single inner blocks intact but not return trailing text", async () => {
272+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```","trailing text"]);
273+
274+ const result = lineStream.filterCodeBlockLines(linesGenerator);
275+ const filteredLines = await getFilteredLines(result);
276+
277+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
278+ });
279+
280+ it("should leave double inner blocks intact but not return trailing text", async () => {
281+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```","```","trailing text"]);
282+
283+ const result = lineStream.filterCodeBlockLines(linesGenerator);
284+ const filteredLines = await getFilteredLines(result);
285+
286+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```"]);
287+ });
288+
289+ it("should leave inner blocks intact but not return trailing or leading text", async () => {
290+ const linesGenerator = await getLineGenerator(["[CODE]", "const x = 5;", "```bash","ls -al","```","[/CODE]","trailing text"]);
291+
292+ const result = lineStream.filterCodeBlockLines(linesGenerator);
293+ const filteredLines = await getFilteredLines(result);
294+
295+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
296+ });
217297 });
218298
219299 describe("filterEnglishLinesAtStart", () => {
modified core/autocomplete/filtering/streamTransforms/lineStream.ts +40 −26
@@ -55,8 +55,8 @@
5555 return line;
5656 }
5757
58- if (line.includes(CODE_START_BLOCK)) {
59- return line.split(CODE_START_BLOCK)[0].trimEnd();
58+ if (line.includes(CODE_STOP_BLOCK)) {
59+ return line.split(CODE_STOP_BLOCK)[0].trimEnd();
6060 }
6161
6262 return undefined;
@@ -71,9 +71,9 @@
7171 return hasUselessLine || trimmed.startsWith("// end");
7272 }
7373
74-export const USELESS_LINES = ["", "```"];
74+export const USELESS_LINES = [""];
7575 export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
76-export const CODE_START_BLOCK = "[/CODE]";
76+export const CODE_STOP_BLOCK = "[/CODE]";
7777 export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
7878 export const PREFIXES_TO_SKIP = ["<COMPLETION>"];
7979 export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
@@ -343,34 +343,48 @@
343343 * 4. Yields processed lines that are part of the actual code block content.
344344 */
345345 export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
346- let seenValidLine = false;
347- let waitingToSeeIfLineIsLast = undefined;
346+ let seenFirstFence = false;
347+ // nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
348+ // when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
349+ // when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
350+ let nestCount = 0;
348351
349352 for await (const line of rawLines) {
350- // Filter out starting ```
351- if (!seenValidLine) {
353+
354+
355+ if (!seenFirstFence) {
352356 if (shouldRemoveLineBeforeStart(line)) {
353- continue;
357+ // Filter out starting ``` or START block
358+ continue
354359 }
355- seenValidLine = true;
356- }
357-
358- // Filter out ending ```
359- if (typeof waitingToSeeIfLineIsLast !== "undefined") {
360- yield waitingToSeeIfLineIsLast;
361- waitingToSeeIfLineIsLast = undefined;
360+ // Regardless of a fence or START block start tracking the nesting level
361+ seenFirstFence = true;
362+ nestCount = 1;
362363 }
363364
364- const changedEndLine = shouldChangeLineAndStop(line);
365- if (typeof changedEndLine === "string") {
366- yield changedEndLine;
367- return;
368- }
369-
370- if (line.startsWith("```")) {
371- waitingToSeeIfLineIsLast = line;
372- } else {
373- yield line;
365+ if (nestCount > 0) {
366+ // Inside a block including the outer block
367+ const changedEndLine = shouldChangeLineAndStop(line);
368+ if (typeof changedEndLine === "string") {
369+ // Ending a block with just backticks (```) or STOP
370+ nestCount--;
371+ if (nestCount === 0) {
372+ // if we are closing the outer block then exit early
373+ // only exit early if the outer block was started with a block
374+ // it it was text, we will never exit early
375+ return;
376+ } else {
377+ // otherwise just yield the line
378+ yield line;
379+ }
380+ } else if (line.startsWith("```")) {
381+ // Going into a nested codeblock
382+ nestCount++;
383+ yield line;
384+ } else {
385+ // otherwise just yield the line
386+ yield line;
387+ }
374388 }
375389 }
376390 }
added gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts +65 −0
@@ -0,0 +1,65 @@
1+import { headerIsMarkdown } from './headerIsMarkdown';
2+
3+describe('headerIsMarkdown', () => {
4+ // Test exact match with common Markdown identifiers
5+ it('should identify exact matches with common Markdown identifiers', () => {
6+ expect(headerIsMarkdown('md')).toBe(true);
7+ expect(headerIsMarkdown('markdown')).toBe(true);
8+ expect(headerIsMarkdown('gfm')).toBe(true);
9+ expect(headerIsMarkdown('github-markdown')).toBe(true);
10+ });
11+
12+ // Test identifiers preceded by a space
13+ it('should identify identifiers preceded by a space', () => {
14+ expect(headerIsMarkdown('lang md')).toBe(true);
15+ expect(headerIsMarkdown('something markdown')).toBe(true);
16+ expect(headerIsMarkdown('language gfm')).toBe(true);
17+ expect(headerIsMarkdown('spec github-markdown')).toBe(true);
18+ });
19+
20+ // Test file extensions
21+ it('should identify file names with markdown extensions', () => {
22+ expect(headerIsMarkdown('example.md')).toBe(true);
23+ expect(headerIsMarkdown('document.markdown')).toBe(true);
24+ expect(headerIsMarkdown('readme.gfm')).toBe(true);
25+ });
26+
27+ // Test more complex cases with extensions
28+ it('should identify file names with markdown extensions followed by other text', () => {
29+ expect(headerIsMarkdown('example.md additional text')).toBe(true);
30+ expect(headerIsMarkdown('document.markdown with some description')).toBe(true);
31+ expect(headerIsMarkdown('readme.gfm v2.0')).toBe(true);
32+ });
33+
34+ // Test non-markdown cases
35+ it('should not identify non-markdown headers', () => {
36+ expect(headerIsMarkdown('javascript')).toBe(false);
37+ expect(headerIsMarkdown('typescript')).toBe(false);
38+ expect(headerIsMarkdown('plain')).toBe(false);
39+ expect(headerIsMarkdown('python')).toBe(false);
40+ });
41+
42+ // Test edge cases
43+ it('should handle edge cases correctly', () => {
44+ expect(headerIsMarkdown('')).toBe(false);
45+ expect(headerIsMarkdown('mdx')).toBe(false); // Similar but not exactly "md"
46+ expect(headerIsMarkdown('readme md')).toBe(true);
47+ expect(headerIsMarkdown('md.js')).toBe(false); // "md" is not the extension
48+ });
49+
50+ // Test case sensitivity
51+ it('should respect case sensitivity', () => {
52+ expect(headerIsMarkdown('MD')).toBe(false);
53+ expect(headerIsMarkdown('MARKDOWN')).toBe(false);
54+ expect(headerIsMarkdown('example.MD')).toBe(false);
55+ expect(headerIsMarkdown('lang MD')).toBe(false);
56+ });
57+
58+ // Test with special characters and spacing
59+ it('should handle special characters and spacing correctly', () => {
60+ expect(headerIsMarkdown(' md')).toBe(true); // Space before "md"
61+ expect(headerIsMarkdown('md ')).toBe(true); // Space after "md"
62+ expect(headerIsMarkdown('hello-md')).toBe(false); // "md" with hyphen prefix
63+ expect(headerIsMarkdown('markdown:')).toBe(false); // "markdown" with suffix
64+ });
65+});
No newline at the end of the file
added gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts +26 −0
@@ -0,0 +1,26 @@
1+/**
2+ * Determines if a given header string represents Markdown content.
3+ *
4+ * The function checks various patterns to identify Markdown headers:
5+ * - Exact match with common Markdown identifiers (md, markdown, gfm, github-markdown)
6+ * - Contains these identifiers preceded by a space
7+ * - First word has a file extension of md, markdown, or gfm
8+ *
9+ * @param header - The string to check for Markdown indicators
10+ * @returns True if the header represents Markdown content, false otherwise
11+ */
12+export function headerIsMarkdown(header: string): boolean {
13+ return (
14+ header === "md" ||
15+ header === "markdown" ||
16+ header === "gfm" ||
17+ header === "github-markdown" ||
18+ header.includes(" md") ||
19+ header.includes(" markdown") ||
20+ header.includes(" gfm") ||
21+ header.includes(" github-markdown") ||
22+ (header.split(" ")[0]?.split(".").pop() === "md") ||
23+ (header.split(" ")[0]?.split(".").pop() === "markdown") ||
24+ (header.split(" ")[0]?.split(".").pop() === "gfm")
25+ );
26+}
No newline at the end of the file
added gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts +105 −0
@@ -0,0 +1,105 @@
1+import { patchNestedMarkdown } from './patchNestedMarkdown';
2+
3+describe('patchNestedMarkdown', () => {
4+ it('should return unchanged content when no markdown codeblocks are present', () => {
5+ const source = 'Regular text\n```javascript\nconsole.log("hello");\n```';
6+ expect(patchNestedMarkdown(source)).toBe(source);
7+ });
8+
9+ it('should replace backticks with tildes for markdown codeblocks', () => {
10+ const source = '```markdown\n# Header\nSome text\n```';
11+ const expected = '~~~markdown\n# Header\nSome text\n~~~';
12+ expect(patchNestedMarkdown(source)).toBe(expected);
13+ });
14+
15+ it('should handle nested codeblocks within markdown blocks', () => {
16+ const source = '```markdown\n# Example\n```js\nconsole.log("nested");\n```\n```';
17+ const expected = '~~~markdown\n# Example\n```js\nconsole.log("nested");\n```\n~~~';
18+ expect(patchNestedMarkdown(source)).toBe(expected);
19+ });
20+
21+ it('should handle .md file extension', () => {
22+ const source = '```test.md\nContent\n```';
23+ const expected = '~~~test.md\nContent\n~~~';
24+ expect(patchNestedMarkdown(source)).toBe(expected);
25+ });
26+
27+ it('should handle multiple levels of nesting', () => {
28+ const source = '```markdown\n# Doc\n```js\nlet x = "```nested```";\n```\n```';
29+ const expected = '~~~markdown\n# Doc\n```js\nlet x = "```nested```";\n```\n~~~';
30+ expect(patchNestedMarkdown(source)).toBe(expected);
31+ });
32+
33+ it('should handle blocks that start with md', () => {
34+ const source = '```md\n# Header\nSome text\n```';
35+ const expected = '~~~md\n# Header\nSome text\n~~~';
36+ expect(patchNestedMarkdown(source)).toBe(expected);
37+ });
38+
39+ it('should handle blocks with language specifier followed by md', () => {
40+ const source = '```lang md\n# Header\nSome text\n```';
41+ const expected = '~~~lang md\n# Header\nSome text\n~~~';
42+ expect(patchNestedMarkdown(source)).toBe(expected);
43+ });
44+
45+ it('should handle blocks with language specifier followed by markdown', () => {
46+ const source = '```lang markdown\n# Header\nSome text\n```';
47+ const expected = '~~~lang markdown\n# Header\nSome text\n~~~';
48+ expect(patchNestedMarkdown(source)).toBe(expected);
49+ });
50+
51+ it('should not replace backticks for non-markdown file extensions', () => {
52+ const source = '```test.js\nContent\n```';
53+ expect(patchNestedMarkdown(source)).toBe(source);
54+ });
55+
56+ it('should check the file extension branch when extension is not md/markdown/gfm', () => {
57+ // This tests the extension check branch with an unrecognized extension
58+ const source = '```test.txt\nContent with md keyword\n```';
59+ expect(patchNestedMarkdown(source)).toBe(source);
60+ });
61+
62+ it('should handle empty file name in code block header', () => {
63+ // This covers the branch where file is empty or undefined
64+ const source = '``` \nSome content\n```';
65+ expect(patchNestedMarkdown(source)).toBe(source);
66+ });
67+
68+ it('should handle file names with no extension', () => {
69+ // This covers the branch where ext might be undefined
70+ const source = '```filename\nContent\n```';
71+ expect(patchNestedMarkdown(source)).toBe(source);
72+ });
73+
74+ it('should correctly identify .markdown extension', () => {
75+ // This specifically tests the ext === "markdown" condition in the extension check
76+ const source = '```example.markdown\n# Some markdown content\n```';
77+ const expected = '~~~example.markdown\n# Some markdown content\n~~~';
78+ expect(patchNestedMarkdown(source)).toBe(expected);
79+ });
80+
81+ // GitHub-specific tests
82+ it('should handle gfm language identifier', () => {
83+ const source = '```gfm\n# Header\nSome text\n```';
84+ const expected = '~~~gfm\n# Header\nSome text\n~~~';
85+ expect(patchNestedMarkdown(source)).toBe(expected);
86+ });
87+
88+ it('should handle github-markdown language identifier', () => {
89+ const source = '```github-markdown\n# Header\nSome text\n```';
90+ const expected = '~~~github-markdown\n# Header\nSome text\n~~~';
91+ expect(patchNestedMarkdown(source)).toBe(expected);
92+ });
93+
94+ it('should handle language specifier followed by gfm', () => {
95+ const source = '```lang gfm\n# Header\nSome text\n```';
96+ const expected = '~~~lang gfm\n# Header\nSome text\n~~~';
97+ expect(patchNestedMarkdown(source)).toBe(expected);
98+ });
99+
100+ it('should handle .gfm file extension', () => {
101+ const source = '```example.gfm\n# Some GitHub markdown content\n```';
102+ const expected = '~~~example.gfm\n# Some GitHub markdown content\n~~~';
103+ expect(patchNestedMarkdown(source)).toBe(expected);
104+ });
105+});
modified gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +25 −20
@@ -1,47 +1,52 @@
11 /*
22 This is a patch for outputing markdown code that contains codeblocks
33
4- It notices markdown blocks, keeps track of when that specific block is closed,
4+ It notices markdown blocks (including GitHub-specific variants),
5+ keeps track of when that specific block is closed,
56 and uses ~~~ instead of ``` for that block
67
78 Note, this was benchmarked at sub-millisecond
8-
9- // TODO support github-specific markdown as well, edge case
109 */
10+import { headerIsMarkdown } from './headerIsMarkdown';
11+
1112 export const patchNestedMarkdown = (source: string): string => {
12- if (!source.match(/```(\w+\.(md|markdown))/)) return source; // For performance
13- // const start = Date.now();
13+ // Early return if no markdown codeblock pattern is found (including GitHub variants)
14+ if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) return source;
15+
1416 let nestCount = 0;
1517 const lines = source.split("\n");
1618 const trimmedLines = lines.map((l) => l.trim());
19+
1720 for (let i = 0; i < trimmedLines.length; i++) {
1821 const line = trimmedLines[i];
19- if (nestCount) {
22+
23+ if (nestCount > 0) {
24+ // Inside a markdown block
2025 if (line.match(/^`+$/)) {
21- // Ending a block
22- if (nestCount === 1) lines[i] = "~~~"; // End of markdown block
26+ // Ending a block with just backticks (```)
2327 nestCount--;
28+ if (nestCount === 0) {
29+ lines[i] = "~~~"; // End of markdown block
30+ }
2431 } else if (line.startsWith("```")) {
2532 // Going into a nested codeblock
2633 nestCount++;
2734 }
2835 } else {
29- // Enter the markdown block, start tracking nesting
36+ // Not inside a markdown block yet
3037 if (line.startsWith("```")) {
3138 const header = line.replaceAll("`", "");
32- const file = header.split(" ")[0];
33-
34- if (file) {
35- const ext = file.split(".").at(-1);
36- if (ext === "md" || ext === "markdown") {
37- nestCount = 1;
38- lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes
39- }
39+
40+ // Check if this is a markdown codeblock using a consolidated approach (including GitHub-specific variants)
41+ const isMarkdown = headerIsMarkdown(header);
42+
43+ if (isMarkdown) {
44+ nestCount = 1;
45+ lines[i] = lines[i].replaceAll("`", "~");
4046 }
4147 }
4248 }
4349 }
44- const out = lines.join("\n");
45- // console.log(`patched in ${Date.now() - start}ms`);
46- return out;
50+
51+ return lines.join("\n");
4752 };