tex.py 16 KB

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