ident
All repositories: gitoria
41.0 KB
// hl:markdown — THE SYNTAX: Markdown text → plain data → Markdown text (ticket #111).// One parser for every app. Merged from tickets.worldapi.org/markdown.hl (the base:// safe links, emphasis by lookahead, autolinks), gitoria.worldapi.org/markdown.hl// (quotes, tables, rules) and components.hybriel's md-editor.hl (images, the// Markdown writer), plus what LLM answers need: nested lists, task items, code// fences with a language, ~~strike~~, and text that is still arriving.//// THE DATA. parse(text) answers a document `{ blocks, tail }`; every block carries// `type` and `gap` (the blank lines written before it):// p { spans }// heading { level (1-6), spans, trail (a closing ` ##`, usually '') }// code { code (every line + NL), lang (first word of the info string), info,// fence ('```', '~~~~' …; '' = an indented block), closed (false while// a fence is still open — streaming) }// list { ordered, start, marker ('-' '*' '+', or '.' ')' after a number),// indent, tight, items: [{ gap, num, task (null | true | false), cont// (the indent of its continuation lines), blocks }] }// quote { blocks }// table { align (['' | 'left' | 'center' | 'right']), head: { cells, src },// sep (the |---| line), rows: [{ cells, src }] }; a cell is { spans }// hr { src ('---', '***' …) }// `tail` is the number of newlines after the last block.// A span: { text, strong, em, strike, code, href, image, br, src }. `href` is ''// or a link that safeHref let through; `image` spans are links to the picture// (the View never loads one); `br` is a line break inside a block (text = NL).// `src` is the exact source the span came from — see serialize.//// SAFE BY CONSTRUCTION: nothing here builds HTML. Raw HTML in the text stays text// (`<script>` is ten characters). A link or image whose target safeHref refuses// (`javascript:`, `data:`, relative paths, spaces, quotes, control characters) is// kept as the plain text it was written as.//// STREAMING-SAFE: any prefix of a document parses. An open fence is a code block// with `closed = false`; a half list is a list; an emphasis run with no closer yet// is literal text; a table head without its |---| line is a paragraph. Nothing// here throws on input — every index is bounds-checked.//// ROUND TRIP: serialize(parse(t)) == t for normal documents. Each block kind keeps// its markers (bullet, fence, number, rule), blank lines are counted, and a// block's inline text is written from the spans' `src` when re-reading that// source gives the same spans — so an edited span (its text or flags changed, or// a span built by hand without `src`) makes that block's text canonical Markdown,// and every untouched block comes back byte for byte. Normalised, not kept: CR// characters, tabs in indentation, spaces on blank lines, a heading's or list// marker's extra spaces, lazy (unindented) continuation lines of a list item or// quote, `>` without its space.static NL = ""static BS = 'x\y'.slice(1, 2)// ---- characters -------------------------------------------------------------------static isSpaceC = (c) => { return c == 32 || c == 9 || c == 10 || c == 13 }static isAlnumC = (c) => { return (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c > 127 }static isPunctC = (c) => { return (c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126) }static rep = (s, n) => {let out = ''let i = 0while (i < n) {out = out + si = i + 1}return out}// ---- links --------------------------------------------------------------------------// the target of a link, or null when it is not one we let through: http(s), mailto, or// a SAME-SITE relative reference (`/path`, `./x`, `../x`, `x.html`, `#anchor`, `?q`) —// no scheme at all, and not `//host` (another site). Never spaces, control// characters, quotes, < > ` or backslashstatic safeHref = (u) => {if (u == null) { return null }let t = ('' + u).trim()if (t == '' || t.length > 2000) { return null }let i = 0while (i < t.length) {let c = t.charCodeAt(i)if (c <= 32 || c == 127 || c == 34 || c == 39 || c == 60 || c == 62 || c == 96 || c == 92) { return null }i = i + 1}let low = t.toLowerCase()if (low.startsWith('https://') && t.length > 8) { return t }if (low.startsWith('http://') && t.length > 7) { return t }if (low.startsWith('mailto:') && t.length > 7) { return t }// relative: not `//host`, and no ':' anywhere — a ':' is a scheme, or could become// one (`javascript:` is a ':' after a '#'); strict beats clever hereif (t.startsWith('//') || t.includes(':')) { return null }return t}static isUrlStart = (s, i) => {let low = s.slice(i, i + 8).toLowerCase()return low.startsWith('https://') || low.startsWith('http://')}// where a bare URL starting at i ends: up to whitespace or < > " `, minus trailing// punctuation (and a closing parenthesis that has no opening one inside the URL)static isUrlStop = (c) => { return isSpaceC(c) || c == 60 || c == 62 || c == 34 || c == 96 }static urlEnd = (s, i) => {let end = iwhile (end < s.length && !isUrlStop(s.charCodeAt(end))) { end = end + 1 }let trimming = truewhile (trimming && end > i) {let c = s.charCodeAt(end - 1)if (c == 46 || c == 44 || c == 59 || c == 58 || c == 33 || c == 63 || c == 39 || c == 42 || c == 95 || c == 126) {end = end - 1} else if (c == 41) {let opens = 0let closes = 0let k = iwhile (k < end) {if (s.charCodeAt(k) == 40) { opens = opens + 1 }if (s.charCodeAt(k) == 41) { closes = closes + 1 }k = k + 1}if (closes > opens) { end = end - 1 } else { trimming = false }} else {trimming = false}}return end}// `[label](target)` at i → { label, href (null = not allowed), end } or null (not a link)static linkAt = (s, i) => {let j = i + 1let found = -1let depth = 0while (j < s.length && found < 0) {let c = s.charCodeAt(j)if (c == 92) {j = j + 1} else if (c == 96) {// a code span inside the label is skipped wholelet k = jwhile (k < s.length && s.charCodeAt(k) == 96) { k = k + 1 }let close = runAt(s, k, 96, k - j, false)if (close >= 0) { j = close + (k - j) - 1 } else { j = k - 1 }} else if (c == 91) {depth = depth + 1} else if (c == 93) {if (depth == 0) { found = j } else { depth = depth - 1 }}j = j + 1}if (found < 0 || found == i + 1) { return null }if (found + 1 >= s.length || s.charCodeAt(found + 1) != 40) { return null }// the target ends at the `)` that balances its `(` — `(https://x.org/a_(b))`let k = found + 2let depth2 = 0let endAt = -1while (k < s.length && endAt < 0) {let c2 = s.charCodeAt(k)if (c2 == 92) {k = k + 1} else if (c2 == 40) {depth2 = depth2 + 1} else if (c2 == 41) {if (depth2 == 0) { endAt = k } else { depth2 = depth2 - 1 }} else if (c2 == 10) {return null}k = k + 1}if (endAt < 0) { return null }k = endAtlet target = s.slice(found + 2, k).trim()if (target.startsWith('<') && target.endsWith('>')) { target = target.slice(1, target.length - 1) }// an optional title after a space is dropped: [x](url "title")let sp = target.indexOf(' ')if (sp > 0) { target = target.slice(0, sp) }return { label = s.slice(i + 1, found) href = safeHref(target) end = k + 1 }}// ---- spans ----------------------------------------------------------------------------static span = (t, f) => {return { text = t strong = f.strong em = f.em strike = f.strike code = false href = f.href image = false br = false src = '' }}// the index of a run of EXACTLY n characters c at or after `at`, or -1. `esc`: a// character after a backslash does not count (inside `code` a backslash is just one)static runAt = (s, at, c, n, esc) => {let i = atwhile (i < s.length) {if (esc && s.charCodeAt(i) == 92) {i = i + 2} else if (s.charCodeAt(i) == c) {let k = iwhile (k < s.length && s.charCodeAt(k) == c) { k = k + 1 }if (k - i == n) { return i }i = k} else {i = i + 1}}return -1}// is there a CLOSING delimiter run (exactly n of c, not after a space; `_` not before// a letter or digit) after `at`, before the end of the line group?static hasCloser = (s, at, c, n) => {let i = atwhile (i < s.length) {let r = runAt(s, i, c, n, true)if (r < 0) { return false }let prev = r > 0 ? s.charCodeAt(r - 1) : 32let next = r + n < s.length ? s.charCodeAt(r + n) : 32if (r > at && !isSpaceC(prev) && (c != 95 || !isAlnumC(next))) { return true }i = r + n}return false}static trimEndSp = (t) => {let e = t.lengthwhile (e > 0 && (t.charCodeAt(e - 1) == 32 || t.charCodeAt(e - 1) == 9)) { e = e - 1 }return t.slice(0, e)}// inline Markdown → spans. `base` holds the flags of an enclosing link (its label is// read by the same function). Every character of `src` lands in exactly one span's// `src`, so the spans' src joined IS the source.static parseInline = (source, base) => {let out = []if (source == null) { return out }let s = '' + sourcelet n = s.lengthlet f = { strong = base.strong em = base.em strike = base.strike href = base.href }let strongC = 0let emC = 0let buf = ''let acc = ''let i = 0// the leading spaces of the text are source, not textwhile (i < n && (s.charCodeAt(i) == 32 || s.charCodeAt(i) == 9)) {acc = acc + s[i]i = i + 1}while (i < n) {let c = s.charCodeAt(i)if (c == 10 || (c == 92 && i + 1 < n && s.charCodeAt(i + 1) == 10)) {// a line break: the text before it loses its trailing spaces, the next line its// leading ones; a backslash before it is a hard break's markerif (buf != '') {let sp = span(trimEndSp(buf), f)sp.src = accout[] = sp} else if (acc != '' && out.length > 0) {out[out.length - 1].src = out[out.length - 1].src + acc} else if (acc != '') {let sp0 = span('', f)sp0.src = accout[] = sp0}buf = ''acc = c == 92 ? BS + NL : NLi = i + (c == 92 ? 2 : 1)while (i < n && (s.charCodeAt(i) == 32 || s.charCodeAt(i) == 9)) {acc = acc + s[i]i = i + 1}let b = span(NL, f)b.br = trueb.src = accout[] = bacc = ''} else if (c == 92 && i + 1 < n && isPunctC(s.charCodeAt(i + 1))) {// a backslash escape: the next punctuation character as itselfbuf = buf + s[i + 1]acc = acc + s.slice(i, i + 2)i = i + 2} else if (c == 96) {// `code`: a run of backticks up to the same runlet k = iwhile (k < n && s.charCodeAt(k) == 96) { k = k + 1 }let close = runAt(s, k, 96, k - i, false)if (close < 0) {buf = buf + s.slice(i, k)acc = acc + s.slice(i, k)i = k} else {if (buf != '') {let sp1 = span(buf, f)sp1.src = accout[] = sp1acc = ''}buf = ''let code = s.slice(k, close).replaceAll(NL, ' ')if (code.length > 2 && code.startsWith(' ') && code.endsWith(' ') && code.trim() != '') { code = code.slice(1, code.length - 1) }let cs = span(code, f)cs.code = truecs.src = acc + s.slice(i, close + (k - i))acc = ''out[] = csi = close + (k - i)}} else if (f.href == '' && (c == 91 || (c == 33 && i + 1 < n && s.charCodeAt(i + 1) == 91))) {// [label](url) and let img = c == 33let l = linkAt(s, img ? i + 1 : i)if (l == null) {buf = buf + s[i]acc = acc + s[i]i = i + 1} else if (l.href == null) {// a target we do not let through: the whole thing is textbuf = buf + s.slice(i, l.end)acc = acc + s.slice(i, l.end)i = l.end} else {if (buf != '') {let sp2 = span(buf, f)sp2.src = accout[] = sp2acc = ''}buf = ''let open = img ? '![' : '['let tailSrc = s.slice(i + open.length + l.label.length, l.end)if (img) {let im = span(l.label, f)im.image = trueim.href = l.hrefim.src = acc + s.slice(i, l.end)out[] = im} else {let inner = parseInline(l.label, { strong = f.strong em = f.em strike = f.strike href = l.href })if (inner.length == 0) {let e0 = span('', f)e0.href = l.hrefinner[] = e0}inner[0].src = acc + open + inner[0].srcinner[inner.length - 1].src = inner[inner.length - 1].src + tailSrcfor (x of inner) { out[] = x }}acc = ''i = l.end}} else if (f.href == '' && c == 60 && i + 1 < n && (isUrlStart(s, i + 1) || s.slice(i + 1, i + 8).toLowerCase() == 'mailto:')) {// <https://…>let e = s.indexOf('>', i + 1)let url = e > 0 ? s.slice(i + 1, e) : ''let h = safeHref(url)if (e < 0 || h == null) {buf = buf + '<'acc = acc + '<'i = i + 1} else {if (buf != '') {let sp3 = span(buf, f)sp3.src = accout[] = sp3acc = ''}buf = ''let al = span(url, f)al.href = hal.src = acc + s.slice(i, e + 1)acc = ''out[] = ali = e + 1}} else if (f.href == '' && (c == 104 || c == 72) && (i == 0 || !isAlnumC(s.charCodeAt(i - 1))) && isUrlStart(s, i)) {// a bare http(s):// URLlet e2 = urlEnd(s, i)let url2 = s.slice(i, e2)let h2 = safeHref(url2)if (h2 == null) {buf = buf + s[i]acc = acc + s[i]i = i + 1} else {if (buf != '') {let sp4 = span(buf, f)sp4.src = accout[] = sp4acc = ''}buf = ''let bl = span(url2, f)bl.href = h2bl.src = acc + url2acc = ''out[] = bli = e2}} else if (c == 42 || c == 95 || c == 126) {// * and _: emphasis (1), strong (2), both (3); ~~: strikelet k = iwhile (k < n && s.charCodeAt(k) == c) { k = k + 1 }let run = k - ilet prev = i > 0 ? s.charCodeAt(i - 1) : 32let next = k < n ? s.charCodeAt(k) : 32let canOpen = !isSpaceC(next) && (c != 95 || !isAlnumC(prev))let canClose = !isSpaceC(prev) && (c != 95 || !isAlnumC(next))let closes = falselet opens = falseif (c == 126) {closes = run == 2 && canClose && f.strikeopens = !closes && run == 2 && canOpen && !f.strike && hasCloser(s, k, c, run)} else {let wantStrong = run == 2 || run == 3let wantEm = run == 1 || run == 3closes = canClose && run <= 3 && (!wantStrong || (f.strong && strongC == c)) && (!wantEm || (f.em && emC == c))opens = !closes && canOpen && run <= 3 && (!wantStrong || !f.strong) && (!wantEm || !f.em) && hasCloser(s, k, c, run)}if (closes || opens) {if (buf != '') {let sp5 = span(buf, f)sp5.src = accout[] = sp5acc = ''}buf = ''acc = acc + s.slice(i, k)if (c == 126) {f.strike = opens} else {if (run == 2 || run == 3) {f.strong = opensstrongC = c}if (run == 1 || run == 3) {f.em = opensemC = c}}} else {buf = buf + s.slice(i, k)acc = acc + s.slice(i, k)}i = k} else {buf = buf + s[i]acc = acc + s[i]i = i + 1}}if (buf != '') {let sp6 = span(trimEndSp(buf), f)sp6.src = accout[] = sp6} else if (acc != '') {if (out.length > 0) {out[out.length - 1].src = out[out.length - 1].src + acc} else {let sp7 = span('', f)sp7.src = accout[] = sp7}}return out}static plain = { strong = false em = false strike = false href = '' }// the spans of an inline text, with the View's flags: exactly one of isBr, isCode,// isImage, isLink, isStrongEm, isStrong, isEm, isStrike, isText is truestatic spansOf = (t) => {let out = []for (s of parseInline(t, plain)) {s.isBr = s.brs.isCode = !s.br && s.codes.isImage = !s.br && !s.code && s.images.isLink = !s.br && !s.code && !s.image && s.href != ''let fmt = !s.br && !s.code && !s.image && s.href == ''s.isStrongEm = fmt && s.strong && s.ems.isStrong = fmt && s.strong && !s.ems.isEm = fmt && s.em && !s.strongs.isStrike = fmt && s.strike && !s.strong && !s.ems.isText = fmt && !s.strong && !s.em && !s.strikeout[] = s}return out}// ---- blocks ---------------------------------------------------------------------------static isBlank = (line) => { return line.trim() == '' }static indentOf = (line) => {let col = 0let i = 0while (i < line.length && (line.charCodeAt(i) == 32 || line.charCodeAt(i) == 9)) {col = line.charCodeAt(i) == 9 ? col + 4 - (col % 4) : col + 1i = i + 1}return col}// the line without its first n columns of indentationstatic stripCols = (line, n) => {let col = 0let i = 0while (i < line.length && col < n && (line.charCodeAt(i) == 32 || line.charCodeAt(i) == 9)) {col = line.charCodeAt(i) == 9 ? col + 4 - (col % 4) : col + 1i = i + 1}return line.slice(i)}static trimStartSp = (t) => {let i = 0while (i < t.length && (t.charCodeAt(i) == 32 || t.charCodeAt(i) == 9)) { i = i + 1 }return t.slice(i)}// a heading line (≤ 3 spaces in, 1–6 '#', then a space or the end) → { level, text, trail }static headingOf = (line) => {if (indentOf(line) > 3) { return null }let t = trimEndSp(trimStartSp(line))let k = 0while (k < t.length && t.charCodeAt(k) == 35) { k = k + 1 }if (k == 0 || k > 6) { return null }if (k < t.length && t.charCodeAt(k) != 32 && t.charCodeAt(k) != 9) { return null }let body = trimStartSp(t.slice(k))let trail = ''// a closing run of '#' after a space is the heading's, not its text'slet e = body.lengthwhile (e > 0 && body.charCodeAt(e - 1) == 35) { e = e - 1 }if (e < body.length && (e == 0 || body.charCodeAt(e - 1) == 32 || body.charCodeAt(e - 1) == 9)) {let e2 = ewhile (e2 > 0 && (body.charCodeAt(e2 - 1) == 32 || body.charCodeAt(e2 - 1) == 9)) { e2 = e2 - 1 }trail = e2 == 0 ? body : body.slice(e2)body = body.slice(0, e2)}return { level = k text = body trail = trail }}// a list item line → { indent, ordered, num, marker, text, col (where its text starts) }static itemOf = (line) => {let ind = indentOf(line)if (ind > 3) { return null }let t = trimStartSp(line)let mlen = 0let ordered = falselet num = 1let marker = ''let c0 = t.length > 0 ? t.charCodeAt(0) : 0if (c0 == 45 || c0 == 42 || c0 == 43) {mlen = 1marker = t[0]} else {let k = 0while (k < t.length && k < 9 && t.charCodeAt(k) >= 48 && t.charCodeAt(k) <= 57) { k = k + 1 }if (k == 0 || k >= t.length) { return null }let d = t.charCodeAt(k)if (d != 46 && d != 41) { return null }mlen = k + 1ordered = truenum = toNumber(t.slice(0, k))marker = t[k]}if (mlen < t.length && t.charCodeAt(mlen) != 32 && t.charCodeAt(mlen) != 9) { return null }let rest = t.slice(mlen)let text = trimStartSp(rest)let pad = rest.length - text.lengthif (pad == 0 || pad > 4) { pad = 1 }return { indent = ind ordered = ordered num = num marker = marker text = text col = ind + mlen + pad }}// a code fence line (``` or ~~~, ≥ 3) → { ch, len, info, indent } or nullstatic fenceOf = (line) => {let ind = indentOf(line)if (ind > 3) { return null }let t = trimStartSp(line)if (t.length < 3) { return null }let c = t.charCodeAt(0)if (c != 96 && c != 126) { return null }let k = 0while (k < t.length && t.charCodeAt(k) == c) { k = k + 1 }if (k < 3) { return null }// an info string after ``` must not contain a backtickif (c == 96 && t.slice(k).includes('`')) { return null }return { ch = c len = k run = t.slice(0, k) info = t.slice(k).trim() indent = ind }}static closesFence = (line, fc) => {if (indentOf(line) > 3) { return false }let t = line.trim()let k = 0while (k < t.length && t.charCodeAt(k) == fc.ch) { k = k + 1 }return k >= fc.len && k == t.length}// a line of 3+ of one of - * _ (spaces between allowed) and nothing elsestatic isHrLine = (line) => {if (indentOf(line) > 3) { return false }let t = line.trim()if (t.length < 3) { return false }let c = t.charCodeAt(0)if (c != 45 && c != 42 && c != 95) { return false }let n = 0let i = 0while (i < t.length) {let d = t.charCodeAt(i)if (d == c) { n = n + 1 } else if (d != 32 && d != 9) { return false }i = i + 1}return n >= 3}// `> text` → the text after the marker and one space, or nullstatic quoteOf = (line) => {if (indentOf(line) > 3) { return null }let t = trimStartSp(line)if (!t.startsWith('>')) { return null }let r = t.slice(1)if (r.startsWith(' ')) { r = r.slice(1) }return r}// a table row's cell texts: `| a | b |` → ['a', 'b']; `\|` and code spans do not splitstatic cellTexts = (line) => {let t = line.trim()if (t.startsWith('|')) { t = t.slice(1) }if (t.endsWith('|') && !t.endsWith(BS + '|')) { t = t.slice(0, t.length - 1) }let out = []let cur = ''let i = 0while (i < t.length) {let c = t.charCodeAt(i)if (c == 92 && i + 1 < t.length) {cur = cur + t.slice(i, i + 2)i = i + 2} else if (c == 96) {let k = iwhile (k < t.length && t.charCodeAt(k) == 96) { k = k + 1 }let close = runAt(t, k, 96, k - i, false)let end = close < 0 ? k : close + (k - i)cur = cur + t.slice(i, end)i = end} else if (c == 124) {out[] = cur.trim()cur = ''i = i + 1} else {cur = cur + t[i]i = i + 1}}out[] = cur.trim()return out}static cellsOf = (line, count, align) => {let texts = cellTexts(line)let out = []let i = 0while (i < count) {out[] = { spans = spansOf(i < texts.length ? texts[i] : '') align = i < align.length ? align[i] : '' }i = i + 1}return out}// is this the `|---|:--:|` line under a table head?static isSepLine = (line) => {let t = line.trim()if (!t.includes('-')) { return false }if (!t.includes('|') && !t.includes(':')) { return false }let i = 0while (i < t.length) {let d = t.charCodeAt(i)if (d != 124 && d != 45 && d != 58 && d != 32 && d != 9) { return false }i = i + 1}return true}static alignOf = (sep) => {let out = []for (c of cellTexts(sep)) {let l = c.startsWith(':')let r = c.endsWith(':')out[] = l && r ? 'center' : (r ? 'right' : (l ? 'left' : ''))}return out}static tableAt = (&lines, i) => {if (i + 1 >= lines.length) { return false }let head = lines[i]if (!head.includes('|') || indentOf(head) > 3) { return false }if (!isSepLine(lines[i + 1])) { return false }return cellTexts(head).length == cellTexts(lines[i + 1]).length}// may this line start a block in the middle of a paragraph?static interrupts = (&lines, j) => {let line = lines[j]if (fenceOf(line) != null || headingOf(line) != null || isHrLine(line) || quoteOf(line) != null) { return true }let it = itemOf(line)if (it != null && it.text != '' && (!it.ordered || it.num == 1)) { return true }return tableAt(&lines, j)}static block = (kind, gap, raw) => {let b = { type = kind gap = gap }// the View's conditions: it takes a flag, never an expressionb.isP = kind == 'p'b.isHeading = kind == 'heading'b.isCode = kind == 'code'b.isList = kind == 'list'b.isQuote = kind == 'quote'b.isTable = kind == 'table'b.isHr = kind == 'hr'b.isBare = false// blank lines that held spaces are kept as writtenlet spaced = falsefor (r of raw) { if (r != '') { spaced = true } }if (spaced) { b.blanks = raw }return b}// the item lines of one list, from lines[i] (an item) on → { list, next }static listAt = (&lines, i, gap, raw) => {let n = lines.lengthlet first = itemOf(lines[i])let lst = block('list', gap, raw)lst.ordered = first.orderedlst.isOl = first.orderedlst.isUl = !first.orderedlst.start = first.numlst.marker = first.markerlst.indent = first.indentlst.tight = truelet items = []let j = ilet itemGap = 0let going = truelet endAt = nwhile (going) {let it = itemOf(lines[j])let content = [it.text]// what each content line lost to the item — written back as it waslet pads = [lines[j].slice(0, lines[j].length - it.text.length)]let base = it.indentlet cont = -1let k = j + 1let blanks = 0let inItem = truewhile (inItem && k < n) {let l = lines[k]if (isBlank(l)) {blanks = blanks + 1k = k + 1} else {let ind = indentOf(l)if (ind >= base + 2) {if (cont < 0) { cont = ind < it.col ? ind : it.col }let b = 0while (b < blanks) {content[] = ''pads[] = lines[k - blanks + b]b = b + 1}blanks = 0let body = stripCols(l, cont)content[] = bodypads[] = l.slice(0, l.length - body.length)k = k + 1} else if (blanks == 0 && !isBlank(content[content.length - 1]) && itemOf(l) == null && !interrupts(&lines, k)) {// a lazy continuation of the item's paragraphlet lz = trimStartSp(l)content[] = lzpads[] = l.slice(0, l.length - lz.length)k = k + 1} else {inItem = false}}}let task = nulllet t0 = content[0]if (t0.startsWith('[ ] ') || t0 == '[ ]') {task = false} else if (t0.startsWith('[x] ') || t0 == '[x]') {task = true}if (task != null) {pads[0] = pads[0] + t0.slice(0, 4)content[0] = t0.slice(4)}let sub = parseLines(content)if (items.length > 0 && itemGap > 0) { lst.tight = false }let bi = 0for (sb of sub) {if (bi > 0 && sb.gap > 0) { lst.tight = false }bi = bi + 1}items[] = { gap = itemGap num = it.num task = task cont = cont < 0 ? it.col : cont pads = pads blocks = sub isTask = task != null done = task == true }going = falseendAt = k - blanksif (k < n) {let nx = itemOf(lines[k])if (nx != null && nx.ordered == first.ordered && nx.marker == first.marker && nx.indent < base + 2 && !isHrLine(lines[k])) {itemGap = blanksj = kgoing = true}}}// a TIGHT list's paragraphs are its items' lines: the View writes them without a <p>if (lst.tight) {for (it2 of items) {for (b2 of it2.blocks) {if (b2.type == 'p') {b2.isP = falseb2.isBare = true}}}}lst.items = itemsreturn { list = lst next = endAt }}// lines → blocksstatic parseLines = (&lines) => {let out = []let gap = 0let blanks = []let i = 0let n = lines.lengthwhile (i < n) {let line = lines[i]let fence = fenceOf(line)if (isBlank(line)) {gap = gap + 1blanks[] = linei = i + 1} else if (indentOf(line) >= 4) {// an indented code block: indented lines, and blank lines between themlet j = ilet more = truewhile (j < n && more) {if (isBlank(lines[j])) {let k = jwhile (k < n && isBlank(lines[k])) { k = k + 1 }if (k < n && indentOf(lines[k]) >= 4) { j = k } else { more = false }} else if (indentOf(lines[j]) >= 4) {j = j + 1} else {more = false}}let code = ''let k2 = iwhile (k2 < j) {code = code + (isBlank(lines[k2]) ? '' : stripCols(lines[k2], 4)) + NLk2 = k2 + 1}let cb = block('code', gap, blanks)cb.code = codecb.lang = ''cb.langClass = ''cb.info = ''cb.fence = ''cb.closed = trueout[] = cbgap = 0blanks = []i = j} else if (fence != null) {let j = i + 1let closed = falselet code = ''let closeSrc = ''let cpads = []while (j < n && !closed) {if (closesFence(lines[j], fence)) {closed = truecloseSrc = lines[j]} else {let cl = stripCols(lines[j], fence.indent)code = code + cl + NLcpads[] = lines[j].slice(0, lines[j].length - cl.length)}j = j + 1}let fb = block('code', gap, blanks)fb.code = codefb.info = fence.infolet sp = fence.info.indexOf(' ')fb.lang = sp < 0 ? fence.info : fence.info.slice(0, sp)fb.langClass = fb.lang == '' ? '' : 'language-' + fb.langfb.fence = fence.runfb.closed = closedfb.open = linefb.close = closeSrcif (fence.indent > 0) { fb.pads = cpads }out[] = fbgap = 0blanks = []i = j} else if (isHrLine(line)) {let hb = block('hr', gap, blanks)hb.src = lineout[] = hbgap = 0blanks = []i = i + 1} else if (headingOf(line) != null) {let h = headingOf(line)let hd = block('heading', gap, blanks)hd.level = h.levelhd.isH1 = h.level == 1hd.isH2 = h.level == 2hd.isH3 = h.level == 3hd.isH4 = h.level == 4hd.isH5 = h.level == 5hd.isH6 = h.level == 6hd.spans = spansOf(h.text)hd.trail = h.trailhd.src = lineout[] = hdgap = 0blanks = []i = i + 1} else if (quoteOf(line) != null) {let ql = []let qp = []let j = iwhile (j < n && quoteOf(lines[j]) != null) {let qt = quoteOf(lines[j])ql[] = qtqp[] = lines[j].slice(0, lines[j].length - qt.length)j = j + 1}let qb = block('quote', gap, blanks)// blank lines at the quote's end belong to it (`>` alone), not to what followslet qtail = 0while (ql.length > 0 && isBlank(ql[ql.length - 1])) {ql.pop()qtail = qtail + 1}qb.blocks = parseLines(ql)qb.tail = qtailqb.pads = qpout[] = qbgap = 0blanks = []i = j} else if (tableAt(&lines, i)) {let count = cellTexts(line).lengthlet tb = block('table', gap, blanks)tb.align = alignOf(lines[i + 1])tb.head = { cells = cellsOf(line, count, tb.align) src = line }tb.sep = lines[i + 1]tb.rows = []let j = i + 2while (j < n && !isBlank(lines[j]) && lines[j].includes('|')) {tb.rows[] = { cells = cellsOf(lines[j], count, tb.align) src = lines[j] }j = j + 1}out[] = tbgap = 0blanks = []i = j} else if (itemOf(line) != null) {let r = listAt(&lines, i, gap, blanks)out[] = r.listgap = 0blanks = []i = r.next} else {let para = [line]let j = i + 1while (j < n && !isBlank(lines[j]) && !interrupts(&lines, j)) {para[] = lines[j]j = j + 1}let pb = block('p', gap, blanks)pb.spans = spansOf(para.join(NL))out[] = pbgap = 0blanks = []i = j}}return out}// the Markdown text → the document (see the header)static parse = (text) => {let lines = []// a CR before a newline (Windows line ends) is dropped; a document whose every// line ends in CR LF is written back that way (`eol`)let crs = 0for (l of (text == null ? '' : '' + text).split(NL)) {if (l.length > 0 && l.charCodeAt(l.length - 1) == 13) {crs = crs + 1lines[] = l.slice(0, l.length - 1)} else {lines[] = l}}let crlf = crs > 0 && crs == lines.length - 1let tail = 0let end = ''while (lines.length > 1 && isBlank(lines[lines.length - 1])) {end = NL + lines.pop() + endtail = tail + 1}let doc = { blocks = [] tail = tail }if (crlf) {// the CR LF pair, taken from the text itself (the language writes no CR)let at = ('' + text).indexOf(NL)doc.eol = ('' + text).slice(at - 1, at + 1)}// trailing blank lines that held spaces are kept as writtenif (end != rep(NL, tail)) { doc.end = end }if (lines.length == 1 && isBlank(lines[0])) { return doc }doc.blocks = parseLines(&lines)return doc}// ---- writing ------------------------------------------------------------------------------static flagOf = (v) => { return v == true }static strOf = (v) => { return v == null ? '' : '' + v }// what a span MEANS — everything but its sourcestatic spanKey = (s) => {return [strOf(s.text), flagOf(s.strong), flagOf(s.em), flagOf(s.strike), flagOf(s.code), strOf(s.href), flagOf(s.image), flagOf(s.br)]}static sameSpans = (a, b) => {let ka = []for (x of a) {// an empty text span carries source onlyif (!(strOf(x.text) == '' && !flagOf(x.code) && !flagOf(x.image))) { ka[] = spanKey(x) }}let kb = []for (y of b) {if (!(strOf(y.text) == '' && !flagOf(y.code) && !flagOf(y.image))) { kb[] = spanKey(y) }}return JSON.stringify(ka) == JSON.stringify(kb)}// text as Markdown that reads back as the same textstatic escapeText = (t) => {let out = ''let i = 0while (i < t.length) {let c = t.charCodeAt(i)let prev = i > 0 ? t.charCodeAt(i - 1) : 32let next = i + 1 < t.length ? t.charCodeAt(i + 1) : 32if (c == 92 || c == 42 || c == 96 || c == 91 || c == 93 || c == 60 || c == 124 || (c == 126 && (prev == 126 || next == 126))) {out = out + BS + t[i]} else if (c == 95 && (!isAlnumC(prev) || !isAlnumC(next))) {out = out + BS + t[i]} else {out = out + t[i]}i = i + 1}return out}static codeMd = (t) => {let run = 1while (t.includes(rep('`', run))) { run = run + 1 }let pad = t.startsWith('`') || t.endsWith('`') ? ' ' : ''return rep('`', run) + pad + t + pad + rep('`', run)}static targetMd = (h) => { return h.replaceAll(')', '%29').replaceAll(' ', '%20') }// spans → canonical inline Markdown: a link outermost, then ~~, **, *static canonicalInline = (spans) => {let out = ''let cur = { href = '' strike = false strong = false em = false }for (s of spans) {let want = { href = s.image ? '' : strOf(s.href) strike = flagOf(s.strike) strong = flagOf(s.strong) em = flagOf(s.em) }if (flagOf(s.br)) { want = { href = cur.href strike = cur.strike strong = cur.strong em = cur.em } }// the outermost level that changes; everything inside it closes and reopenslet lvl = 4if (want.em != cur.em) { lvl = 3 }if (want.strong != cur.strong) { lvl = 2 }if (want.strike != cur.strike) { lvl = 1 }if (want.href != cur.href) { lvl = 0 }if (lvl < 4) {if (cur.em && lvl <= 3) { out = out + '*' }if (cur.strong && lvl <= 2) { out = out + '**' }if (cur.strike && lvl <= 1) { out = out + '~~' }if (cur.href != '' && lvl == 0) { out = out + '](' + targetMd(cur.href) + ')' }if (want.href != '' && lvl == 0) { out = out + '[' }if (want.strike && lvl <= 1) { out = out + '~~' }if (want.strong && lvl <= 2) { out = out + '**' }if (want.em && lvl <= 3) { out = out + '*' }cur = want}if (flagOf(s.br)) {out = out + NL} else if (flagOf(s.code)) {out = out + codeMd(strOf(s.text))} else if (flagOf(s.image)) {out = out + ') + ')'} else {out = out + escapeText(strOf(s.text))}}if (cur.em) { out = out + '*' }if (cur.strong) { out = out + '**' }if (cur.strike) { out = out + '~~' }if (cur.href != '') { out = out + '](' + targetMd(cur.href) + ')' }return out}// spans → inline Markdown: the source they came from when it still reads as themstatic inlineMd = (spans) => {if (spans == null) { return '' }let cand = ''let all = truefor (s of spans) {if (s.src == null) { all = false } else { cand = cand + s.src }}if (all && sameSpans(spansOf(cand), spans)) { return cand }return canonicalInline(spans)}// a written paragraph line that would start a block gets its first character escapedstatic guardLine = (l) => {let t = trimStartSp(l)if (t == '') { return l }let lead = l.slice(0, l.length - t.length)if (headingOf(t) != null || fenceOf(t) != null || isHrLine(t) || quoteOf(t) != null || t.startsWith('+ ') || t.startsWith('- ') || t.startsWith('= ')) {return lead + BS + t}let it = itemOf(t)if (it != null && it.ordered) {let k = 0while (k < t.length && t.charCodeAt(k) >= 48 && t.charCodeAt(k) <= 57) { k = k + 1 }return lead + t.slice(0, k) + BS + t.slice(k)}return l}static tableRowMd = (row) => {let cells = []for (c of row.cells) { cells[] = inlineMd(c.spans) }if (row.src != null) {// the row as written, when its cells (missing ones empty, extra ones dropped) still read the samelet texts = cellTexts(row.src)let same = truelet i = 0while (i < cells.length) {if ((i < texts.length ? texts[i] : '') != cells[i]) { same = false }i = i + 1}if (same) { return row.src }}return '| ' + cells.join(' | ') + ' |'}// one block → its linesstatic blockLines = (b) => {let out = []let kind = strOf(b.type)if (kind == 'p') {let md = inlineMd(b.spans)let src = truefor (s of b.spans) { if (s.src == null) { src = false } }for (l of md.split(NL)) { out[] = src && md == inlineMdSrc(b.spans) ? l : guardLine(l) }} else if (kind == 'heading') {let lv = b.level == null ? 1 : b.levelif (lv < 1) { lv = 1 }if (lv > 6) { lv = 6 }let md2 = inlineMd(b.spans).replaceAll(NL, ' ')let h = b.src == null ? null : headingOf(b.src)if (h != null && h.level == lv && h.trail == strOf(b.trail) && h.text == md2) {out[] = b.src} else {out[] = rep('#', lv) + (md2 == '' ? '' : ' ' + md2) + strOf(b.trail)}} else if (kind == 'code') {let code = strOf(b.code)let ls = code.split(NL)if (code.endsWith(NL)) { ls.pop() }if (code == '') { ls = [] }if (strOf(b.fence) == '' && b.fence != null && code.trim() != '') {for (l of ls) { out[] = l == '' ? '' : ' ' + l }} else {let fence = strOf(b.fence)if (fence == '') { fence = '```' }let fc = fence.charCodeAt(0)// a fence longer than any fence-like line inside the codefor (l of ls) {let t = l.trim()let k = 0while (k < t.length && t.charCodeAt(k) == fc) { k = k + 1 }if (k >= fence.length && k == t.length) { fence = rep(fence[0], k + 1) }}let info = strOf(b.info)if (info == '') { info = strOf(b.lang) }let fo = b.open == null ? null : fenceOf(b.open)let asWritten = fo != null && fo.run == fence && fo.info == infoout[] = asWritten ? b.open : fence + infolet cp = asWritten && b.pads != null && b.pads.length == ls.length ? b.pads : nulllet ci = 0for (l of ls) {out[] = cp != null ? cp[ci] + l : lci = ci + 1}if (b.closed != false) { out[] = asWritten && b.close != null && closesFence(b.close, fo) ? b.close : fence }}} else if (kind == 'hr') {out[] = isHrLine(strOf(b.src)) ? strOf(b.src) : '---'} else if (kind == 'quote') {let ql = linesOf(b.blocks == null ? [] : b.blocks, false)let qt = 0while (qt < (b.tail == null ? 0 : b.tail)) {ql[] = ''qt = qt + 1}let qp = b.pads != null && b.pads.length == ql.length ? b.pads : nulllet qi = 0for (l of ql) {if (qp != null && quoteOf(qp[qi] + l) != null) {out[] = qp[qi] + l} else {out[] = l == '' ? '>' : '> ' + l}qi = qi + 1}} else if (kind == 'table') {let head = b.head == null ? { cells = [] } : b.headlet cols = head.cells.lengthout[] = tableRowMd(head)let sep = strOf(b.sep)let al = b.align == null ? [] : b.alignif (!isSepLine(sep) || JSON.stringify(alignOf(sep)) != JSON.stringify(al) || cellTexts(sep).length != cols) {let parts = []let i = 0while (i < cols) {let a = i < al.length ? al[i] : ''parts[] = a == 'center' ? ':---:' : (a == 'right' ? '---:' : (a == 'left' ? ':---' : '---'))i = i + 1}sep = '| ' + parts.join(' | ') + ' |'}out[] = sepfor (r of (b.rows == null ? [] : b.rows)) { out[] = tableRowMd(r) }} else if (kind == 'list') {let ordered = b.ordered == truelet marker = strOf(b.marker)if (ordered && marker != '.' && marker != ')') { marker = '.' }if (!ordered && marker != '-' && marker != '*' && marker != '+') { marker = '-' }let lead = rep(' ', b.indent == null ? 0 : b.indent)let start = b.start == null ? 1 : b.startlet idx = 0for (it of b.items) {let g = 0while (g < (it.gap == null ? 0 : it.gap)) {out[] = ''g = g + 1}let num = it.num == null ? start + idx : it.numlet mark = lead + (ordered ? '' + num + marker : marker)let task = it.task == true ? '[x] ' : (it.task == false ? '[ ] ' : '')let cont = it.cont == null ? mark.length + 1 : it.contlet pad = rep(' ', cont)let ls = linesOf(it.blocks == null ? [] : it.blocks, true)// the item's lines as they were written, while they still fitlet ip = it.pads != null && it.pads.length == (ls.length == 0 ? 1 : ls.length) && it.pads[0].trim() == (mark + ' ' + task).trim() ? it.pads : nullif (ls.length == 0) {out[] = ip != null ? ip[0] : mark + (task == '' ? '' : ' ' + trimEndSp(task))} else {let fl = 0for (l of ls) {if (fl == 0) {out[] = ip != null ? ip[0] + l : (l == '' && task == '' ? mark : mark + ' ' + task + l)} else if (ip != null) {out[] = ip[fl] + l} else {out[] = l == '' ? '' : pad + l}fl = fl + 1}}idx = idx + 1}}return out}static inlineMdSrc = (spans) => {let cand = ''for (s of spans) { cand = cand + strOf(s.src) }return cand}// blocks → lines, with their blank lines between them. A block with no `gap` (built// by hand) gets one blank line before it — none inside a list item (`inItem`), except// between two paragraphs, which would otherwise read back as onestatic linesOf = (blocks, inItem) => {let out = []let bi = 0let prevKind = ''for (b of blocks) {let g = 0let want = b.gapif (want == null) {want = bi == 0 ? 0 : 1if (inItem && !(prevKind == 'p' && b.type == 'p')) { want = 0 }}prevKind = strOf(b.type)let raw = b.blanks != null && b.blanks.length == want ? b.blanks : nullwhile (g < want) {out[] = raw != null ? raw[g] : ''g = g + 1}for (l of blockLines(b)) { out[] = l }bi = bi + 1}return out}// the document (or a bare array of blocks) → Markdown textstatic serialize = (doc) => {if (doc == null) { return '' }let blocks = doclet tail = 0if (doc.blocks != null) {blocks = doc.blockstail = doc.tail == null ? 0 : doc.tail}let end = rep(NL, tail)if (doc.end != null && doc.end.split(NL).length == tail + 1 && doc.end.trim() == '') { end = doc.end }let out = linesOf(blocks, false).join(NL) + end// a CR LF document: every line end gets its CR backif (doc.eol != null && doc.eol.length == 2 && doc.eol.charCodeAt(0) == 13) { out = out.split(NL).join(doc.eol) }return out}
Branches
Latest commits
- 40627a89ident#33: the time zone section's spacing moves into timezone.hlmre
- d389db08ident#33: the identity page's rules and the Notif. chip move into identity.hl's Stylemre
- ddda0b5bident#33: the identity row's parts move into identitylist.hl's Stylemre
- 47e516afident#33 ident#34: the identity form's avatar rules move into identityform.hl; the preview and Remove button are hidden with the hidden attribute instead of built class strings (avatarPreviewClass, avatarRemoveClass gone)mre
- 5cb5cf0eident#33: the code field's look moves into codestep.hl's Stylemre
- f421cd60ident#33: the shell's own rules (user menu address, offline note, network probe) move into main.hl's Stylemre
- c512fb96Merge branch 'f4-homesplit' into mainIdent
- 07d1717c|||PR ident#40 home.hl is split into components, one per area: email step, identity form, identity list, app identity choice, time zone; each moves its faces with it, the email step is shared with embed.hl (#40.3, rest of #40.2)mre
- 59e8fcc1ident#40.3: the app's identity choice is one component (components/chooseidentity.hl); its face chooseIdentity moves with itmre
- e23efdfcident#40.3: the identity list is one component (components/identitylist.hl); its delete and face dropIdentity move with itmre
- e24b59a6ident#40.3: the time zone is one component (components/timezone.hl); its face changeTimeZone moves with itmre
- 8cbc5717ident#40.3: the email step is one component (components/emailstep.hl) placed by home.hl and embed.hlmre
- 6fad3bd2Merge branch 'f3-codestep' into mainIdent
- 51e387f2|||PR ident#40 the code step is one component (components/codestep.hl) placed by home.hl and embed.hl; its verify face, setCode, browserZone and verify call exist once (#40.2)mre
- c28bddeeMerge branch 'f2-shell' into mainIdent
- c3a40ff6|||PR ident#40 one shell for the app and /start (account part off on /start, #40.1); startshell.hl removed; unused signOut faces gone (#40.4)mre
- 060f3870ident#40.4: use the shell sign-out faces in regression gatesmre
- 9b94aa6aMerge branch 'f1b-cleanup' into mainIdent
- edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
- 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre