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.

437 lines
17 KiB

6 years ago
  1. """SCons.Scanner.LaTeX
  2. This module implements the dependency scanner for LaTeX code.
  3. """
  4. #
  5. # Copyright (c) 2001 - 2017 The SCons Foundation
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining
  8. # a copy of this software and associated documentation files (the
  9. # "Software"), to deal in the Software without restriction, including
  10. # without limitation the rights to use, copy, modify, merge, publish,
  11. # distribute, sublicense, and/or sell copies of the Software, and to
  12. # permit persons to whom the Software is furnished to do so, subject to
  13. # the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included
  16. # in all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  19. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  20. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. #
  26. __revision__ = "src/engine/SCons/Scanner/LaTeX.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  27. import os.path
  28. import re
  29. import SCons.Scanner
  30. import SCons.Util
  31. # list of graphics file extensions for TeX and LaTeX
  32. TexGraphics = ['.eps', '.ps']
  33. #LatexGraphics = ['.pdf', '.png', '.jpg', '.gif', '.tif']
  34. LatexGraphics = [ '.png', '.jpg', '.gif', '.tif']
  35. # Used as a return value of modify_env_var if the variable is not set.
  36. class _Null(object):
  37. pass
  38. _null = _Null
  39. # The user specifies the paths in env[variable], similar to other builders.
  40. # They may be relative and must be converted to absolute, as expected
  41. # by LaTeX and Co. The environment may already have some paths in
  42. # env['ENV'][var]. These paths are honored, but the env[var] paths have
  43. # higher precedence. All changes are un-done on exit.
  44. def modify_env_var(env, var, abspath):
  45. try:
  46. save = env['ENV'][var]
  47. except KeyError:
  48. save = _null
  49. env.PrependENVPath(var, abspath)
  50. try:
  51. if SCons.Util.is_List(env[var]):
  52. env.PrependENVPath(var, [os.path.abspath(str(p)) for p in env[var]])
  53. else:
  54. # Split at os.pathsep to convert into absolute path
  55. env.PrependENVPath(var, [os.path.abspath(p) for p in str(env[var]).split(os.pathsep)])
  56. except KeyError:
  57. pass
  58. # Convert into a string explicitly to append ":" (without which it won't search system
  59. # paths as well). The problem is that env.AppendENVPath(var, ":")
  60. # does not work, refuses to append ":" (os.pathsep).
  61. if SCons.Util.is_List(env['ENV'][var]):
  62. env['ENV'][var] = os.pathsep.join(env['ENV'][var])
  63. # Append the trailing os.pathsep character here to catch the case with no env[var]
  64. env['ENV'][var] = env['ENV'][var] + os.pathsep
  65. return save
  66. class FindENVPathDirs(object):
  67. """
  68. A class to bind a specific E{*}PATH variable name to a function that
  69. will return all of the E{*}path directories.
  70. """
  71. def __init__(self, variable):
  72. self.variable = variable
  73. def __call__(self, env, dir=None, target=None, source=None, argument=None):
  74. import SCons.PathList
  75. try:
  76. path = env['ENV'][self.variable]
  77. except KeyError:
  78. return ()
  79. dir = dir or env.fs._cwd
  80. path = SCons.PathList.PathList(path).subst_path(env, target, source)
  81. return tuple(dir.Rfindalldirs(path))
  82. def LaTeXScanner():
  83. """
  84. Return a prototype Scanner instance for scanning LaTeX source files
  85. when built with latex.
  86. """
  87. ds = LaTeX(name = "LaTeXScanner",
  88. suffixes = '$LATEXSUFFIXES',
  89. # in the search order, see below in LaTeX class docstring
  90. graphics_extensions = TexGraphics,
  91. recursive = 0)
  92. return ds
  93. def PDFLaTeXScanner():
  94. """
  95. Return a prototype Scanner instance for scanning LaTeX source files
  96. when built with pdflatex.
  97. """
  98. ds = LaTeX(name = "PDFLaTeXScanner",
  99. suffixes = '$LATEXSUFFIXES',
  100. # in the search order, see below in LaTeX class docstring
  101. graphics_extensions = LatexGraphics,
  102. recursive = 0)
  103. return ds
  104. class LaTeX(SCons.Scanner.Base):
  105. """
  106. Class for scanning LaTeX files for included files.
  107. Unlike most scanners, which use regular expressions that just
  108. return the included file name, this returns a tuple consisting
  109. of the keyword for the inclusion ("include", "includegraphics",
  110. "input", or "bibliography"), and then the file name itself.
  111. Based on a quick look at LaTeX documentation, it seems that we
  112. should append .tex suffix for the "include" keywords, append .tex if
  113. there is no extension for the "input" keyword, and need to add .bib
  114. for the "bibliography" keyword that does not accept extensions by itself.
  115. Finally, if there is no extension for an "includegraphics" keyword
  116. latex will append .ps or .eps to find the file, while pdftex may use .pdf,
  117. .jpg, .tif, .mps, or .png.
  118. The actual subset and search order may be altered by
  119. DeclareGraphicsExtensions command. This complication is ignored.
  120. The default order corresponds to experimentation with teTeX::
  121. $ latex --version
  122. pdfeTeX 3.141592-1.21a-2.2 (Web2C 7.5.4)
  123. kpathsea version 3.5.4
  124. The order is:
  125. ['.eps', '.ps'] for latex
  126. ['.png', '.pdf', '.jpg', '.tif'].
  127. Another difference is that the search path is determined by the type
  128. of the file being searched:
  129. env['TEXINPUTS'] for "input" and "include" keywords
  130. env['TEXINPUTS'] for "includegraphics" keyword
  131. env['TEXINPUTS'] for "lstinputlisting" keyword
  132. env['BIBINPUTS'] for "bibliography" keyword
  133. env['BSTINPUTS'] for "bibliographystyle" keyword
  134. env['INDEXSTYLE'] for "makeindex" keyword, no scanning support needed just allows user to set it if needed.
  135. FIXME: also look for the class or style in document[class|style]{}
  136. FIXME: also look for the argument of bibliographystyle{}
  137. """
  138. keyword_paths = {'include': 'TEXINPUTS',
  139. 'input': 'TEXINPUTS',
  140. 'includegraphics': 'TEXINPUTS',
  141. 'bibliography': 'BIBINPUTS',
  142. 'bibliographystyle': 'BSTINPUTS',
  143. 'addbibresource': 'BIBINPUTS',
  144. 'addglobalbib': 'BIBINPUTS',
  145. 'addsectionbib': 'BIBINPUTS',
  146. 'makeindex': 'INDEXSTYLE',
  147. 'usepackage': 'TEXINPUTS',
  148. 'lstinputlisting': 'TEXINPUTS'}
  149. env_variables = SCons.Util.unique(list(keyword_paths.values()))
  150. two_arg_commands = ['import', 'subimport',
  151. 'includefrom', 'subincludefrom',
  152. 'inputfrom', 'subinputfrom']
  153. def __init__(self, name, suffixes, graphics_extensions, *args, **kw):
  154. # We have to include \n with the % we exclude from the first part
  155. # part of the regex because the expression is compiled with re.M.
  156. # Without the \n, the ^ could match the beginning of a *previous*
  157. # line followed by one or more newline characters (i.e. blank
  158. # lines), interfering with a match on the next line.
  159. # add option for whitespace before the '[options]' or the '{filename}'
  160. regex = r'''
  161. ^[^%\n]*
  162. \\(
  163. include
  164. | includegraphics(?:\s*\[[^\]]+\])?
  165. | lstinputlisting(?:\[[^\]]+\])?
  166. | input
  167. | import
  168. | subimport
  169. | includefrom
  170. | subincludefrom
  171. | inputfrom
  172. | subinputfrom
  173. | bibliography
  174. | addbibresource
  175. | addglobalbib
  176. | addsectionbib
  177. | usepackage
  178. )
  179. \s*{([^}]*)} # first arg
  180. (?: \s*{([^}]*)} )? # maybe another arg
  181. '''
  182. self.cre = re.compile(regex, re.M | re.X)
  183. self.comment_re = re.compile(r'^((?:(?:\\%)|[^%\n])*)(.*)$', re.M)
  184. self.graphics_extensions = graphics_extensions
  185. def _scan(node, env, path=(), self=self):
  186. node = node.rfile()
  187. if not node.exists():
  188. return []
  189. return self.scan_recurse(node, path)
  190. class FindMultiPathDirs(object):
  191. """The stock FindPathDirs function has the wrong granularity:
  192. it is called once per target, while we need the path that depends
  193. on what kind of included files is being searched. This wrapper
  194. hides multiple instances of FindPathDirs, one per the LaTeX path
  195. variable in the environment. When invoked, the function calculates
  196. and returns all the required paths as a dictionary (converted into
  197. a tuple to become hashable). Then the scan function converts it
  198. back and uses a dictionary of tuples rather than a single tuple
  199. of paths.
  200. """
  201. def __init__(self, dictionary):
  202. self.dictionary = {}
  203. for k,n in dictionary.items():
  204. self.dictionary[k] = ( SCons.Scanner.FindPathDirs(n),
  205. FindENVPathDirs(n) )
  206. def __call__(self, env, dir=None, target=None, source=None,
  207. argument=None):
  208. di = {}
  209. for k,(c,cENV) in self.dictionary.items():
  210. di[k] = ( c(env, dir=None, target=None, source=None,
  211. argument=None) ,
  212. cENV(env, dir=None, target=None, source=None,
  213. argument=None) )
  214. # To prevent "dict is not hashable error"
  215. return tuple(di.items())
  216. class LaTeXScanCheck(object):
  217. """Skip all but LaTeX source files, i.e., do not scan *.eps,
  218. *.pdf, *.jpg, etc.
  219. """
  220. def __init__(self, suffixes):
  221. self.suffixes = suffixes
  222. def __call__(self, node, env):
  223. current = not node.has_builder() or node.is_up_to_date()
  224. scannable = node.get_suffix() in env.subst_list(self.suffixes)[0]
  225. # Returning false means that the file is not scanned.
  226. return scannable and current
  227. kw['function'] = _scan
  228. kw['path_function'] = FindMultiPathDirs(LaTeX.keyword_paths)
  229. kw['recursive'] = 0
  230. kw['skeys'] = suffixes
  231. kw['scan_check'] = LaTeXScanCheck(suffixes)
  232. kw['name'] = name
  233. SCons.Scanner.Base.__init__(self, *args, **kw)
  234. def _latex_names(self, include_type, filename):
  235. if include_type == 'input':
  236. base, ext = os.path.splitext( filename )
  237. if ext == "":
  238. return [filename + '.tex']
  239. if include_type in ('include', 'import', 'subimport',
  240. 'includefrom', 'subincludefrom',
  241. 'inputfrom', 'subinputfrom'):
  242. base, ext = os.path.splitext( filename )
  243. if ext == "":
  244. return [filename + '.tex']
  245. if include_type == 'bibliography':
  246. base, ext = os.path.splitext( filename )
  247. if ext == "":
  248. return [filename + '.bib']
  249. if include_type == 'usepackage':
  250. base, ext = os.path.splitext( filename )
  251. if ext == "":
  252. return [filename + '.sty']
  253. if include_type == 'includegraphics':
  254. base, ext = os.path.splitext( filename )
  255. if ext == "":
  256. #return [filename+e for e in self.graphics_extensions + TexGraphics]
  257. # use the line above to find dependencies for the PDF builder
  258. # when only an .eps figure is present. Since it will be found
  259. # if the user tells scons how to make the pdf figure, leave
  260. # it out for now.
  261. return [filename+e for e in self.graphics_extensions]
  262. return [filename]
  263. def sort_key(self, include):
  264. return SCons.Node.FS._my_normcase(str(include))
  265. def find_include(self, include, source_dir, path):
  266. inc_type, inc_subdir, inc_filename = include
  267. try:
  268. sub_paths = path[inc_type]
  269. except (IndexError, KeyError):
  270. sub_paths = ((), ())
  271. try_names = self._latex_names(inc_type, inc_filename)
  272. # There are three search paths to try:
  273. # 1. current directory "source_dir"
  274. # 2. env[var]
  275. # 3. env['ENV'][var]
  276. search_paths = [(source_dir,)] + list(sub_paths)
  277. for n in try_names:
  278. for search_path in search_paths:
  279. paths = tuple([d.Dir(inc_subdir) for d in search_path])
  280. i = SCons.Node.FS.find_file(n, paths)
  281. if i:
  282. return i, include
  283. return None, include
  284. def canonical_text(self, text):
  285. """Standardize an input TeX-file contents.
  286. Currently:
  287. * removes comments, unwrapping comment-wrapped lines.
  288. """
  289. out = []
  290. line_continues_a_comment = False
  291. for line in text.splitlines():
  292. line,comment = self.comment_re.findall(line)[0]
  293. if line_continues_a_comment == True:
  294. out[-1] = out[-1] + line.lstrip()
  295. else:
  296. out.append(line)
  297. line_continues_a_comment = len(comment) > 0
  298. return '\n'.join(out).rstrip()+'\n'
  299. def scan(self, node, subdir='.'):
  300. # Modify the default scan function to allow for the regular
  301. # expression to return a comma separated list of file names
  302. # as can be the case with the bibliography keyword.
  303. # Cache the includes list in node so we only scan it once:
  304. # path_dict = dict(list(path))
  305. # add option for whitespace (\s) before the '['
  306. noopt_cre = re.compile('\s*\[.*$')
  307. if node.includes != None:
  308. includes = node.includes
  309. else:
  310. text = self.canonical_text(node.get_text_contents())
  311. includes = self.cre.findall(text)
  312. # 1. Split comma-separated lines, e.g.
  313. # ('bibliography', 'phys,comp')
  314. # should become two entries
  315. # ('bibliography', 'phys')
  316. # ('bibliography', 'comp')
  317. # 2. Remove the options, e.g., such as
  318. # ('includegraphics[clip,width=0.7\\linewidth]', 'picture.eps')
  319. # should become
  320. # ('includegraphics', 'picture.eps')
  321. split_includes = []
  322. for include in includes:
  323. inc_type = noopt_cre.sub('', include[0])
  324. inc_subdir = subdir
  325. if inc_type in self.two_arg_commands:
  326. inc_subdir = os.path.join(subdir, include[1])
  327. inc_list = include[2].split(',')
  328. else:
  329. inc_list = include[1].split(',')
  330. for j in range(len(inc_list)):
  331. split_includes.append( (inc_type, inc_subdir, inc_list[j]) )
  332. #
  333. includes = split_includes
  334. node.includes = includes
  335. return includes
  336. def scan_recurse(self, node, path=()):
  337. """ do a recursive scan of the top level target file
  338. This lets us search for included files based on the
  339. directory of the main file just as latex does"""
  340. path_dict = dict(list(path))
  341. queue = []
  342. queue.extend( self.scan(node) )
  343. seen = {}
  344. # This is a hand-coded DSU (decorate-sort-undecorate, or
  345. # Schwartzian transform) pattern. The sort key is the raw name
  346. # of the file as specifed on the \include, \input, etc. line.
  347. # TODO: what about the comment in the original Classic scanner:
  348. # """which lets
  349. # us keep the sort order constant regardless of whether the file
  350. # is actually found in a Repository or locally."""
  351. nodes = []
  352. source_dir = node.get_dir()
  353. #for include in includes:
  354. while queue:
  355. include = queue.pop()
  356. inc_type, inc_subdir, inc_filename = include
  357. try:
  358. if seen[inc_filename] == 1:
  359. continue
  360. except KeyError:
  361. seen[inc_filename] = 1
  362. #
  363. # Handle multiple filenames in include[1]
  364. #
  365. n, i = self.find_include(include, source_dir, path_dict)
  366. if n is None:
  367. # Do not bother with 'usepackage' warnings, as they most
  368. # likely refer to system-level files
  369. if inc_type != 'usepackage':
  370. SCons.Warnings.warn(SCons.Warnings.DependencyWarning,
  371. "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node))
  372. else:
  373. sortkey = self.sort_key(n)
  374. nodes.append((sortkey, n))
  375. # recurse down
  376. queue.extend( self.scan(n, inc_subdir) )
  377. return [pair[1] for pair in sorted(nodes)]
  378. # Local Variables:
  379. # tab-width:4
  380. # indent-tabs-mode:nil
  381. # End:
  382. # vim: set expandtab tabstop=4 shiftwidth=4: