/** * Removes standalone ` ` and related non-breaking whitespace entity lines * (commonly produced when converting empty rich text paragraphs `

 

` to Markdown) * while safely preserving: * 1. Fenced code blocks (``` or ~~~) containing ` ` * 2. Inline ` ` within sentences or tables (e.g. `word1 word2` or `|   |`) * 3. Inline code spans (e.g. `` ` ` ``) * * @param text The input markdown text. * @returns Cleaned markdown text without raw standalone ` ` lines. */ export function cleanMarkdownNbsp(text: string): string { if (!text || typeof text !== 'string') return text; if (!text.includes(' ') && !text.includes(' ') && !text.includes(' ')) return text; const lines = text.split(/\r?\n/); const eol = text.includes('\r\n') ? '\r\n' : '\n'; const result: string[] = []; let inCodeBlock = false; // Matches lines consisting exclusively of one or more non-breaking space entities // ( ,  ,  ) and whitespace / unicode non-breaking spaces (\u00A0) const standaloneNbspLineRegex = /^[ \t\u00A0]*(?:(?: | | )[ \t\u00A0]*)+$/; for (const line of lines) { const trimmed = line.trim(); if (trimmed.startsWith('```') || trimmed.startsWith('~~~')) { inCodeBlock = !inCodeBlock; result.push(line); continue; } if (inCodeBlock) { result.push(line); continue; } // Check if the line consists entirely of standalone non-breaking space entities if (standaloneNbspLineRegex.test(line)) { // If previous line was already empty, skip pushing another empty line // to avoid ballooning vertical whitespace if (result.length > 0 && result[result.length - 1] === '') { continue; } result.push(''); continue; } result.push(line); } return result.join(eol).replace(/(\r?\n){3,}/g, '$1$1'); } export default cleanMarkdownNbsp;