Commit 54b288bf authored by Miguel Angel Reina Ortega's avatar Miguel Angel Reina Ortega
Browse files

Adding figure caption as it appears in the markdown file

parent 2507da6a
Loading
Loading
Loading
Loading
Loading
+76 −4
Changes for generateBaseline/mermaid-filter.js: 76 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -20,7 +20,57 @@ function isMermaidBlock(el) {
		el.c[0][1].indexOf('mermaid') >= 0;
}

function renderMermaid(el) {
function stringifyInlines(inlines) {
	if (!inlines) {
		return '';
	}
	if (typeof inlines === 'string') {
		return inlines;
	}
	if (Array.isArray(inlines)) {
		return inlines.map(stringifyInlines).join('');
	}
	if (inlines && typeof inlines === 'object') {
		if (inlines.t === 'Str') {
			return inlines.c || '';
		}
		if (inlines.t === 'Space' || inlines.t === 'SoftBreak') {
			return ' ';
		}
		if (Object.prototype.hasOwnProperty.call(inlines, 'c')) {
			return stringifyInlines(inlines.c);
		}
	}
	return '';
}

function isFigureCaptionPara(el) {
	if (!el || el.t !== 'Para' || !Array.isArray(el.c) || el.c.length === 0) {
		return false;
	}
	if (el.c[0].t !== 'Strong') {
		return false;
	}
	return /^Figure\s/.test(stringifyInlines(el.c).trim());
}

function figureCaptionInlines(el) {
	if (el.c.length === 1 && el.c[0].t === 'Strong' && Array.isArray(el.c[0].c)) {
		return el.c[0].c;
	}
	const out = [];
	for (let i = 0; i < el.c.length; i++) {
		const inline = el.c[i];
		if (inline && inline.t === 'Strong' && Array.isArray(inline.c)) {
			Array.prototype.push.apply(out, inline.c);
		} else {
			out.push(inline);
		}
	}
	return out;
}

function renderMermaid(el, caption) {
	const attrs = el.c[0];
	const content = el.c[1];
	const id = attrs[0] || '';
@@ -64,23 +114,45 @@ function renderMermaid(el) {
		fs.rmSync(tmp, { recursive: true, force: true });
	} catch (e) { /* ignore */ }

	const fig = id.startsWith('fig:') ? 'fig:' : '';
	const captionInlines = Array.isArray(caption) ? caption : [];
	const fig = (id.startsWith('fig:') || captionInlines.length) ? 'fig:' : '';
	return {
		t: 'Para',
		c: [{
			t: 'Image',
			c: [[id, [], []], [], [src, fig]]
			c: [[id, [], []], captionInlines, [src, fig]]
		}]
	};
}

function walkBlocks(blocks) {
	const out = [];
	for (let i = 0; i < blocks.length; i++) {
		const el = blocks[i];
		if (isMermaidBlock(el)) {
			let caption = [];
			if (isFigureCaptionPara(blocks[i + 1])) {
				caption = figureCaptionInlines(blocks[i + 1]);
				i += 1;
			}
			out.push(renderMermaid(el, caption));
		} else {
			out.push(walk(el));
		}
	}
	return out;
}

function walk(node) {
	if (Array.isArray(node)) {
		if (node.some(isMermaidBlock)) {
			return walkBlocks(node);
		}
		return node.map(walk);
	}
	if (node && typeof node === 'object') {
		if (isMermaidBlock(node)) {
			return renderMermaid(node);
			return renderMermaid(node, []);
		}
		// Pandoc 3 JSON is {pandoc-api-version, meta, blocks}. Older filters
		// only walked `c`, so top-level mermaid CodeBlocks were left unchanged.
+29
Changes for generateBaseline/pandocFilter.py: 29 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -274,6 +274,31 @@ def replaceTableCaptions(progress:Progress, mdLines:list[str]) -> list[str]:
	return _lines


def _opens_mermaid_fence(line: str) -> bool:
	stripped = line.strip()
	if not stripped.startswith('```'):
		return False
	info = stripped[3:].strip()
	lang = info.split()[0] if info else ''
	return lang == 'mermaid' or 'mermaid' in lang


def _follows_mermaid_block(lines: list[str]) -> bool:
	"""True when the last non-empty line closes a ```mermaid fence."""
	idx = len(lines) - 1
	while idx >= 0 and lines[idx].strip() == '':
		idx -= 1
	if idx < 0 or lines[idx].strip() != '```':
		return False
	idx -= 1
	while idx >= 0:
		stripped = lines[idx].strip()
		if stripped.startswith('```'):
			return _opens_mermaid_fence(lines[idx])
		idx -= 1
	return False


def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]:
	"""	Replace figure captions with a pandoc figure caption.
	"""
@@ -290,6 +315,10 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]:
			_lines.append(line)
			continue
		if matches:
			# Leave mermaid captions in place for mermaid-filter (no ![ ] yet).
			if _follows_mermaid_block(_lines):
				_lines.append(line)
				continue
			# Replace the previous figure markdown name with the captions
			_idx = len(_lines) - 1
			while _idx >= 0 and _lines[_idx].count('![') == 0: