The best way to control Claude Code, Codex and more from any computer or phone
| 1 | export type RichTextMark = "bold" | "italic" | "strike" | "code"; |
| 2 | |
| 3 | interface RichTextSpan { |
| 4 | text: string; |
| 5 | marks: RichTextMark[]; |
| 6 | } |
| 7 | |
| 8 | export const RICH_TEXT_DELIMITERS: Record<RichTextMark, string> = { |
| 9 | bold: "**", |
| 10 | italic: "*", |
| 11 | strike: "~~", |
| 12 | code: "`", |
| 13 | }; |
| 14 | |
| 15 | /** A run of `text` from `start` to `end` that parses with `marks`. */ |
| 16 | interface SourcePiece { |
| 17 | start: number; |
| 18 | end: number; |
| 19 | marks: RichTextMark[]; |
| 20 | } |
| 21 | |
| 22 | function sameMarks(left: readonly RichTextMark[], right: readonly RichTextMark[]): boolean { |
| 23 | return left.length === right.length && left.every((mark, index) => mark === right[index]); |
| 24 | } |
| 25 | |
| 26 | // Brackets, quotes, commas, and Markdown delimiters end a URL or path token; a lone `~` does not. |
| 27 | const PATH_TOKEN = /(?:[\p{L}\p{N}_/.:@%+=&?#-]|(?<!~)~(?!~))+/gu; |
| 28 | const FILE_EXTENSION = /^\.[a-z][a-z0-9]*(?::\d+){0,2}$/i; |
| 29 | // `_yes_/_no_`: each side of a slash is its own emphasis span, so the word is not a path. |
| 30 | const EMPHASIS_ALTERNATIVES = /^_[^/]+_(?:\/_[^/]+_)+$/; |
| 31 | // Word characters in any script; callers pass two code units so a letter outside the BMP matches whole. |
| 32 | const WORD_CHARACTER_BEFORE = /[\p{L}\p{M}\p{N}_]$/u; |
| 33 | const WORD_CHARACTER_AFTER = /^[\p{L}\p{M}\p{N}_]/u; |
| 34 | |
| 35 | /** |
| 36 | * Starts of underscore runs that belong to a URL, path, or filename, not to emphasis. |
| 37 | * A run ending the token stays a delimiter so emphasis wrapped around the token still closes. |
| 38 | */ |
| 39 | function literalUnderscoreRuns(text: string): Set<number> { |
| 40 | const literal = new Set<number>(); |
| 41 | if (!text.includes("_")) return literal; |
| 42 | for (const match of text.matchAll(PATH_TOKEN)) { |
| 43 | const token = match[0]; |
| 44 | let bodyEnd = token.length; |
| 45 | while (bodyEnd > 0 && ".:?".includes(token[bodyEnd - 1]!)) bodyEnd -= 1; |
| 46 | if (EMPHASIS_ALTERNATIVES.test(token.slice(0, bodyEnd))) continue; |
| 47 | while (bodyEnd > 0 && token[bodyEnd - 1] === "_") bodyEnd -= 1; |
| 48 | const body = token.slice(0, bodyEnd); |
| 49 | // A slash alone is prose (`and/_or_`); a path also has a dot, a scheme or port, or a root. |
| 50 | const isPath = body.includes("/") |
| 51 | ? /^~?\/|[.:]/.test(body) |
| 52 | : FILE_EXTENSION.test(body.slice(body.lastIndexOf("."))); |
| 53 | if (!isPath) continue; |
| 54 | let closesInside = false; |
| 55 | let start = body.indexOf("_"); |
| 56 | while (start !== -1) { |
| 57 | let end = start; |
| 58 | while (body[end] === "_") end += 1; |
| 59 | if (start > 0) { |
| 60 | literal.add(match.index + start); |
| 61 | closesInside ||= !WORD_CHARACTER_AFTER.test(body.slice(end, end + 2)); |
| 62 | } |
| 63 | start = body.indexOf("_", end); |
| 64 | } |
| 65 | // A leading run could only pair with a run inside the name, as in `__init__.py`. |
| 66 | if (closesInside && body[0] === "_") literal.add(match.index); |
| 67 | } |
| 68 | return literal; |
| 69 | } |
| 70 | |
| 71 | // Pieces keep source offsets, so callers can map parsed text back onto the |
| 72 | // characters it came from; parsing only drops delimiters. |
| 73 | function parseInlineMarkdownPieces(text: string): SourcePiece[] { |
| 74 | const literalRuns = literalUnderscoreRuns(text); |
| 75 | const root: SourcePiece[] = []; |
| 76 | const stack: { delimiter: string; mark: RichTextMark; start: number; pieces: SourcePiece[] }[] = |
| 77 | []; |
| 78 | const push = (start: number, end: number, marks: RichTextMark[] = []) => { |
| 79 | if (end <= start) return; |
| 80 | const pieces = stack.at(-1)?.pieces ?? root; |
| 81 | const last = pieces.at(-1); |
| 82 | if (last?.end === start && sameMarks(last.marks, marks)) last.end = end; |
| 83 | else pieces.push({ start, end, marks }); |
| 84 | }; |
| 85 | let index = 0; |
| 86 | while (index < text.length) { |
| 87 | const char = text[index]!; |
| 88 | if (char === "\\") { |
| 89 | push(index, Math.min(index + 2, text.length)); |
| 90 | index += 2; |
| 91 | continue; |
| 92 | } |
| 93 | if (char === "`") { |
| 94 | const run = text.slice(index).match(/^`+/)![0]; |
| 95 | const close = text.indexOf(run, index + run.length); |
| 96 | if ( |
| 97 | run.length === 1 && |
| 98 | close > index + 1 && |
| 99 | !text.slice(index, close).includes("\n") && |
| 100 | text[close + 1] !== "`" |
| 101 | ) { |
| 102 | push(index + 1, close, ["code"]); |
| 103 | index = close + 1; |
| 104 | } else { |
| 105 | push(index, index + run.length); |
| 106 | index += run.length; |
| 107 | } |
| 108 | continue; |
| 109 | } |
| 110 | if (char !== "*" && char !== "_" && char !== "~") { |
| 111 | push(index, index + 1); |
| 112 | index += 1; |
| 113 | continue; |
| 114 | } |
| 115 | let end = index; |
| 116 | while (text[end] === char) end += 1; |
| 117 | if (literalRuns.has(index)) { |
| 118 | push(index, end); |
| 119 | index = end; |
| 120 | continue; |
| 121 | } |
| 122 | const before = text[index - 1] ?? ""; |
| 123 | const after = text[end] ?? ""; |
| 124 | const wordAfter = WORD_CHARACTER_AFTER.test(text.slice(end, end + 2)); |
| 125 | const wordBefore = WORD_CHARACTER_BEFORE.test(text.slice(Math.max(0, index - 2), index)); |
| 126 | const canClose = before !== "" && !/\s/.test(before) && (char !== "_" || !wordAfter); |
| 127 | const canOpen = after !== "" && !/\s/.test(after) && (char !== "_" || !wordBefore); |
| 128 | while (index < end) { |
| 129 | const top = stack.at(-1); |
| 130 | const opensNestedBold = |
| 131 | top?.mark === "italic" && |
| 132 | end - index === 2 && |
| 133 | canOpen && |
| 134 | (char === "*" || char === "_") && |
| 135 | !stack.some((frame) => frame.mark === "bold"); |
| 136 | if ( |
| 137 | !opensNestedBold && |
| 138 | canClose && |
| 139 | top && |
| 140 | text.startsWith(top.delimiter, index) && |
| 141 | index + top.delimiter.length <= end |
| 142 | ) { |
| 143 | stack.pop(); |
| 144 | for (const piece of top.pieces) push(piece.start, piece.end, [top.mark, ...piece.marks]); |
| 145 | index += top.delimiter.length; |
| 146 | } else if (canOpen && (char !== "~" || end - index >= 2)) { |
| 147 | const length = char === "~" || end - index >= 2 ? 2 : 1; |
| 148 | const mark = char === "~" ? "strike" : length === 2 ? "bold" : "italic"; |
| 149 | // Prevent self-nesting, including alternate delimiters, to bound the stack by supported styles. |
| 150 | if (stack.some((frame) => frame.mark === mark)) { |
| 151 | push(index, end); |
| 152 | index = end; |
| 153 | continue; |
| 154 | } |
| 155 | stack.push({ delimiter: char.repeat(length), mark, start: index, pieces: [] }); |
| 156 | index += length; |
| 157 | } else { |
| 158 | push(index, end); |
| 159 | index = end; |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | while (stack.length > 0) { |
| 164 | const frame = stack.pop()!; |
| 165 | push(frame.start, frame.start + frame.delimiter.length); |
| 166 | for (const piece of frame.pieces) push(piece.start, piece.end, piece.marks); |
| 167 | } |
| 168 | return root; |
| 169 | } |
| 170 | |
| 171 | export function parseInlineMarkdown(text: string): RichTextSpan[] { |
| 172 | const spans: RichTextSpan[] = []; |
| 173 | for (const { start, end, marks } of parseInlineMarkdownPieces(text)) { |
| 174 | const last = spans.at(-1); |
| 175 | if (last && sameMarks(last.marks, marks)) { |
| 176 | last.text += text.slice(start, end); |
| 177 | } else { |
| 178 | spans.push({ text: text.slice(start, end), marks }); |
| 179 | } |
| 180 | } |
| 181 | return spans; |
| 182 | } |
| 183 | |
| 184 | /** Marks text the composer shows as editable Markdown source while the caret is in it. */ |
| 185 | export const MARKDOWN_SOURCE_MARK = "markdownSource"; |
| 186 | |
| 187 | /** Marks for each UTF-16 unit of `text`, or null for a delimiter that parsing drops. */ |
| 188 | export function inlineMarkdownUnitMarks(text: string): Array<RichTextMark[] | null> { |
| 189 | const result: Array<RichTextMark[] | null> = Array.from({ length: text.length }, () => null); |
| 190 | for (const { start, end, marks } of parseInlineMarkdownPieces(text)) { |
| 191 | result.fill(marks, start, end); |
| 192 | } |
| 193 | return result; |
| 194 | } |