tex.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2006-2018 (ita)
  4. """
  5. TeX/LaTeX/PDFLaTeX/XeLaTeX support
  6. Example::
  7. def configure(conf):
  8. conf.load('tex')
  9. if not conf.env.LATEX:
  10. conf.fatal('The program LaTex is required')
  11. def build(bld):
  12. bld(
  13. features = 'tex',
  14. type = 'latex', # pdflatex or xelatex
  15. source = 'document.ltx', # mandatory, the source
  16. outs = 'ps', # 'pdf' or 'ps pdf'
  17. deps = 'crossreferencing.lst', # to give dependencies directly
  18. prompt = 1, # 0 for the batch mode
  19. )
  20. Notes:
  21. - To configure with a special program, use::
  22. $ PDFLATEX=luatex waf configure
  23. - This tool does not use the target attribute of the task generator
  24. (``bld(target=...)``); the target file name is built from the source
  25. base name and the output type(s)
  26. """
  27. import os, re
  28. from waflib import Utils, Task, Errors, Logs, Node
  29. from waflib.TaskGen import feature, before_method
  30. re_bibunit = re.compile(r'\\(?P<type>putbib)\[(?P<file>[^\[\]]*)\]',re.M)
  31. def bibunitscan(self):
  32. """
  33. Parses TeX inputs and try to find the *bibunit* file dependencies
  34. :return: list of bibunit files
  35. :rtype: list of :py:class:`waflib.Node.Node`
  36. """
  37. node = self.inputs[0]
  38. nodes = []
  39. if not node:
  40. return nodes
  41. code = node.read()
  42. for match in re_bibunit.finditer(code):
  43. path = match.group('file')
  44. if path:
  45. found = None
  46. for k in ('', '.bib'):
  47. # add another loop for the tex include paths?
  48. Logs.debug('tex: trying %s%s', path, k)
  49. fi = node.parent.find_resource(path + k)
  50. if fi:
  51. found = True
  52. nodes.append(fi)
  53. # no break
  54. if not found:
  55. Logs.debug('tex: could not find %s', path)
  56. Logs.debug('tex: found the following bibunit files: %s', nodes)
  57. return nodes
  58. exts_deps_tex = ['', '.ltx', '.tex', '.bib', '.pdf', '.png', '.eps', '.ps', '.sty']
  59. """List of typical file extensions included in latex files"""
  60. exts_tex = ['.ltx', '.tex']
  61. """List of typical file extensions that contain latex"""
  62. re_tex = re.compile(r'\\(?P<type>usepackage|RequirePackage|include|bibliography([^\[\]{}]*)|putbib|includegraphics|input|import|bringin|lstinputlisting)(\[[^\[\]]*\])?{(?P<file>[^{}]*)}',re.M)
  63. """Regexp for expressions that may include latex files"""
  64. g_bibtex_re = re.compile('bibdata', re.M)
  65. """Regexp for bibtex files"""
  66. g_glossaries_re = re.compile('\\@newglossary', re.M)
  67. """Regexp for expressions that create glossaries"""
  68. class tex(Task.Task):
  69. """
  70. Compiles a tex/latex file.
  71. .. inheritance-diagram:: waflib.Tools.tex.latex waflib.Tools.tex.xelatex waflib.Tools.tex.pdflatex
  72. """
  73. bibtex_fun, _ = Task.compile_fun('${BIBTEX} ${BIBTEXFLAGS} ${SRCFILE}', shell=False)
  74. bibtex_fun.__doc__ = """
  75. Execute the program **bibtex**
  76. """
  77. makeindex_fun, _ = Task.compile_fun('${MAKEINDEX} ${MAKEINDEXFLAGS} ${SRCFILE}', shell=False)
  78. makeindex_fun.__doc__ = """
  79. Execute the program **makeindex**
  80. """
  81. makeglossaries_fun, _ = Task.compile_fun('${MAKEGLOSSARIES} ${SRCFILE}', shell=False)
  82. makeglossaries_fun.__doc__ = """
  83. Execute the program **makeglossaries**
  84. """
  85. def exec_command(self, cmd, **kw):
  86. """
  87. Executes TeX commands without buffering (latex may prompt for inputs)
  88. :return: the return code
  89. :rtype: int
  90. """
  91. if self.env.PROMPT_LATEX:
  92. # capture the outputs in configuration tests
  93. kw['stdout'] = kw['stderr'] = None
  94. return super(tex, self).exec_command(cmd, **kw)
  95. def scan_aux(self, node):
  96. """
  97. Recursive regex-based scanner that finds included auxiliary files.
  98. """
  99. nodes = [node]
  100. re_aux = re.compile(r'\\@input{(?P<file>[^{}]*)}', re.M)
  101. def parse_node(node):
  102. code = node.read()
  103. for match in re_aux.finditer(code):
  104. path = match.group('file')
  105. found = node.parent.find_or_declare(path)
  106. if found and found not in nodes:
  107. Logs.debug('tex: found aux node %r', found)
  108. nodes.append(found)
  109. parse_node(found)
  110. parse_node(node)
  111. return nodes
  112. def scan(self):
  113. """
  114. Recursive regex-based scanner that finds latex dependencies. It uses :py:attr:`waflib.Tools.tex.re_tex`
  115. Depending on your needs you might want:
  116. * to change re_tex::
  117. from waflib.Tools import tex
  118. tex.re_tex = myregex
  119. * or to change the method scan from the latex tasks::
  120. from waflib.Task import classes
  121. classes['latex'].scan = myscanfunction
  122. """
  123. node = self.inputs[0]
  124. nodes = []
  125. names = []
  126. seen = []
  127. if not node:
  128. return (nodes, names)
  129. def parse_node(node):
  130. if node in seen:
  131. return
  132. seen.append(node)
  133. code = node.read()
  134. for match in re_tex.finditer(code):
  135. multibib = match.group('type')
  136. if multibib and multibib.startswith('bibliography'):
  137. multibib = multibib[len('bibliography'):]
  138. if multibib.startswith('style'):
  139. continue
  140. else:
  141. multibib = None
  142. for path in match.group('file').split(','):
  143. if path:
  144. add_name = True
  145. found = None
  146. for k in exts_deps_tex:
  147. # issue 1067, scan in all texinputs folders
  148. for up in self.texinputs_nodes:
  149. Logs.debug('tex: trying %s%s', path, k)
  150. found = up.find_resource(path + k)
  151. if found:
  152. break
  153. for tsk in self.generator.tasks:
  154. if not found or found in tsk.outputs:
  155. break
  156. else:
  157. nodes.append(found)
  158. add_name = False
  159. for ext in exts_tex:
  160. if found.name.endswith(ext):
  161. parse_node(found)
  162. break
  163. # multibib stuff
  164. if found and multibib and found.name.endswith('.bib'):
  165. try:
  166. self.multibibs.append(found)
  167. except AttributeError:
  168. self.multibibs = [found]
  169. # no break, people are crazy
  170. if add_name:
  171. names.append(path)
  172. parse_node(node)
  173. for x in nodes:
  174. x.parent.get_bld().mkdir()
  175. Logs.debug("tex: found the following : %s and names %s", nodes, names)
  176. return (nodes, names)
  177. def check_status(self, msg, retcode):
  178. """
  179. Checks an exit status and raise an error with a particular message
  180. :param msg: message to display if the code is non-zero
  181. :type msg: string
  182. :param retcode: condition
  183. :type retcode: boolean
  184. """
  185. if retcode != 0:
  186. raise Errors.WafError('%r command exit status %r' % (msg, retcode))
  187. def info(self, *k, **kw):
  188. try:
  189. info = self.generator.bld.conf.logger.info
  190. except AttributeError:
  191. info = Logs.info
  192. info(*k, **kw)
  193. def bibfile(self):
  194. """
  195. Parses *.aux* files to find bibfiles to process.
  196. If present, execute :py:meth:`waflib.Tools.tex.tex.bibtex_fun`
  197. """
  198. for aux_node in self.aux_nodes:
  199. try:
  200. ct = aux_node.read()
  201. except EnvironmentError:
  202. Logs.error('Error reading %s: %r', aux_node.abspath())
  203. continue
  204. if g_bibtex_re.findall(ct):
  205. self.info('calling bibtex')
  206. self.env.env = {}
  207. self.env.env.update(os.environ)
  208. self.env.env.update({'BIBINPUTS': self.texinputs(), 'BSTINPUTS': self.texinputs()})
  209. self.env.SRCFILE = aux_node.name[:-4]
  210. self.check_status('error when calling bibtex', self.bibtex_fun())
  211. for node in getattr(self, 'multibibs', []):
  212. self.env.env = {}
  213. self.env.env.update(os.environ)
  214. self.env.env.update({'BIBINPUTS': self.texinputs(), 'BSTINPUTS': self.texinputs()})
  215. self.env.SRCFILE = node.name[:-4]
  216. self.check_status('error when calling bibtex', self.bibtex_fun())
  217. def bibunits(self):
  218. """
  219. Parses *.aux* file to find bibunit files. If there are bibunit files,
  220. runs :py:meth:`waflib.Tools.tex.tex.bibtex_fun`.
  221. """
  222. try:
  223. bibunits = bibunitscan(self)
  224. except OSError:
  225. Logs.error('error bibunitscan')
  226. else:
  227. if bibunits:
  228. fn = ['bu' + str(i) for i in range(1, len(bibunits) + 1)]
  229. if fn:
  230. self.info('calling bibtex on bibunits')
  231. for f in fn:
  232. self.env.env = {'BIBINPUTS': self.texinputs(), 'BSTINPUTS': self.texinputs()}
  233. self.env.SRCFILE = f
  234. self.check_status('error when calling bibtex', self.bibtex_fun())
  235. def makeindex(self):
  236. """
  237. Searches the filesystem for *.idx* files to process. If present,
  238. runs :py:meth:`waflib.Tools.tex.tex.makeindex_fun`
  239. """
  240. self.idx_node = self.inputs[0].change_ext('.idx')
  241. try:
  242. idx_path = self.idx_node.abspath()
  243. os.stat(idx_path)
  244. except OSError:
  245. self.info('index file %s absent, not calling makeindex', idx_path)
  246. else:
  247. self.info('calling makeindex')
  248. self.env.SRCFILE = self.idx_node.name
  249. self.env.env = {}
  250. self.check_status('error when calling makeindex %s' % idx_path, self.makeindex_fun())
  251. def bibtopic(self):
  252. """
  253. Lists additional .aux files from the bibtopic package
  254. """
  255. p = self.inputs[0].parent.get_bld()
  256. if os.path.exists(os.path.join(p.abspath(), 'btaux.aux')):
  257. self.aux_nodes += p.ant_glob('*[0-9].aux')
  258. def makeglossaries(self):
  259. """
  260. Lists additional glossaries from .aux files. If present, runs the makeglossaries program.
  261. """
  262. src_file = self.inputs[0].abspath()
  263. base_file = os.path.basename(src_file)
  264. base, _ = os.path.splitext(base_file)
  265. for aux_node in self.aux_nodes:
  266. try:
  267. ct = aux_node.read()
  268. except EnvironmentError:
  269. Logs.error('Error reading %s: %r', aux_node.abspath())
  270. continue
  271. if g_glossaries_re.findall(ct):
  272. if not self.env.MAKEGLOSSARIES:
  273. raise Errors.WafError("The program 'makeglossaries' is missing!")
  274. Logs.warn('calling makeglossaries')
  275. self.env.SRCFILE = base
  276. self.check_status('error when calling makeglossaries %s' % base, self.makeglossaries_fun())
  277. return
  278. def texinputs(self):
  279. """
  280. Returns the list of texinput nodes as a string suitable for the TEXINPUTS environment variables
  281. :rtype: string
  282. """
  283. return os.pathsep.join([k.abspath() for k in self.texinputs_nodes]) + os.pathsep
  284. def run(self):
  285. """
  286. Runs the whole TeX build process
  287. Multiple passes are required depending on the usage of cross-references,
  288. bibliographies, glossaries, indexes and additional contents
  289. The appropriate TeX compiler is called until the *.aux* files stop changing.
  290. """
  291. env = self.env
  292. if not env.PROMPT_LATEX:
  293. env.append_value('LATEXFLAGS', '-interaction=batchmode')
  294. env.append_value('PDFLATEXFLAGS', '-interaction=batchmode')
  295. env.append_value('XELATEXFLAGS', '-interaction=batchmode')
  296. # important, set the cwd for everybody
  297. self.cwd = self.inputs[0].parent.get_bld()
  298. self.info('first pass on %s', self.__class__.__name__)
  299. # Hash .aux files before even calling the LaTeX compiler
  300. cur_hash = self.hash_aux_nodes()
  301. self.call_latex()
  302. # Find the .aux files again since bibtex processing can require it
  303. self.hash_aux_nodes()
  304. self.bibtopic()
  305. self.bibfile()
  306. self.bibunits()
  307. self.makeindex()
  308. self.makeglossaries()
  309. for i in range(10):
  310. # There is no need to call latex again if the .aux hash value has not changed
  311. prev_hash = cur_hash
  312. cur_hash = self.hash_aux_nodes()
  313. if not cur_hash:
  314. Logs.error('No aux.h to process')
  315. if cur_hash and cur_hash == prev_hash:
  316. break
  317. # run the command
  318. self.info('calling %s', self.__class__.__name__)
  319. self.call_latex()
  320. def hash_aux_nodes(self):
  321. """
  322. Returns a hash of the .aux file contents
  323. :rtype: string or bytes
  324. """
  325. try:
  326. self.aux_nodes
  327. except AttributeError:
  328. try:
  329. self.aux_nodes = self.scan_aux(self.inputs[0].change_ext('.aux'))
  330. except IOError:
  331. return None
  332. return Utils.h_list([Utils.h_file(x.abspath()) for x in self.aux_nodes])
  333. def call_latex(self):
  334. """
  335. Runs the TeX compiler once
  336. """
  337. self.env.env = {}
  338. self.env.env.update(os.environ)
  339. self.env.env.update({'TEXINPUTS': self.texinputs()})
  340. self.env.SRCFILE = self.inputs[0].abspath()
  341. self.check_status('error when calling latex', self.texfun())
  342. class latex(tex):
  343. "Compiles LaTeX files"
  344. texfun, vars = Task.compile_fun('${LATEX} ${LATEXFLAGS} ${SRCFILE}', shell=False)
  345. class pdflatex(tex):
  346. "Compiles PdfLaTeX files"
  347. texfun, vars = Task.compile_fun('${PDFLATEX} ${PDFLATEXFLAGS} ${SRCFILE}', shell=False)
  348. class xelatex(tex):
  349. "XeLaTeX files"
  350. texfun, vars = Task.compile_fun('${XELATEX} ${XELATEXFLAGS} ${SRCFILE}', shell=False)
  351. class dvips(Task.Task):
  352. "Converts dvi files to postscript"
  353. run_str = '${DVIPS} ${DVIPSFLAGS} ${SRC} -o ${TGT}'
  354. color = 'BLUE'
  355. after = ['latex', 'pdflatex', 'xelatex']
  356. class dvipdf(Task.Task):
  357. "Converts dvi files to pdf"
  358. run_str = '${DVIPDF} ${DVIPDFFLAGS} ${SRC} ${TGT}'
  359. color = 'BLUE'
  360. after = ['latex', 'pdflatex', 'xelatex']
  361. class pdf2ps(Task.Task):
  362. "Converts pdf files to postscript"
  363. run_str = '${PDF2PS} ${PDF2PSFLAGS} ${SRC} ${TGT}'
  364. color = 'BLUE'
  365. after = ['latex', 'pdflatex', 'xelatex']
  366. @feature('tex')
  367. @before_method('process_source')
  368. def apply_tex(self):
  369. """
  370. Creates :py:class:`waflib.Tools.tex.tex` objects, and
  371. dvips/dvipdf/pdf2ps tasks if necessary (outs='ps', etc).
  372. """
  373. if not getattr(self, 'type', None) in ('latex', 'pdflatex', 'xelatex'):
  374. self.type = 'pdflatex'
  375. outs = Utils.to_list(getattr(self, 'outs', []))
  376. # prompt for incomplete files (else the batchmode is used)
  377. try:
  378. self.generator.bld.conf
  379. except AttributeError:
  380. default_prompt = False
  381. else:
  382. default_prompt = True
  383. self.env.PROMPT_LATEX = getattr(self, 'prompt', default_prompt)
  384. deps_lst = []
  385. if getattr(self, 'deps', None):
  386. deps = self.to_list(self.deps)
  387. for dep in deps:
  388. if isinstance(dep, str):
  389. n = self.path.find_resource(dep)
  390. if not n:
  391. self.bld.fatal('Could not find %r for %r' % (dep, self))
  392. if not n in deps_lst:
  393. deps_lst.append(n)
  394. elif isinstance(dep, Node.Node):
  395. deps_lst.append(dep)
  396. for node in self.to_nodes(self.source):
  397. if self.type == 'latex':
  398. task = self.create_task('latex', node, node.change_ext('.dvi'))
  399. elif self.type == 'pdflatex':
  400. task = self.create_task('pdflatex', node, node.change_ext('.pdf'))
  401. elif self.type == 'xelatex':
  402. task = self.create_task('xelatex', node, node.change_ext('.pdf'))
  403. task.env = self.env
  404. # add the manual dependencies
  405. if deps_lst:
  406. for n in deps_lst:
  407. if not n in task.dep_nodes:
  408. task.dep_nodes.append(n)
  409. # texinputs is a nasty beast
  410. if hasattr(self, 'texinputs_nodes'):
  411. task.texinputs_nodes = self.texinputs_nodes
  412. else:
  413. task.texinputs_nodes = [node.parent, node.parent.get_bld(), self.path, self.path.get_bld()]
  414. lst = os.environ.get('TEXINPUTS', '')
  415. if self.env.TEXINPUTS:
  416. lst += os.pathsep + self.env.TEXINPUTS
  417. if lst:
  418. lst = lst.split(os.pathsep)
  419. for x in lst:
  420. if x:
  421. if os.path.isabs(x):
  422. p = self.bld.root.find_node(x)
  423. if p:
  424. task.texinputs_nodes.append(p)
  425. else:
  426. Logs.error('Invalid TEXINPUTS folder %s', x)
  427. else:
  428. Logs.error('Cannot resolve relative paths in TEXINPUTS %s', x)
  429. if self.type == 'latex':
  430. if 'ps' in outs:
  431. tsk = self.create_task('dvips', task.outputs, node.change_ext('.ps'))
  432. tsk.env.env = dict(os.environ)
  433. if 'pdf' in outs:
  434. tsk = self.create_task('dvipdf', task.outputs, node.change_ext('.pdf'))
  435. tsk.env.env = dict(os.environ)
  436. elif self.type == 'pdflatex':
  437. if 'ps' in outs:
  438. self.create_task('pdf2ps', task.outputs, node.change_ext('.ps'))
  439. self.source = []
  440. def configure(self):
  441. """
  442. Find the programs tex, latex and others without raising errors.
  443. """
  444. v = self.env
  445. for p in 'tex latex pdflatex xelatex bibtex dvips dvipdf ps2pdf makeindex pdf2ps makeglossaries'.split():
  446. try:
  447. self.find_program(p, var=p.upper())
  448. except self.errors.ConfigurationError:
  449. pass
  450. v.DVIPSFLAGS = '-Ppdf'