"""Render the standalone manuscript with ReportLab; equations are typeset math images.
The Markdown source is the searchable, machine-readable equation source.
"""
from pathlib import Path
import re,html,textwrap,hashlib
from io import BytesIO
import matplotlib
matplotlib.use('Agg')
from matplotlib.mathtext import math_to_image
from matplotlib.font_manager import FontProperties
from PIL import Image as PILImage
from reportlab.pdfgen import canvas
from reportlab.platypus import SimpleDocTemplate,Paragraph,Spacer,PageBreak,Image,Table,TableStyle,Preformatted,KeepTogether
from reportlab.lib import colors
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.enums import TA_CENTER,TA_LEFT
from reportlab.lib.pagesizes import A4
ROOT=Path(__file__).resolve().parents[1]
import matplotlib as mpl
FONTROOT=Path(mpl.get_data_path())/'fonts/ttf'
for name,filename in [('Body','DejaVuSerif.ttf'),('BodyBold','DejaVuSerif-Bold.ttf'),
('BodyItalic','DejaVuSerif-Italic.ttf'),('Sans','DejaVuSans.ttf'),('SansBold','DejaVuSans-Bold.ttf'),('Mono','DejaVuSansMono.ttf')]:
pdfmetrics.registerFont(TTFont(name,str(FONTROOT/filename)))
pdfmetrics.registerFontFamily('Body',normal='Body',bold='BodyBold',italic='BodyItalic',boldItalic='BodyBold')
pdfmetrics.registerFontFamily('Sans',normal='Sans',bold='SansBold',italic='Sans',boldItalic='SansBold')
ink=colors.HexColor('#203044');blue=colors.HexColor('#17647F');muted=colors.HexColor('#647386')
W,H=A4;M=47;CW=W-2*M
styles={
'body':ParagraphStyle('body',fontName='Body',fontSize=9.6,leading=13.9,spaceAfter=7.5,textColor=ink),
'title':ParagraphStyle('title',fontName='SansBold',fontSize=29,leading=34,spaceAfter=16,textColor=ink),
'subtitle':ParagraphStyle('subtitle',fontName='Sans',fontSize=15,leading=21,spaceAfter=18,textColor=blue),
'h2':ParagraphStyle('h2',fontName='SansBold',fontSize=14,leading=18,spaceBefore=16,spaceAfter=9,textColor=blue,keepWithNext=True),
'h3':ParagraphStyle('h3',fontName='SansBold',fontSize=11,leading=15,spaceBefore=12,spaceAfter=7,textColor=ink,keepWithNext=True),
'cell':ParagraphStyle('cell',fontName='Sans',fontSize=8.1,leading=11.2,textColor=ink),
'thead':ParagraphStyle('thead',fontName='SansBold',fontSize=8,leading=11,textColor=colors.white),
'caption':ParagraphStyle('caption',fontName='Sans',fontSize=8.3,leading=11.6,spaceAfter=12,textColor=muted),
'code':ParagraphStyle('code',fontName='Mono',fontSize=7.2,leading=10,spaceBefore=5,spaceAfter=10,textColor=ink),
'ref':ParagraphStyle('ref',fontName='Body',fontSize=8.1,leading=11.6,spaceAfter=6,textColor=ink,splitLongWords=True)
}
for style in styles.values():
style.allowWidows=0
style.allowOrphans=0
def fmt(s):
stash=[]
def save(x):
stash.append(x);return f'ZZTOKEN{len(stash)-1}ZZ'
s=re.sub(r'\[([^\]]+)\]\((https?://[^)]+)\)',lambda m:save(''+html.escape(m[1])+''),s)
s=re.sub(r'https?://[^\s<>]+',lambda m:save(''+html.escape(m[0])+''),s)
s=html.escape(s)
s=re.sub(r'\*\*(.+?)\*\*',r'\1',s)
s=re.sub(r'`([^`]+)`',r'\1',s)
for i,x in enumerate(stash):s=s.replace(f'ZZTOKEN{i}ZZ',x)
return s
class Doc(SimpleDocTemplate):
def afterFlowable(self,flowable):
if isinstance(flowable,Paragraph) and flowable.style.name=='h2':
t=flowable.getPlainText();k='sec'+hashlib.sha256(t.encode()).hexdigest()[:12]
self.canv.bookmarkPage(k);self.canv.addOutlineEntry(t,k,0,False)
def footer(c,doc):
c.saveState();c.setStrokeColor(colors.HexColor('#CED9E0'));c.setLineWidth(.5)
c.line(M,H-35,W-M,H-35)
c.setFillColor(muted);c.setFont('Sans',7.2)
c.drawString(M,H-25,'MATTER EMBRYOGENESIS / THEORETICAL RESEARCH')
c.drawString(M,27,'v3.0.0 | 19 September 2026 | No new laboratory data')
c.drawRightString(W-M,27,str(doc.page));c.restoreState()
def build():
text=(ROOT/'manuscript/Matter_Embryogenesis.md').read_text();lines=text.splitlines();story=[];i=0;firstsub=True;inrefs=False
mathcache=ROOT/'manuscript'/'math_assets';mathcache.mkdir(exist_ok=True)
while iEMBRYOGENESIS',styles['title'])];i+=1;continue
if s.startswith('## '):
heading=s[3:]
if firstsub:story.append(Paragraph(fmt(heading),styles['subtitle']));firstsub=False
else:
if heading.startswith('1. Central') or heading=='Final assessment':story.append(PageBreak())
story.append(Paragraph(fmt(heading),styles['h2']))
inrefs=(heading=='References') or (inrefs and heading!='Final assessment');i+=1;continue
if s.startswith('### '):story.append(Paragraph(fmt(s[4:]),styles['h3']));i+=1;continue
if s=='$$':
arr=[];i+=1
while i95:code.extend(textwrap.wrap(x,width=95,subsequent_indent=' ',replace_whitespace=False))
else:code.append(x)
i+=1
block=[Preformatted('\n'.join(code),styles['code'])]
if story and isinstance(story[-1],Paragraph) and len(story[-1].getPlainText())<450 and story[-1].getPlainText().endswith(':'):
block.insert(0,story.pop())
while story and isinstance(story[-1],Paragraph) and story[-1].style.name in ('h2','h3'):
block.insert(0,story.pop())
story.append(KeepTogether(block));i+=1;continue
if s.startswith('|'):
rows=[]
while i=6 else None)
tbl.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),blue),('VALIGN',(0,0),(-1,-1),'TOP'),
('LEFTPADDING',(0,0),(-1,-1),7),('RIGHTPADDING',(0,0),(-1,-1),7),
('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7),
('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.HexColor('#F0F4F6'),colors.white]),
('LINEBELOW',(0,0),(-1,-1),.25,colors.HexColor('#D4DEE3'))]))
tbl.spaceBefore=3
story += [tbl,Spacer(1,12)];continue
if s.startswith('!['):
match=re.match(r'!\[(.*?)\]\((.*?)\)',s)
if not match:raise ValueError('Image syntax')
path=(ROOT/'manuscript'/match[2]).resolve()
with PILImage.open(path) as im:ww,hh=im.size
h=CW*hh/ww
story += [Spacer(1,6),Image(str(path),width=CW,height=h,hAlign='CENTER')]
i+=1;continue
if re.match(r'^\d+\.\s',s):
story.append(Paragraph(fmt(s),styles['body']));i+=1;continue
p=[s];i+=1
is_meta=s.startswith(('**Author:**','**Version:**','**Document type:**','**Evidence status:**'))
while not is_meta and i