From 4b6e464c7cc8f9e2a9257946937bda7b5c278ad9 Mon Sep 17 00:00:00 2001 From: jay23606 <4602056+jay23606@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:51:07 +0000 Subject: [PATCH 1/2] fix: restore Nim syntax highlighting and syntax menu entry --- src/cm/modes/nim/index.ts | 191 +++++++++++++++++++++++++++++ src/cm/supportedModes.ts | 7 ++ tests/unit/nimHighlighting.test.ts | 69 +++++++++++ 3 files changed, 267 insertions(+) create mode 100644 src/cm/modes/nim/index.ts create mode 100644 tests/unit/nimHighlighting.test.ts diff --git a/src/cm/modes/nim/index.ts b/src/cm/modes/nim/index.ts new file mode 100644 index 000000000..56f7d6e52 --- /dev/null +++ b/src/cm/modes/nim/index.ts @@ -0,0 +1,191 @@ +import { + LanguageSupport, + StreamLanguage, + type StringStream, +} from "@codemirror/language"; + +interface NimState { + blockCommentDepth: number; + inTripleString: boolean; +} + +const NUMBER_PATTERN = + /^(?:0[xX][0-9a-fA-F_]+|0[oO][0-7_]+|0[bB][01_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?)(?:'[iuf]\d*)?/; + +const keywords = new Set([ + "addr", + "and", + "as", + "asm", + "bind", + "block", + "break", + "case", + "cast", + "concept", + "const", + "continue", + "converter", + "defer", + "discard", + "distinct", + "div", + "do", + "elif", + "else", + "end", + "enum", + "except", + "export", + "finally", + "for", + "from", + "func", + "if", + "import", + "in", + "include", + "interface", + "is", + "isnot", + "iterator", + "let", + "macro", + "method", + "mixin", + "mod", + "not", + "notin", + "object", + "of", + "or", + "out", + "proc", + "ptr", + "raise", + "ref", + "return", + "shl", + "shr", + "static", + "template", + "try", + "tuple", + "type", + "using", + "var", + "when", + "while", + "xor", + "yield", +]); + +const atoms = new Set(["true", "false", "nil"]); + +const builtinTypes = new Set([ + "bool", + "byte", + "char", + "cstring", + "float", + "float32", + "float64", + "int", + "int8", + "int16", + "int32", + "int64", + "pointer", + "seq", + "string", + "uint", + "uint8", + "uint16", + "uint32", + "uint64", + "void", +]); + +const nimLanguage = StreamLanguage.define({ + name: "nim", + startState() { + return { blockCommentDepth: 0, inTripleString: false }; + }, + copyState(state) { + return { ...state }; + }, + token(stream, state) { + if (state.blockCommentDepth > 0) return readBlockComment(stream, state); + if (state.inTripleString) return readTripleString(stream, state); + if (stream.eatSpace()) return null; + + if (stream.match("#[")) { + state.blockCommentDepth = 1; + return readBlockComment(stream, state); + } + if (stream.match("#")) { + stream.skipToEnd(); + return "comment"; + } + if (stream.match('"""')) { + state.inTripleString = true; + return readTripleString(stream, state); + } + if (stream.match('"')) return readString(stream); + if (stream.match(/^'(?:\\.|[^'\\])*'?/)) return "string"; + if (stream.match(NUMBER_PATTERN)) return "number"; + if (stream.match(/^[A-Za-z_]\w*/)) return identifierStyle(stream.current()); + if (stream.match(/^[-+*/<>=!~^&|@$%?.:\\]+/)) return "operator"; + + stream.next(); + return null; + }, + languageData: { + commentTokens: { line: "#" }, + }, +}); + +export function nim(): LanguageSupport { + return new LanguageSupport(nimLanguage); +} + +function identifierStyle(word: string): string | null { + if (keywords.has(word)) return "keyword"; + if (atoms.has(word)) return "atom"; + if (builtinTypes.has(word)) return "typeName"; + return null; +} + +function readBlockComment(stream: StringStream, state: NimState): string { + while (!stream.eol()) { + if (stream.match("#[")) { + state.blockCommentDepth++; + } else if (stream.match("]#")) { + state.blockCommentDepth--; + if (state.blockCommentDepth === 0) break; + } else { + stream.next(); + } + } + return "comment"; +} + +function readTripleString(stream: StringStream, state: NimState): string { + while (!stream.eol()) { + if (stream.match('"""')) { + state.inTripleString = false; + break; + } + stream.next(); + } + return "string"; +} + +function readString(stream: StringStream): string { + while (!stream.eol()) { + const character = stream.next(); + if (character === "\\") stream.next(); + else if (character === '"') break; + } + return "string"; +} diff --git a/src/cm/supportedModes.ts b/src/cm/supportedModes.ts index 23b51840e..fc4909798 100644 --- a/src/cm/supportedModes.ts +++ b/src/cm/supportedModes.ts @@ -313,6 +313,13 @@ addMode("Luau", "luau", "Luau", async () => { return luau(); }); +// Nim isn't bundled in @codemirror/language-data, and the Ace editor's Nim +// mode was lost when the editor moved to CodeMirror. +addMode("nim", "nim|nims|nimble", "Nim", async () => { + const { nim } = await import("./modes/nim"); + return nim(); +}); + // Astro isn't bundled in @codemirror/language-data. Register it with HTML as // the structural parser plus Astro frontmatter and expression highlighting. addMode("Astro", "astro", "Astro", async () => { diff --git a/tests/unit/nimHighlighting.test.ts b/tests/unit/nimHighlighting.test.ts new file mode 100644 index 000000000..32339cb4c --- /dev/null +++ b/tests/unit/nimHighlighting.test.ts @@ -0,0 +1,69 @@ +import "cm/supportedModes"; +import { ensureSyntaxTree } from "@codemirror/language"; +import { EditorState } from "@codemirror/state"; +import { highlightTree } from "@lezer/highlight"; +import { getModeForPath } from "cm/modelist"; +import { describe, expect, it } from "vitest"; + +const sample = `proc add*(a: int): int = + # line note + let s = "hi \\" there" # trailing + discard 0x1F + 2.5e3 + var ok = true +#[ block + note ]# +let raw = """multi +line""" +`; + +async function highlightedTexts(doc: string) { + const { nim } = await import("cm/modes/nim"); + const state = EditorState.create({ doc, extensions: nim() }); + const tree = ensureSyntaxTree(state, doc.length, 5000); + if (!tree) throw new Error("parse did not finish"); + const out: [string, string][] = []; + highlightTree( + tree, + { style: (tags) => tags.map(String).join(" ") }, + (from, to, tags) => { + const text = doc.slice(from, to); + if (text.trim()) out.push([tags, text]); + }, + ); + return out; +} + +function textsWith(highlights: [string, string][], tags: string) { + return highlights.filter(([style]) => style === tags).map(([, text]) => text); +} + +describe("Nim syntax highlighting", () => { + it("selects the Nim mode for .nim files", () => { + expect(getModeForPath("src/main.nim").caption).toBe("Nim"); + }); + + it("colours keywords, types, numbers, strings and comments", async () => { + const highlights = await highlightedTexts(sample); + expect(textsWith(highlights, "keyword")).toEqual([ + "proc", + "let", + "discard", + "var", + "let", + ]); + expect(textsWith(highlights, "typeName")).toEqual(["int", "int"]); + expect(textsWith(highlights, "atom")).toEqual(["true"]); + expect(textsWith(highlights, "number")).toEqual(["0x1F", "2.5e3"]); + expect(textsWith(highlights, "string")).toEqual([ + '"hi \\" there"', + '"""multi', + 'line"""', + ]); + expect(textsWith(highlights, "comment")).toEqual([ + "# line note", + "# trailing", + "#[ block", + " note ]#", + ]); + }); +}); From a05947e9d3f630dfe5295a562d3c1d0a3d9cf9a4 Mon Sep 17 00:00:00 2001 From: jay23606 <4602056+jay23606@users.noreply.github.com> Date: Sat, 5 Dec 2026 08:15:41 -0500 Subject: [PATCH 2/2] fix: tokenize Nim raw strings and doc comments Signed-off-by: jay23606 <4602056+jay23606@users.noreply.github.com> --- src/cm/modes/nim/index.ts | 46 ++++++++++++++++++++++++++++-------- tests/unit/nimSyntax.test.ts | 24 +++++++++++++++++++ 2 files changed, 60 insertions(+), 10 deletions(-) create mode 100644 tests/unit/nimSyntax.test.ts diff --git a/src/cm/modes/nim/index.ts b/src/cm/modes/nim/index.ts index 56f7d6e52..66b8844af 100644 --- a/src/cm/modes/nim/index.ts +++ b/src/cm/modes/nim/index.ts @@ -5,7 +5,7 @@ import { } from "@codemirror/language"; interface NimState { - blockCommentDepth: number; + blockCommentClosers: string[]; inTripleString: boolean; } @@ -109,18 +109,27 @@ const builtinTypes = new Set([ const nimLanguage = StreamLanguage.define({ name: "nim", startState() { - return { blockCommentDepth: 0, inTripleString: false }; + return { blockCommentClosers: [], inTripleString: false }; }, copyState(state) { - return { ...state }; + return { + ...state, + blockCommentClosers: [...state.blockCommentClosers], + }; }, token(stream, state) { - if (state.blockCommentDepth > 0) return readBlockComment(stream, state); + if (state.blockCommentClosers.length > 0) { + return readBlockComment(stream, state); + } if (state.inTripleString) return readTripleString(stream, state); if (stream.eatSpace()) return null; + if (stream.match("##[")) { + state.blockCommentClosers.push("]##"); + return readBlockComment(stream, state); + } if (stream.match("#[")) { - state.blockCommentDepth = 1; + state.blockCommentClosers.push("]#"); return readBlockComment(stream, state); } if (stream.match("#")) { @@ -131,6 +140,7 @@ const nimLanguage = StreamLanguage.define({ state.inTripleString = true; return readTripleString(stream, state); } + if (stream.match(/^[A-Za-z_]\w*"/)) return readRawString(stream); if (stream.match('"')) return readString(stream); if (stream.match(/^'(?:\\.|[^'\\])*'?/)) return "string"; if (stream.match(NUMBER_PATTERN)) return "number"; @@ -158,11 +168,17 @@ function identifierStyle(word: string): string | null { function readBlockComment(stream: StringStream, state: NimState): string { while (!stream.eol()) { - if (stream.match("#[")) { - state.blockCommentDepth++; - } else if (stream.match("]#")) { - state.blockCommentDepth--; - if (state.blockCommentDepth === 0) break; + if (stream.match("##[")) { + state.blockCommentClosers.push("]##"); + } else if (stream.match("#[")) { + state.blockCommentClosers.push("]#"); + } else if ( + stream.match( + state.blockCommentClosers[state.blockCommentClosers.length - 1], + ) + ) { + state.blockCommentClosers.pop(); + if (state.blockCommentClosers.length === 0) break; } else { stream.next(); } @@ -189,3 +205,13 @@ function readString(stream: StringStream): string { } return "string"; } + +function readRawString(stream: StringStream): string { + while (!stream.eol()) { + if (stream.next() === '"') { + if (stream.eat('"')) continue; + break; + } + } + return "string"; +} diff --git a/tests/unit/nimSyntax.test.ts b/tests/unit/nimSyntax.test.ts new file mode 100644 index 000000000..ad398ba39 --- /dev/null +++ b/tests/unit/nimSyntax.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; +import { nim } from "../../src/cm/modes/nim"; + +describe("Nim syntax mode", () => { + it("keeps raw and generalized string contents inside the string token", () => { + const parser = nim().language.parser; + const tree = parser.parse( + 'let path = r"C:\\" # note\nlet pattern = re"[a-z]+" # end', + ); + expect(tree.toString()).toBe( + "Document(keyword,operator,string,comment,keyword,operator,string,comment)", + ); + }); + + it("recognizes multiline documentation comments", () => { + const parser = nim().language.parser; + const tree = parser.parse( + "##[ docs\nlet thisIsComment = true\n]##\nlet code = true", + ); + expect(tree.toString()).toBe( + "Document(comment,comment,comment,keyword,operator,atom)", + ); + }); +});