convert.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import re
  5. from subprocess import run
  6. from os.path import splitext
  7. from glob import glob
  8. # title_re = re.compile(r'^# (.*)$', re.MULTILINE)
  9. # tex_re = re.compile(r'\\begin{document}(.*)\\end{document}', re.MULTILINE | re.DOTALL)
  10. def parse_title(infilename):
  11. # Find chapter title
  12. with open(infilename) as f:
  13. matches = title_re.findall(f.read())
  14. if matches:
  15. return matches[0]
  16. else:
  17. return splitext(infilename.split('/')[-1])[0]
  18. def make_tex(infilename):
  19. # title = parse_title(infilename)
  20. outfilename = splitext(infilename)[0]+'.tex'
  21. run(('pandoc', '--biblatex', '-F', 'pandoc-crossref', '-s', infilename, '-o', outfilename,
  22. '--metadata=bibliography:references.bib',
  23. '--template=chapter',
  24. ))
  25. with open(outfilename, 'r') as f:
  26. full = f.read()
  27. # body = tex_re.findall(full)[0]
  28. body = full
  29. # body = body.replace('section{'+title+'}', 'chapter{'+title+'}')
  30. body = body.replace(r'\printbibliography', '')
  31. with open(outfilename, 'w') as f:
  32. f.write(body)
  33. def make_html(infilename):
  34. # title = parse_title(infilename)
  35. outfilename = splitext(infilename)[0]+'.html'
  36. run(('pandoc', '-F', 'pandoc-crossref', '-F', 'pandoc-citeproc', '-s', infilename, '-o', outfilename,
  37. '--metadata=linkReferences:true',
  38. # f'--metadata=pagetitle:{title}',
  39. '--metadata=bibliography:references.bib',
  40. '--metadata=citation-style:stuttgart-media-university.csl',
  41. '--template=chapter',
  42. ))
  43. def main():
  44. if len(sys.argv) != 2 or sys.argv[1] not in ('html', 'tex'):
  45. print('usage: ./convert.py [html|tex]')
  46. sys.exit(1)
  47. os.chdir('content')
  48. for infilename in glob('*_*.md'):
  49. if sys.argv[1] == 'html':
  50. make_html(infilename)
  51. else:
  52. make_tex(infilename)
  53. if __name__ == '__main__':
  54. main()