123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- #!/usr/bin/env python3
- import sys
- import re
- from subprocess import run
- from os.path import splitext
- from glob import glob
- title_re = re.compile(r'^# (.*)$', re.MULTILINE)
- tex_re = re.compile(r'\\begin{document}(.*)\\end{document}', re.MULTILINE | re.DOTALL)
- def parse_title(infilename):
- # Find chapter title
- with open(infilename) as f:
- matches = title_re.findall(f.read())
- if matches:
- return matches[0]
- else:
- return splitext(infilename.split('/')[-1])[0]
- def make_tex(infilename):
- title = parse_title(infilename)
- outfilename = splitext(infilename)[0]+'.tex'
- run(('pandoc', '-F', 'pandoc-crossref', '-F', 'pandoc-citeproc', '-s', infilename, '-o', outfilename,))
- with open(outfilename, 'r') as f:
- full = f.read()
- body = tex_re.findall(full)[0]
- body = body.replace('section{'+title+'}', 'chapter{'+title+'}')
- with open(outfilename, 'w') as f:
- f.write(body)
- def make_html(infilename):
- title = parse_title(infilename)
- outfilename = splitext(infilename)[0]+'.html'
- run(('pandoc', '-F', 'pandoc-crossref', '-F', 'pandoc-citeproc', '-s', infilename, '-o', outfilename,
- '--metadata=linkReferences:true', f'--metadata=pagetitle:{title}'))
- def main():
- if len(sys.argv) != 2 or sys.argv[1] not in ('html', 'tex'):
- print('usage: ./convert.py [html|tex]')
- sys.exit(1)
- for infilename in glob('content/*_*.md'):
- if sys.argv[1] == 'html':
- make_html(infilename)
- else:
- make_tex(infilename)
- if __name__ == '__main__':
- main()
|