| 1 | // Cómo se pinta en Code el texto que escribe una extensión. Regla única: nada |
| 2 | // de lo que sale del recinto puede hacer una petición, navegar o meter HTML. |
| 3 | // |
| 4 | // · Campos de texto plano (documentación de un autocompletado, detalle, |
| 5 | // firmas, mensajes de diagnóstico): Monaco los pinta como texto. Se pasa el |
| 6 | // markdown a texto legible: una imagen queda en su texto alternativo y un |
| 7 | // enlace [t](u) en «t (u)». |
| 8 | // · Campos que Monaco exige en markdown (hover): markdown CANÓNICO hecho |
| 9 | // aquí. El texto va con TODOS los signos de puntuación ASCII escapados con |
| 10 | // barra: no puede sobrevivir ningún enlace, imagen, autoenlace, HTML, |
| 11 | // énfasis ni título. El código va entre delimitadores nuestros. |
| 12 | // isTrusted, supportHtml y supportThemeIcons a false y sin baseUri. |
| 13 | // |
| 14 | // La página solo pinta markdown que ha escrito ella: no hay diferencias entre |
| 15 | // el analizador de la extensión y el nuestro, porque la estructura es nuestra. |
| 16 | |
| 17 | const PUNCT = /[!-/:-@[-`{-~]/g; // toda la puntuación ASCII |
| 18 | const MAX = 65536; |
| 19 | |
| 20 | // Trocea el markdown de una extensión en texto, código en línea y bloques de |
| 21 | // código vallados. Conservador: lo que no es código es texto. |
| 22 | export function segments(src) { |
| 23 | const s = String(src ?? '').slice(0, MAX).replace(/\r\n?/g, '\n'); |
| 24 | const out = []; |
| 25 | let i = 0, text = ''; |
| 26 | const flush = () => { if (text) { out.push({ type: 'text', value: text }); text = ''; } }; |
| 27 | while (i < s.length) { |
| 28 | const atLineStart = i === 0 || s[i - 1] === '\n'; |
| 29 | if (atLineStart) { |
| 30 | const fence = /^( {0,3})(`{3,}|~{3,})([^\n`]*)\n/.exec(s.slice(i)); |
| 31 | if (fence) { |
| 32 | const marker = fence[2]; |
| 33 | const body = s.slice(i + fence[0].length); |
| 34 | const close = new RegExp('(^|\\n) {0,3}' + marker[0] + '{' + marker.length + ',}[ \\t]*(\\n|$)').exec(body); |
| 35 | const end = close ? close.index + (close[1] ? 1 : 0) : body.length; |
| 36 | flush(); |
| 37 | out.push({ type: 'fence', lang: (fence[3].trim().split(/\s+/)[0] || '').toLowerCase(), value: body.slice(0, end).replace(/\n$/, '') }); |
| 38 | i += fence[0].length + (close ? close.index + close[0].length : body.length); |
| 39 | continue; |
| 40 | } |
| 41 | } |
| 42 | if (s[i] === '`') { |
| 43 | let n = 0; while (s[i + n] === '`') n++; |
| 44 | const ticks = '`'.repeat(n); |
| 45 | let j = i + n, found = -1; |
| 46 | while ((j = s.indexOf(ticks, j)) !== -1) { |
| 47 | if (s[j + n] !== '`' && s[j - 1] !== '`') { found = j; break; } |
| 48 | j += n; |
| 49 | } |
| 50 | if (found !== -1) { |
| 51 | flush(); |
| 52 | out.push({ type: 'code', value: s.slice(i + n, found).replace(/\n/g, ' ') }); |
| 53 | i = found + n; |
| 54 | continue; |
| 55 | } |
| 56 | text += ticks; i += n; continue; |
| 57 | } |
| 58 | text += s[i++]; |
| 59 | } |
| 60 | flush(); |
| 61 | return out; |
| 62 | } |
| 63 | |
| 64 | // Texto de un trozo de markdown, sin sintaxis que pueda convertirse en nada. |
| 65 | function toPlain(text) { |
| 66 | return text |
| 67 | .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1') // imagen → su texto alternativo |
| 68 | .replace(/\[([^\]]+)\]\(\s*<?([^)\s>]*)>?(?:\s+"[^"]*")?\s*\)/g, (_, t, u) => (u ? `${t} (${u})` : t)) |
| 69 | .replace(/<\/?[a-zA-Z][^>]*>/g, ''); |
| 70 | } |
| 71 | |
| 72 | export function plainText(src) { |
| 73 | return segments(src).map(seg => (seg.type === 'text' ? toPlain(seg.value) : seg.type === 'code' ? seg.value : seg.value + '\n')).join('').slice(0, MAX); |
| 74 | } |
| 75 | |
| 76 | const escapeText = t => t.replace(PUNCT, ch => '\\' + ch) |
| 77 | // sangría de 4 espacios = bloque de código: se conserva con espacios duros |
| 78 | .replace(/^( +)/gm, sp => ' '.repeat(sp.length)) |
| 79 | // saltos de línea simples visibles (dos espacios + salto) |
| 80 | .replace(/([^\n])\n(?!\n)/g, '$1 \n'); |
| 81 | |
| 82 | function fenceFor(value) { |
| 83 | let longest = 2; |
| 84 | for (const m of value.matchAll(/`+/g)) longest = Math.max(longest, m[0].length); |
| 85 | return '`'.repeat(longest + 1); |
| 86 | } |
| 87 | |
| 88 | export function canonicalMarkdown(src) { |
| 89 | const parts = []; |
| 90 | for (const seg of segments(src)) { |
| 91 | if (seg.type === 'text') parts.push(escapeText(seg.value)); |
| 92 | else if (seg.type === 'code') { |
| 93 | let n = 1; |
| 94 | for (const m of seg.value.matchAll(/`+/g)) n = Math.max(n, m[0].length + 1); |
| 95 | const d = '`'.repeat(n); |
| 96 | const pad = seg.value.startsWith('`') || seg.value.endsWith('`') ? ' ' : ''; |
| 97 | parts.push(d + pad + seg.value + pad + d); |
| 98 | } else { |
| 99 | const lang = /^[a-z0-9-]{0,30}$/.test(seg.lang) ? seg.lang : ''; |
| 100 | const f = fenceFor(seg.value); |
| 101 | const before = parts.length && !/\n$/.test(parts[parts.length - 1]) ? '\n' : ''; |
| 102 | parts.push(`${before}${f}${lang}\n${seg.value}\n${f}\n`); |
| 103 | } |
| 104 | } |
| 105 | return { value: parts.join('').slice(0, MAX * 2), isTrusted: false, supportHtml: false, supportThemeIcons: false }; |
| 106 | } |
| 107 | |
| 108 | // Texto plano que va en un campo markdown (p. ej. un hover que llegó como |
| 109 | // cadena): todo escapado, ninguna estructura. |
| 110 | export function markdownFromText(text) { |
| 111 | return { value: escapeText(String(text ?? '').slice(0, MAX)), isTrusted: false, supportHtml: false, supportThemeIcons: false }; |
| 112 | } |
| 113 | |
| 114 | // Variables ${CLIPBOARD} de un snippet de extensión: fuera. Si no, aceptar un |
| 115 | // autocompletado metería tu portapapeles en un documento que la extensión lee. |
| 116 | export function stripClipboard(snippet) { |
| 117 | const s = String(snippet ?? ''); |
| 118 | let out = '', i = 0; |
| 119 | while (i < s.length) { |
| 120 | if (s[i] === '\\' && i + 1 < s.length) { out += s[i] + s[i + 1]; i += 2; continue; } |
| 121 | if (s[i] === '$') { |
| 122 | const bare = /^\$CLIPBOARD(?![A-Za-z0-9_])/.exec(s.slice(i)); |
| 123 | if (bare) { i += bare[0].length; continue; } |
| 124 | if (s[i + 1] === '{' && /^\$\{CLIPBOARD(?![A-Za-z0-9_])/.test(s.slice(i))) { |
| 125 | // salta hasta la llave que cierra, respetando las anidadas y los escapes |
| 126 | let depth = 0, j = i + 1; |
| 127 | for (; j < s.length; j++) { |
| 128 | if (s[j] === '\\') { j++; continue; } |
| 129 | if (s[j] === '{') depth++; |
| 130 | else if (s[j] === '}' && --depth === 0) break; |
| 131 | } |
| 132 | i = j + 1; |
| 133 | continue; |
| 134 | } |
| 135 | } |
| 136 | out += s[i++]; |
| 137 | } |
| 138 | return out; |
| 139 | } |