Skip to content

Commit 69b11c9

Browse files
committed
fix: rebalance inline formatting (bold/italic) across Discord chunk boundaries
When bold, italic, or code markers span chunk boundaries, close them at the end of the current chunk and reopen at the start of the next so Discord renders each chunk with correct formatting. Implemented as a post-processing pass (rebalanceInlineFormatting) that scans each chunk for unmatched markers and appends close/reopen tokens. The marker scanner is inlined since the plugin SDK doesn't export the core inline-formatting utilities.
1 parent e76de4b commit 69b11c9

2 files changed

Lines changed: 112 additions & 1 deletion

File tree

‎extensions/discord/src/chunk.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,4 +216,17 @@ describe("chunkDiscordText", () => {
216216
}
217217
}
218218
});
219+
220+
it("closes and reopens bold markers when split across chunks", () => {
221+
const text = "Line 1\n**Bold text that\nspans multiple lines\nand should stay bold** done.";
222+
223+
const chunks = chunkDiscordText(text, { maxChars: 2000, maxLines: 2 });
224+
expect(chunks.length).toBeGreaterThan(1);
225+
226+
// Every chunk should have balanced ** markers
227+
for (const chunk of chunks) {
228+
const stars = (chunk.match(/\*\*/g) || []).length;
229+
expect(stars % 2).toBe(0);
230+
}
231+
});
219232
});

‎extensions/discord/src/chunk.ts‎

Lines changed: 99 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,62 @@ import { chunkMarkdownTextWithMode, type ChunkMode } from "openclaw/plugin-sdk/r
33
const BQ_PREFIX_RE = /^(>+\s?)/;
44
const TABLE_SEPARATOR_RE = /^\|?[\s-:|]+\|[\s-:|]*$/;
55

6+
// Inline formatting markers, longest first.
7+
const INLINE_MARKERS = ["***", "**", "*", "___", "__", "_", "``", "`"];
8+
9+
type InlineFormatState = {
10+
openMarkers: string[];
11+
};
12+
13+
/**
14+
* Scan text for unmatched inline formatting markers, skipping fenced regions.
15+
*/
16+
function scanUnmatchedInlineMarkers(text: string): InlineFormatState {
17+
const openMarkers: string[] = [];
18+
let i = 0;
19+
let inFence = false;
20+
21+
while (i < text.length) {
22+
// Simple fence detection: toggle on ``` at start of line
23+
if ((i === 0 || text[i - 1] === "\n") && text.startsWith("```", i)) {
24+
inFence = !inFence;
25+
i += 3;
26+
// Skip to end of line
27+
while (i < text.length && text[i] !== "\n") { i++; }
28+
continue;
29+
}
30+
if (inFence) { i++; continue; }
31+
32+
// Skip escaped characters
33+
if (text[i] === "\\" && i + 1 < text.length) { i += 2; continue; }
34+
35+
// Try to match markers longest-first
36+
let matched = false;
37+
for (const marker of INLINE_MARKERS) {
38+
if (text.startsWith(marker, i)) {
39+
// For _-based markers: only treat as emphasis at word boundaries
40+
if (marker.startsWith("_")) {
41+
const prev = i > 0 ? text[i - 1] : " ";
42+
const next = i + marker.length < text.length ? text[i + marker.length] : " ";
43+
if (/\w/.test(prev) || /\w/.test(next)) { i++; matched = true; break; }
44+
}
45+
const existingIdx = openMarkers.lastIndexOf(marker);
46+
if (existingIdx !== -1) {
47+
openMarkers.splice(existingIdx, 1);
48+
} else {
49+
openMarkers.push(marker);
50+
}
51+
i += marker.length;
52+
matched = true;
53+
break;
54+
}
55+
}
56+
if (!matched) { i++; }
57+
}
58+
59+
return { openMarkers };
60+
}
61+
662
type TableHeader = {
763
headerLine: string;
864
separatorLine: string;
@@ -439,7 +495,7 @@ export function chunkDiscordText(text: string, opts: ChunkDiscordTextOpts = {}):
439495
}
440496
}
441497

442-
return rebalanceReasoningItalics(text, chunks);
498+
return rebalanceReasoningItalics(text, rebalanceInlineFormatting(chunks));
443499
}
444500

445501
export function chunkDiscordTextWithMode(
@@ -467,6 +523,48 @@ export function chunkDiscordTextWithMode(
467523
return chunks;
468524
}
469525

526+
/**
527+
* Close unmatched inline formatting markers (**, *, __, _, `) at chunk
528+
* boundaries and reopen them at the start of the next chunk so bold,
529+
* italic, and code spans render correctly when split across messages.
530+
*/
531+
function rebalanceInlineFormatting(chunks: string[]): string[] {
532+
if (chunks.length <= 1) {
533+
return chunks;
534+
}
535+
536+
const adjusted = [...chunks];
537+
let pendingReopen = "";
538+
539+
for (let i = 0; i < adjusted.length; i++) {
540+
let chunk = adjusted[i];
541+
542+
// Prepend any reopen markers from the previous chunk
543+
if (pendingReopen) {
544+
chunk = `${pendingReopen}${chunk}`;
545+
adjusted[i] = chunk;
546+
}
547+
548+
if (i === adjusted.length - 1) {
549+
pendingReopen = "";
550+
break;
551+
}
552+
553+
// Scan for unmatched markers in this chunk
554+
const state = scanUnmatchedInlineMarkers(chunk);
555+
if (state.openMarkers.length > 0) {
556+
const close = [...state.openMarkers].reverse().join("");
557+
const reopen = state.openMarkers.join("");
558+
adjusted[i] = `${chunk}${close}`;
559+
pendingReopen = reopen;
560+
} else {
561+
pendingReopen = "";
562+
}
563+
}
564+
565+
return adjusted;
566+
}
567+
470568
// Keep italics intact for reasoning payloads that are wrapped once with `_…_`.
471569
// When Discord chunking splits the message, we close italics at the end of
472570
// each chunk and reopen at the start of the next so every chunk renders

0 commit comments

Comments
 (0)