PageRenderTime 61ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/couchjs/scons/scons-local-2.0.1/SCons/Tool/tex.py

http://github.com/cloudant/bigcouch
Python | 813 lines | 800 code | 1 blank | 12 comment | 10 complexity | c13ecb1cf2690e03f23be88c3c7ed698 MD5 | raw file
Possible License(s): Apache-2.0
  1. """SCons.Tool.tex
  2. Tool-specific initialization for TeX.
  3. Generates .dvi files from .tex files
  4. There normally shouldn't be any need to import this module directly.
  5. It will usually be imported through the generic SCons.Tool.Tool()
  6. selection method.
  7. """
  8. #
  9. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  10. #
  11. # Permission is hereby granted, free of charge, to any person obtaining
  12. # a copy of this software and associated documentation files (the
  13. # "Software"), to deal in the Software without restriction, including
  14. # without limitation the rights to use, copy, modify, merge, publish,
  15. # distribute, sublicense, and/or sell copies of the Software, and to
  16. # permit persons to whom the Software is furnished to do so, subject to
  17. # the following conditions:
  18. #
  19. # The above copyright notice and this permission notice shall be included
  20. # in all copies or substantial portions of the Software.
  21. #
  22. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  23. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  24. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. #
  30. __revision__ = "src/engine/SCons/Tool/tex.py 5134 2010/08/16 23:02:40 bdeegan"
  31. import os.path
  32. import re
  33. import shutil
  34. import sys
  35. import platform
  36. import SCons.Action
  37. import SCons.Node
  38. import SCons.Node.FS
  39. import SCons.Util
  40. import SCons.Scanner.LaTeX
  41. Verbose = False
  42. must_rerun_latex = True
  43. # these are files that just need to be checked for changes and then rerun latex
  44. check_suffixes = ['.toc', '.lof', '.lot', '.out', '.nav', '.snm']
  45. # these are files that require bibtex or makeindex to be run when they change
  46. all_suffixes = check_suffixes + ['.bbl', '.idx', '.nlo', '.glo', '.acn']
  47. #
  48. # regular expressions used to search for Latex features
  49. # or outputs that require rerunning latex
  50. #
  51. # search for all .aux files opened by latex (recorded in the .fls file)
  52. openout_aux_re = re.compile(r"INPUT *(.*\.aux)")
  53. #printindex_re = re.compile(r"^[^%]*\\printindex", re.MULTILINE)
  54. #printnomenclature_re = re.compile(r"^[^%]*\\printnomenclature", re.MULTILINE)
  55. #printglossary_re = re.compile(r"^[^%]*\\printglossary", re.MULTILINE)
  56. # search to find rerun warnings
  57. warning_rerun_str = '(^LaTeX Warning:.*Rerun)|(^Package \w+ Warning:.*Rerun)'
  58. warning_rerun_re = re.compile(warning_rerun_str, re.MULTILINE)
  59. # search to find citation rerun warnings
  60. rerun_citations_str = "^LaTeX Warning:.*\n.*Rerun to get citations correct"
  61. rerun_citations_re = re.compile(rerun_citations_str, re.MULTILINE)
  62. # search to find undefined references or citations warnings
  63. undefined_references_str = '(^LaTeX Warning:.*undefined references)|(^Package \w+ Warning:.*undefined citations)'
  64. undefined_references_re = re.compile(undefined_references_str, re.MULTILINE)
  65. # used by the emitter
  66. auxfile_re = re.compile(r".", re.MULTILINE)
  67. tableofcontents_re = re.compile(r"^[^%\n]*\\tableofcontents", re.MULTILINE)
  68. makeindex_re = re.compile(r"^[^%\n]*\\makeindex", re.MULTILINE)
  69. bibliography_re = re.compile(r"^[^%\n]*\\bibliography", re.MULTILINE)
  70. listoffigures_re = re.compile(r"^[^%\n]*\\listoffigures", re.MULTILINE)
  71. listoftables_re = re.compile(r"^[^%\n]*\\listoftables", re.MULTILINE)
  72. hyperref_re = re.compile(r"^[^%\n]*\\usepackage.*\{hyperref\}", re.MULTILINE)
  73. makenomenclature_re = re.compile(r"^[^%\n]*\\makenomenclature", re.MULTILINE)
  74. makeglossary_re = re.compile(r"^[^%\n]*\\makeglossary", re.MULTILINE)
  75. makeglossaries_re = re.compile(r"^[^%\n]*\\makeglossaries", re.MULTILINE)
  76. makeacronyms_re = re.compile(r"^[^%\n]*\\makeglossaries", re.MULTILINE)
  77. beamer_re = re.compile(r"^[^%\n]*\\documentclass\{beamer\}", re.MULTILINE)
  78. # search to find all files included by Latex
  79. include_re = re.compile(r'^[^%\n]*\\(?:include|input){([^}]*)}', re.MULTILINE)
  80. includeOnly_re = re.compile(r'^[^%\n]*\\(?:include){([^}]*)}', re.MULTILINE)
  81. # search to find all graphics files included by Latex
  82. includegraphics_re = re.compile(r'^[^%\n]*\\(?:includegraphics(?:\[[^\]]+\])?){([^}]*)}', re.MULTILINE)
  83. # search to find all files opened by Latex (recorded in .log file)
  84. openout_re = re.compile(r"OUTPUT *(.*)")
  85. # list of graphics file extensions for TeX and LaTeX
  86. TexGraphics = SCons.Scanner.LaTeX.TexGraphics
  87. LatexGraphics = SCons.Scanner.LaTeX.LatexGraphics
  88. # An Action sufficient to build any generic tex file.
  89. TeXAction = None
  90. # An action to build a latex file. This action might be needed more
  91. # than once if we are dealing with labels and bibtex.
  92. LaTeXAction = None
  93. # An action to run BibTeX on a file.
  94. BibTeXAction = None
  95. # An action to run MakeIndex on a file.
  96. MakeIndexAction = None
  97. # An action to run MakeIndex (for nomencl) on a file.
  98. MakeNclAction = None
  99. # An action to run MakeIndex (for glossary) on a file.
  100. MakeGlossaryAction = None
  101. # An action to run MakeIndex (for acronyms) on a file.
  102. MakeAcronymsAction = None
  103. # Used as a return value of modify_env_var if the variable is not set.
  104. _null = SCons.Scanner.LaTeX._null
  105. modify_env_var = SCons.Scanner.LaTeX.modify_env_var
  106. def check_file_error_message(utility, filename='log'):
  107. msg = '%s returned an error, check the %s file\n' % (utility, filename)
  108. sys.stdout.write(msg)
  109. def FindFile(name,suffixes,paths,env,requireExt=False):
  110. if requireExt:
  111. name,ext = SCons.Util.splitext(name)
  112. # if the user gave an extension use it.
  113. if ext:
  114. name = name + ext
  115. if Verbose:
  116. print " searching for '%s' with extensions: " % name,suffixes
  117. for path in paths:
  118. testName = os.path.join(path,name)
  119. if Verbose:
  120. print " look for '%s'" % testName
  121. if os.path.exists(testName):
  122. if Verbose:
  123. print " found '%s'" % testName
  124. return env.fs.File(testName)
  125. else:
  126. name_ext = SCons.Util.splitext(testName)[1]
  127. if name_ext:
  128. continue
  129. # if no suffix try adding those passed in
  130. for suffix in suffixes:
  131. testNameExt = testName + suffix
  132. if Verbose:
  133. print " look for '%s'" % testNameExt
  134. if os.path.exists(testNameExt):
  135. if Verbose:
  136. print " found '%s'" % testNameExt
  137. return env.fs.File(testNameExt)
  138. if Verbose:
  139. print " did not find '%s'" % name
  140. return None
  141. def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None):
  142. """A builder for LaTeX files that checks the output in the aux file
  143. and decides how many times to use LaTeXAction, and BibTeXAction."""
  144. global must_rerun_latex
  145. # This routine is called with two actions. In this file for DVI builds
  146. # with LaTeXAction and from the pdflatex.py with PDFLaTeXAction
  147. # set this up now for the case where the user requests a different extension
  148. # for the target filename
  149. if (XXXLaTeXAction == LaTeXAction):
  150. callerSuffix = ".dvi"
  151. else:
  152. callerSuffix = env['PDFSUFFIX']
  153. basename = SCons.Util.splitext(str(source[0]))[0]
  154. basedir = os.path.split(str(source[0]))[0]
  155. basefile = os.path.split(str(basename))[1]
  156. abspath = os.path.abspath(basedir)
  157. targetext = os.path.splitext(str(target[0]))[1]
  158. targetdir = os.path.split(str(target[0]))[0]
  159. saved_env = {}
  160. for var in SCons.Scanner.LaTeX.LaTeX.env_variables:
  161. saved_env[var] = modify_env_var(env, var, abspath)
  162. # Create base file names with the target directory since the auxiliary files
  163. # will be made there. That's because the *COM variables have the cd
  164. # command in the prolog. We check
  165. # for the existence of files before opening them--even ones like the
  166. # aux file that TeX always creates--to make it possible to write tests
  167. # with stubs that don't necessarily generate all of the same files.
  168. targetbase = os.path.join(targetdir, basefile)
  169. # if there is a \makeindex there will be a .idx and thus
  170. # we have to run makeindex at least once to keep the build
  171. # happy even if there is no index.
  172. # Same for glossaries and nomenclature
  173. src_content = source[0].get_text_contents()
  174. run_makeindex = makeindex_re.search(src_content) and not os.path.exists(targetbase + '.idx')
  175. run_nomenclature = makenomenclature_re.search(src_content) and not os.path.exists(targetbase + '.nlo')
  176. run_glossary = makeglossary_re.search(src_content) and not os.path.exists(targetbase + '.glo')
  177. run_glossaries = makeglossaries_re.search(src_content) and not os.path.exists(targetbase + '.glo')
  178. run_acronyms = makeacronyms_re.search(src_content) and not os.path.exists(targetbase + '.acn')
  179. saved_hashes = {}
  180. suffix_nodes = {}
  181. for suffix in all_suffixes:
  182. theNode = env.fs.File(targetbase + suffix)
  183. suffix_nodes[suffix] = theNode
  184. saved_hashes[suffix] = theNode.get_csig()
  185. if Verbose:
  186. print "hashes: ",saved_hashes
  187. must_rerun_latex = True
  188. #
  189. # routine to update MD5 hash and compare
  190. #
  191. def check_MD5(filenode, suffix):
  192. global must_rerun_latex
  193. # two calls to clear old csig
  194. filenode.clear_memoized_values()
  195. filenode.ninfo = filenode.new_ninfo()
  196. new_md5 = filenode.get_csig()
  197. if saved_hashes[suffix] == new_md5:
  198. if Verbose:
  199. print "file %s not changed" % (targetbase+suffix)
  200. return False # unchanged
  201. saved_hashes[suffix] = new_md5
  202. must_rerun_latex = True
  203. if Verbose:
  204. print "file %s changed, rerunning Latex, new hash = " % (targetbase+suffix), new_md5
  205. return True # changed
  206. # generate the file name that latex will generate
  207. resultfilename = targetbase + callerSuffix
  208. count = 0
  209. while (must_rerun_latex and count < int(env.subst('$LATEXRETRIES'))) :
  210. result = XXXLaTeXAction(target, source, env)
  211. if result != 0:
  212. return result
  213. count = count + 1
  214. must_rerun_latex = False
  215. # Decide if various things need to be run, or run again.
  216. # Read the log file to find warnings/errors
  217. logfilename = targetbase + '.log'
  218. logContent = ''
  219. if os.path.exists(logfilename):
  220. logContent = open(logfilename, "rb").read()
  221. # Read the fls file to find all .aux files
  222. flsfilename = targetbase + '.fls'
  223. flsContent = ''
  224. auxfiles = []
  225. if os.path.exists(flsfilename):
  226. flsContent = open(flsfilename, "rb").read()
  227. auxfiles = openout_aux_re.findall(flsContent)
  228. if Verbose:
  229. print "auxfiles ",auxfiles
  230. # Now decide if bibtex will need to be run.
  231. # The information that bibtex reads from the .aux file is
  232. # pass-independent. If we find (below) that the .bbl file is unchanged,
  233. # then the last latex saw a correct bibliography.
  234. # Therefore only do this on the first pass
  235. if count == 1:
  236. for auxfilename in auxfiles:
  237. target_aux = os.path.join(targetdir, auxfilename)
  238. if os.path.exists(target_aux):
  239. content = open(target_aux, "rb").read()
  240. if content.find("bibdata") != -1:
  241. if Verbose:
  242. print "Need to run bibtex"
  243. bibfile = env.fs.File(targetbase)
  244. result = BibTeXAction(bibfile, bibfile, env)
  245. if result != 0:
  246. check_file_error_message(env['BIBTEX'], 'blg')
  247. return result
  248. must_rerun_latex = check_MD5(suffix_nodes['.bbl'],'.bbl')
  249. break
  250. # Now decide if latex will need to be run again due to index.
  251. if check_MD5(suffix_nodes['.idx'],'.idx') or (count == 1 and run_makeindex):
  252. # We must run makeindex
  253. if Verbose:
  254. print "Need to run makeindex"
  255. idxfile = suffix_nodes['.idx']
  256. result = MakeIndexAction(idxfile, idxfile, env)
  257. if result != 0:
  258. check_file_error_message(env['MAKEINDEX'], 'ilg')
  259. return result
  260. # TO-DO: need to add a way for the user to extend this list for whatever
  261. # auxiliary files they create in other (or their own) packages
  262. # Harder is case is where an action needs to be called -- that should be rare (I hope?)
  263. for index in check_suffixes:
  264. check_MD5(suffix_nodes[index],index)
  265. # Now decide if latex will need to be run again due to nomenclature.
  266. if check_MD5(suffix_nodes['.nlo'],'.nlo') or (count == 1 and run_nomenclature):
  267. # We must run makeindex
  268. if Verbose:
  269. print "Need to run makeindex for nomenclature"
  270. nclfile = suffix_nodes['.nlo']
  271. result = MakeNclAction(nclfile, nclfile, env)
  272. if result != 0:
  273. check_file_error_message('%s (nomenclature)' % env['MAKENCL'],
  274. 'nlg')
  275. #return result
  276. # Now decide if latex will need to be run again due to glossary.
  277. if check_MD5(suffix_nodes['.glo'],'.glo') or (count == 1 and run_glossaries) or (count == 1 and run_glossary):
  278. # We must run makeindex
  279. if Verbose:
  280. print "Need to run makeindex for glossary"
  281. glofile = suffix_nodes['.glo']
  282. result = MakeGlossaryAction(glofile, glofile, env)
  283. if result != 0:
  284. check_file_error_message('%s (glossary)' % env['MAKEGLOSSARY'],
  285. 'glg')
  286. #return result
  287. # Now decide if latex will need to be run again due to acronyms.
  288. if check_MD5(suffix_nodes['.acn'],'.acn') or (count == 1 and run_acronyms):
  289. # We must run makeindex
  290. if Verbose:
  291. print "Need to run makeindex for acronyms"
  292. acrfile = suffix_nodes['.acn']
  293. result = MakeAcronymsAction(acrfile, acrfile, env)
  294. if result != 0:
  295. check_file_error_message('%s (acronyms)' % env['MAKEACRONYMS'],
  296. 'alg')
  297. return result
  298. # Now decide if latex needs to be run yet again to resolve warnings.
  299. if warning_rerun_re.search(logContent):
  300. must_rerun_latex = True
  301. if Verbose:
  302. print "rerun Latex due to latex or package rerun warning"
  303. if rerun_citations_re.search(logContent):
  304. must_rerun_latex = True
  305. if Verbose:
  306. print "rerun Latex due to 'Rerun to get citations correct' warning"
  307. if undefined_references_re.search(logContent):
  308. must_rerun_latex = True
  309. if Verbose:
  310. print "rerun Latex due to undefined references or citations"
  311. if (count >= int(env.subst('$LATEXRETRIES')) and must_rerun_latex):
  312. print "reached max number of retries on Latex ,",int(env.subst('$LATEXRETRIES'))
  313. # end of while loop
  314. # rename Latex's output to what the target name is
  315. if not (str(target[0]) == resultfilename and os.path.exists(resultfilename)):
  316. if os.path.exists(resultfilename):
  317. print "move %s to %s" % (resultfilename, str(target[0]), )
  318. shutil.move(resultfilename,str(target[0]))
  319. # Original comment (when TEXPICTS was not restored):
  320. # The TEXPICTS enviroment variable is needed by a dvi -> pdf step
  321. # later on Mac OSX so leave it
  322. #
  323. # It is also used when searching for pictures (implicit dependencies).
  324. # Why not set the variable again in the respective builder instead
  325. # of leaving local modifications in the environment? What if multiple
  326. # latex builds in different directories need different TEXPICTS?
  327. for var in SCons.Scanner.LaTeX.LaTeX.env_variables:
  328. if var == 'TEXPICTS':
  329. continue
  330. if saved_env[var] is _null:
  331. try:
  332. del env['ENV'][var]
  333. except KeyError:
  334. pass # was never set
  335. else:
  336. env['ENV'][var] = saved_env[var]
  337. return result
  338. def LaTeXAuxAction(target = None, source= None, env=None):
  339. result = InternalLaTeXAuxAction( LaTeXAction, target, source, env )
  340. return result
  341. LaTeX_re = re.compile("\\\\document(style|class)")
  342. def is_LaTeX(flist,env,abspath):
  343. """Scan a file list to decide if it's TeX- or LaTeX-flavored."""
  344. # We need to scan files that are included in case the
  345. # \documentclass command is in them.
  346. # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS']
  347. savedpath = modify_env_var(env, 'TEXINPUTS', abspath)
  348. paths = env['ENV']['TEXINPUTS']
  349. if SCons.Util.is_List(paths):
  350. pass
  351. else:
  352. # Split at os.pathsep to convert into absolute path
  353. paths = paths.split(os.pathsep)
  354. # now that we have the path list restore the env
  355. if savedpath is _null:
  356. try:
  357. del env['ENV']['TEXINPUTS']
  358. except KeyError:
  359. pass # was never set
  360. else:
  361. env['ENV']['TEXINPUTS'] = savedpath
  362. if Verbose:
  363. print "is_LaTeX search path ",paths
  364. print "files to search :",flist
  365. # Now that we have the search path and file list, check each one
  366. for f in flist:
  367. if Verbose:
  368. print " checking for Latex source ",str(f)
  369. content = f.get_text_contents()
  370. if LaTeX_re.search(content):
  371. if Verbose:
  372. print "file %s is a LaTeX file" % str(f)
  373. return 1
  374. if Verbose:
  375. print "file %s is not a LaTeX file" % str(f)
  376. # now find included files
  377. inc_files = [ ]
  378. inc_files.extend( include_re.findall(content) )
  379. if Verbose:
  380. print "files included by '%s': "%str(f),inc_files
  381. # inc_files is list of file names as given. need to find them
  382. # using TEXINPUTS paths.
  383. # search the included files
  384. for src in inc_files:
  385. srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False)
  386. # make this a list since is_LaTeX takes a list.
  387. fileList = [srcNode,]
  388. if Verbose:
  389. print "FindFile found ",srcNode
  390. if srcNode is not None:
  391. file_test = is_LaTeX(fileList, env, abspath)
  392. # return on first file that finds latex is needed.
  393. if file_test:
  394. return file_test
  395. if Verbose:
  396. print " done scanning ",str(f)
  397. return 0
  398. def TeXLaTeXFunction(target = None, source= None, env=None):
  399. """A builder for TeX and LaTeX that scans the source file to
  400. decide the "flavor" of the source and then executes the appropriate
  401. program."""
  402. # find these paths for use in is_LaTeX to search for included files
  403. basedir = os.path.split(str(source[0]))[0]
  404. abspath = os.path.abspath(basedir)
  405. if is_LaTeX(source,env,abspath):
  406. result = LaTeXAuxAction(target,source,env)
  407. if result != 0:
  408. check_file_error_message(env['LATEX'])
  409. else:
  410. result = TeXAction(target,source,env)
  411. if result != 0:
  412. check_file_error_message(env['TEX'])
  413. return result
  414. def TeXLaTeXStrFunction(target = None, source= None, env=None):
  415. """A strfunction for TeX and LaTeX that scans the source file to
  416. decide the "flavor" of the source and then returns the appropriate
  417. command string."""
  418. if env.GetOption("no_exec"):
  419. # find these paths for use in is_LaTeX to search for included files
  420. basedir = os.path.split(str(source[0]))[0]
  421. abspath = os.path.abspath(basedir)
  422. if is_LaTeX(source,env,abspath):
  423. result = env.subst('$LATEXCOM',0,target,source)+" ..."
  424. else:
  425. result = env.subst("$TEXCOM",0,target,source)+" ..."
  426. else:
  427. result = ''
  428. return result
  429. def tex_eps_emitter(target, source, env):
  430. """An emitter for TeX and LaTeX sources when
  431. executing tex or latex. It will accept .ps and .eps
  432. graphics files
  433. """
  434. (target, source) = tex_emitter_core(target, source, env, TexGraphics)
  435. return (target, source)
  436. def tex_pdf_emitter(target, source, env):
  437. """An emitter for TeX and LaTeX sources when
  438. executing pdftex or pdflatex. It will accept graphics
  439. files of types .pdf, .jpg, .png, .gif, and .tif
  440. """
  441. (target, source) = tex_emitter_core(target, source, env, LatexGraphics)
  442. return (target, source)
  443. def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files):
  444. """ For theFile (a Node) update any file_tests and search for graphics files
  445. then find all included files and call ScanFiles recursively for each of them"""
  446. content = theFile.get_text_contents()
  447. if Verbose:
  448. print " scanning ",str(theFile)
  449. for i in range(len(file_tests_search)):
  450. if file_tests[i][0] is None:
  451. file_tests[i][0] = file_tests_search[i].search(content)
  452. incResult = includeOnly_re.search(content)
  453. if incResult:
  454. aux_files.append(os.path.join(targetdir, incResult.group(1)))
  455. if Verbose:
  456. print "\include file names : ", aux_files
  457. # recursively call this on each of the included files
  458. inc_files = [ ]
  459. inc_files.extend( include_re.findall(content) )
  460. if Verbose:
  461. print "files included by '%s': "%str(theFile),inc_files
  462. # inc_files is list of file names as given. need to find them
  463. # using TEXINPUTS paths.
  464. for src in inc_files:
  465. srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False)
  466. if srcNode is not None:
  467. file_tests = ScanFiles(srcNode, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files)
  468. if Verbose:
  469. print " done scanning ",str(theFile)
  470. return file_tests
  471. def tex_emitter_core(target, source, env, graphics_extensions):
  472. """An emitter for TeX and LaTeX sources.
  473. For LaTeX sources we try and find the common created files that
  474. are needed on subsequent runs of latex to finish tables of contents,
  475. bibliographies, indices, lists of figures, and hyperlink references.
  476. """
  477. basename = SCons.Util.splitext(str(source[0]))[0]
  478. basefile = os.path.split(str(basename))[1]
  479. targetdir = os.path.split(str(target[0]))[0]
  480. targetbase = os.path.join(targetdir, basefile)
  481. basedir = os.path.split(str(source[0]))[0]
  482. abspath = os.path.abspath(basedir)
  483. target[0].attributes.path = abspath
  484. #
  485. # file names we will make use of in searching the sources and log file
  486. #
  487. emit_suffixes = ['.aux', '.log', '.ilg', '.blg', '.nls', '.nlg', '.gls', '.glg', '.alg'] + all_suffixes
  488. auxfilename = targetbase + '.aux'
  489. logfilename = targetbase + '.log'
  490. flsfilename = targetbase + '.fls'
  491. env.SideEffect(auxfilename,target[0])
  492. env.SideEffect(logfilename,target[0])
  493. env.SideEffect(flsfilename,target[0])
  494. if Verbose:
  495. print "side effect :",auxfilename,logfilename,flsfilename
  496. env.Clean(target[0],auxfilename)
  497. env.Clean(target[0],logfilename)
  498. env.Clean(target[0],flsfilename)
  499. content = source[0].get_text_contents()
  500. idx_exists = os.path.exists(targetbase + '.idx')
  501. nlo_exists = os.path.exists(targetbase + '.nlo')
  502. glo_exists = os.path.exists(targetbase + '.glo')
  503. acr_exists = os.path.exists(targetbase + '.acn')
  504. # set up list with the regular expressions
  505. # we use to find features used
  506. file_tests_search = [auxfile_re,
  507. makeindex_re,
  508. bibliography_re,
  509. tableofcontents_re,
  510. listoffigures_re,
  511. listoftables_re,
  512. hyperref_re,
  513. makenomenclature_re,
  514. makeglossary_re,
  515. makeglossaries_re,
  516. makeacronyms_re,
  517. beamer_re ]
  518. # set up list with the file suffixes that need emitting
  519. # when a feature is found
  520. file_tests_suff = [['.aux'],
  521. ['.idx', '.ind', '.ilg'],
  522. ['.bbl', '.blg'],
  523. ['.toc'],
  524. ['.lof'],
  525. ['.lot'],
  526. ['.out'],
  527. ['.nlo', '.nls', '.nlg'],
  528. ['.glo', '.gls', '.glg'],
  529. ['.glo', '.gls', '.glg'],
  530. ['.acn', '.acr', '.alg'],
  531. ['.nav', '.snm', '.out', '.toc'] ]
  532. # build the list of lists
  533. file_tests = []
  534. for i in range(len(file_tests_search)):
  535. file_tests.append( [None, file_tests_suff[i]] )
  536. # TO-DO: need to add a way for the user to extend this list for whatever
  537. # auxiliary files they create in other (or their own) packages
  538. # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS']
  539. savedpath = modify_env_var(env, 'TEXINPUTS', abspath)
  540. paths = env['ENV']['TEXINPUTS']
  541. if SCons.Util.is_List(paths):
  542. pass
  543. else:
  544. # Split at os.pathsep to convert into absolute path
  545. paths = paths.split(os.pathsep)
  546. # now that we have the path list restore the env
  547. if savedpath is _null:
  548. try:
  549. del env['ENV']['TEXINPUTS']
  550. except KeyError:
  551. pass # was never set
  552. else:
  553. env['ENV']['TEXINPUTS'] = savedpath
  554. if Verbose:
  555. print "search path ",paths
  556. aux_files = []
  557. file_tests = ScanFiles(source[0], target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files)
  558. for (theSearch,suffix_list) in file_tests:
  559. if theSearch:
  560. for suffix in suffix_list:
  561. env.SideEffect(targetbase + suffix,target[0])
  562. if Verbose:
  563. print "side effect :",targetbase + suffix
  564. env.Clean(target[0],targetbase + suffix)
  565. for aFile in aux_files:
  566. aFile_base = SCons.Util.splitext(aFile)[0]
  567. env.SideEffect(aFile_base + '.aux',target[0])
  568. if Verbose:
  569. print "side effect :",aFile_base + '.aux'
  570. env.Clean(target[0],aFile_base + '.aux')
  571. # read fls file to get all other files that latex creates and will read on the next pass
  572. # remove files from list that we explicitly dealt with above
  573. if os.path.exists(flsfilename):
  574. content = open(flsfilename, "rb").read()
  575. out_files = openout_re.findall(content)
  576. myfiles = [auxfilename, logfilename, flsfilename, targetbase+'.dvi',targetbase+'.pdf']
  577. for filename in out_files[:]:
  578. if filename in myfiles:
  579. out_files.remove(filename)
  580. env.SideEffect(out_files,target[0])
  581. if Verbose:
  582. print "side effect :",out_files
  583. env.Clean(target[0],out_files)
  584. return (target, source)
  585. TeXLaTeXAction = None
  586. def generate(env):
  587. """Add Builders and construction variables for TeX to an Environment."""
  588. global TeXLaTeXAction
  589. if TeXLaTeXAction is None:
  590. TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction,
  591. strfunction=TeXLaTeXStrFunction)
  592. env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
  593. generate_common(env)
  594. import dvi
  595. dvi.generate(env)
  596. bld = env['BUILDERS']['DVI']
  597. bld.add_action('.tex', TeXLaTeXAction)
  598. bld.add_emitter('.tex', tex_eps_emitter)
  599. def generate_common(env):
  600. """Add internal Builders and construction variables for LaTeX to an Environment."""
  601. # A generic tex file Action, sufficient for all tex files.
  602. global TeXAction
  603. if TeXAction is None:
  604. TeXAction = SCons.Action.Action("$TEXCOM", "$TEXCOMSTR")
  605. # An Action to build a latex file. This might be needed more
  606. # than once if we are dealing with labels and bibtex.
  607. global LaTeXAction
  608. if LaTeXAction is None:
  609. LaTeXAction = SCons.Action.Action("$LATEXCOM", "$LATEXCOMSTR")
  610. # Define an action to run BibTeX on a file.
  611. global BibTeXAction
  612. if BibTeXAction is None:
  613. BibTeXAction = SCons.Action.Action("$BIBTEXCOM", "$BIBTEXCOMSTR")
  614. # Define an action to run MakeIndex on a file.
  615. global MakeIndexAction
  616. if MakeIndexAction is None:
  617. MakeIndexAction = SCons.Action.Action("$MAKEINDEXCOM", "$MAKEINDEXCOMSTR")
  618. # Define an action to run MakeIndex on a file for nomenclatures.
  619. global MakeNclAction
  620. if MakeNclAction is None:
  621. MakeNclAction = SCons.Action.Action("$MAKENCLCOM", "$MAKENCLCOMSTR")
  622. # Define an action to run MakeIndex on a file for glossaries.
  623. global MakeGlossaryAction
  624. if MakeGlossaryAction is None:
  625. MakeGlossaryAction = SCons.Action.Action("$MAKEGLOSSARYCOM", "$MAKEGLOSSARYCOMSTR")
  626. # Define an action to run MakeIndex on a file for acronyms.
  627. global MakeAcronymsAction
  628. if MakeAcronymsAction is None:
  629. MakeAcronymsAction = SCons.Action.Action("$MAKEACRONYMSCOM", "$MAKEACRONYMSCOMSTR")
  630. CDCOM = 'cd '
  631. if platform.system() == 'Windows':
  632. # allow cd command to change drives on Windows
  633. CDCOM = 'cd /D '
  634. env['TEX'] = 'tex'
  635. env['TEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder')
  636. env['TEXCOM'] = CDCOM + '${TARGET.dir} && $TEX $TEXFLAGS ${SOURCE.file}'
  637. env['PDFTEX'] = 'pdftex'
  638. env['PDFTEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder')
  639. env['PDFTEXCOM'] = CDCOM + '${TARGET.dir} && $PDFTEX $PDFTEXFLAGS ${SOURCE.file}'
  640. env['LATEX'] = 'latex'
  641. env['LATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder')
  642. env['LATEXCOM'] = CDCOM + '${TARGET.dir} && $LATEX $LATEXFLAGS ${SOURCE.file}'
  643. env['LATEXRETRIES'] = 3
  644. env['PDFLATEX'] = 'pdflatex'
  645. env['PDFLATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder')
  646. env['PDFLATEXCOM'] = CDCOM + '${TARGET.dir} && $PDFLATEX $PDFLATEXFLAGS ${SOURCE.file}'
  647. env['BIBTEX'] = 'bibtex'
  648. env['BIBTEXFLAGS'] = SCons.Util.CLVar('')
  649. env['BIBTEXCOM'] = CDCOM + '${TARGET.dir} && $BIBTEX $BIBTEXFLAGS ${SOURCE.filebase}'
  650. env['MAKEINDEX'] = 'makeindex'
  651. env['MAKEINDEXFLAGS'] = SCons.Util.CLVar('')
  652. env['MAKEINDEXCOM'] = CDCOM + '${TARGET.dir} && $MAKEINDEX $MAKEINDEXFLAGS ${SOURCE.file}'
  653. env['MAKEGLOSSARY'] = 'makeindex'
  654. env['MAKEGLOSSARYSTYLE'] = '${SOURCE.filebase}.ist'
  655. env['MAKEGLOSSARYFLAGS'] = SCons.Util.CLVar('-s ${MAKEGLOSSARYSTYLE} -t ${SOURCE.filebase}.glg')
  656. env['MAKEGLOSSARYCOM'] = CDCOM + '${TARGET.dir} && $MAKEGLOSSARY ${SOURCE.filebase}.glo $MAKEGLOSSARYFLAGS -o ${SOURCE.filebase}.gls'
  657. env['MAKEACRONYMS'] = 'makeindex'
  658. env['MAKEACRONYMSSTYLE'] = '${SOURCE.filebase}.ist'
  659. env['MAKEACRONYMSFLAGS'] = SCons.Util.CLVar('-s ${MAKEACRONYMSSTYLE} -t ${SOURCE.filebase}.alg')
  660. env['MAKEACRONYMSCOM'] = CDCOM + '${TARGET.dir} && $MAKEACRONYMS ${SOURCE.filebase}.acn $MAKEACRONYMSFLAGS -o ${SOURCE.filebase}.acr'
  661. env['MAKENCL'] = 'makeindex'
  662. env['MAKENCLSTYLE'] = 'nomencl.ist'
  663. env['MAKENCLFLAGS'] = '-s ${MAKENCLSTYLE} -t ${SOURCE.filebase}.nlg'
  664. env['MAKENCLCOM'] = CDCOM + '${TARGET.dir} && $MAKENCL ${SOURCE.filebase}.nlo $MAKENCLFLAGS -o ${SOURCE.filebase}.nls'
  665. def exists(env):
  666. return env.Detect('tex')
  667. # Local Variables:
  668. # tab-width:4
  669. # indent-tabs-mode:nil
  670. # End:
  671. # vim: set expandtab tabstop=4 shiftwidth=4: