jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

516 lines
14KB

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