dymokomi/luce-prism
Source of release 0.6.1
0.6.1 / src / codecs / markdown_inline.lucb
## Legacy Markdown inline grammar, including variable-length code spans.
from codecs.common import append, set_text, find
from storage import Buffer
from model import DocumentData
from types import limit_exceeded
func flush(doc: DocumentData*, parent: str, text: Buffer*) -> !:
if text.used == 0:
return
var child = try append(doc, parent, "text")
defer child.close()
try set_text(doc, child.view(), "text", text.view())
text.used = 0
pub func parse(doc: DocumentData*, parent: str, text: str, depth: usize = 0) -> !:
if depth > 128:
error(limit_exceeded, "Markdown inline nesting exceeds 128")
var plain: Buffer
defer plain.close()
var i: usize = 0
while i < text.length:
let byte = text.bytes[i]
if byte == '\\' and i + 1 < text.length:
try plain.byte(text.bytes[i + 1])
i += 2
continue
if byte == '`':
var length: usize = 0
while i + length < text.length and text.bytes[i + length] == '`':
length += 1
var end = i + length
while end < text.length:
if text.bytes[end] == '`':
var run: usize = 0
while end + run < text.length and text.bytes[end + run] == '`':
run += 1
if run == length:
break
end += run
else:
end += 1
if end < text.length:
var content = (str)text.bytes[i + length..<end]
var nonspace = false
for c in content.bytes:
if c != ' ':
nonspace = true
if content.length >= 2 and content.bytes[0] == ' ' and content.bytes[content.length - 1] == ' ' and nonspace:
content = (str)content.bytes[1..<content.length - 1]
try flush(doc, parent, &plain)
var child = try append(doc, parent, "code")
defer child.close()
try set_text(doc, child.view(), "text", content)
i = end + length
continue
let image = byte == '!' and i + 1 < text.length and text.bytes[i + 1] == '['
if byte == '[' or image:
let start = i + (2 if image else 1)
if let right = find(text, "]", start):
if right + 1 < text.length and text.bytes[right + 1] == '(':
if let end = find(text, ")", right + 2):
try flush(doc, parent, &plain)
var child = try append(doc, parent, "image" if image else "link")
defer child.close()
try set_text(doc, child.view(), "src" if image else "href", (str)text.bytes[right + 2..<end])
if image:
try set_text(doc, child.view(), "alt", (str)text.bytes[start..<right])
else:
try parse(doc, child.view(), (str)text.bytes[start..<right], depth + 1)
i = end + 1
continue
if byte == '*' or byte == '_':
var consumed = false
let lengths: usize[2] = [2, 1]
for length in lengths:
if i + length > text.length or (length == 2 and text.bytes[i + 1] != byte):
continue
let delimiter = (str)text.bytes[i..<i + length]
if let end = find(text, delimiter, i + length):
if end > i + length:
try flush(doc, parent, &plain)
var child = try append(doc, parent, "strong" if length == 2 else "emphasis")
defer child.close()
try parse(doc, child.view(), (str)text.bytes[i + length..<end], depth + 1)
i = end + length
consumed = true
break
if consumed:
continue
try plain.byte(byte)
i += 1
try flush(doc, parent, &plain)