PageRenderTime 89ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/couchjs/scons/scons-local-2.0.1/SCons/Scanner/LaTeX.py

http://github.com/cloudant/bigcouch
Python | 384 lines | 314 code | 17 blank | 53 comment | 13 complexity | af3078d5af5f790db44b8e3bcd335726 MD5 | raw file
Possible License(s): Apache-2.0
  1. """SCons.Scanner.LaTeX
  2. This module implements the dependency scanner for LaTeX code.
  3. """
  4. #
  5. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 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 5134 2010/08/16 23:02:40 bdeegan"
  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. # Used as a return value of modify_env_var if the variable is not set.
  35. class _Null(object):
  36. pass
  37. _null = _Null
  38. # The user specifies the paths in env[variable], similar to other builders.
  39. # They may be relative and must be converted to absolute, as expected
  40. # by LaTeX and Co. The environment may already have some paths in
  41. # env['ENV'][var]. These paths are honored, but the env[var] paths have
  42. # higher precedence. All changes are un-done on exit.
  43. def modify_env_var(env, var, abspath):
  44. try:
  45. save = env['ENV'][var]
  46. except KeyError:
  47. save = _null
  48. env.PrependENVPath(var, abspath)
  49. try:
  50. if SCons.Util.is_List(env[var]):
  51. env.PrependENVPath(var, [os.path.abspath(str(p)) for p in env[var]])
  52. else:
  53. # Split at os.pathsep to convert into absolute path
  54. env.PrependENVPath(var, [os.path.abspath(p) for p in str(env[var]).split(os.pathsep)])
  55. except KeyError:
  56. pass
  57. # Convert into a string explicitly to append ":" (without which it won't search system
  58. # paths as well). The problem is that env.AppendENVPath(var, ":")
  59. # does not work, refuses to append ":" (os.pathsep).
  60. if SCons.Util.is_List(env['ENV'][var]):
  61. env['ENV'][var] = os.pathsep.join(env['ENV'][var])
  62. # Append the trailing os.pathsep character here to catch the case with no env[var]
  63. env['ENV'][var] = env['ENV'][var] + os.pathsep
  64. return save
  65. class FindENVPathDirs(object):
  66. """A class to bind a specific *PATH variable name to a function that
  67. will return all of the *path directories."""
  68. def __init__(self, variable):
  69. self.variable = variable
  70. def __call__(self, env, dir=None, target=None, source=None, argument=None):
  71. import SCons.PathList
  72. try:
  73. path = env['ENV'][self.variable]
  74. except KeyError:
  75. return ()
  76. dir = dir or env.fs._cwd
  77. path = SCons.PathList.PathList(path).subst_path(env, target, source)
  78. return tuple(dir.Rfindalldirs(path))
  79. def LaTeXScanner():
  80. """Return a prototype Scanner instance for scanning LaTeX source files
  81. when built with latex.
  82. """
  83. ds = LaTeX(name = "LaTeXScanner",
  84. suffixes = '$LATEXSUFFIXES',
  85. # in the search order, see below in LaTeX class docstring
  86. graphics_extensions = TexGraphics,
  87. recursive = 0)
  88. return ds
  89. def PDFLaTeXScanner():
  90. """Return a prototype Scanner instance for scanning LaTeX source files
  91. when built with pdflatex.
  92. """
  93. ds = LaTeX(name = "PDFLaTeXScanner",
  94. suffixes = '$LATEXSUFFIXES',
  95. # in the search order, see below in LaTeX class docstring
  96. graphics_extensions = LatexGraphics,
  97. recursive = 0)
  98. return ds
  99. class LaTeX(SCons.Scanner.Base):
  100. """Class for scanning LaTeX files for included files.
  101. Unlike most scanners, which use regular expressions that just
  102. return the included file name, this returns a tuple consisting
  103. of the keyword for the inclusion ("include", "includegraphics",
  104. "input", or "bibliography"), and then the file name itself.
  105. Based on a quick look at LaTeX documentation, it seems that we
  106. should append .tex suffix for the "include" keywords, append .tex if
  107. there is no extension for the "input" keyword, and need to add .bib
  108. for the "bibliography" keyword that does not accept extensions by itself.
  109. Finally, if there is no extension for an "includegraphics" keyword
  110. latex will append .ps or .eps to find the file, while pdftex may use .pdf,
  111. .jpg, .tif, .mps, or .png.
  112. The actual subset and search order may be altered by
  113. DeclareGraphicsExtensions command. This complication is ignored.
  114. The default order corresponds to experimentation with teTeX
  115. $ latex --version
  116. pdfeTeX 3.141592-1.21a-2.2 (Web2C 7.5.4)
  117. kpathsea version 3.5.4
  118. The order is:
  119. ['.eps', '.ps'] for latex
  120. ['.png', '.pdf', '.jpg', '.tif'].
  121. Another difference is that the search path is determined by the type
  122. of the file being searched:
  123. env['TEXINPUTS'] for "input" and "include" keywords
  124. env['TEXINPUTS'] for "includegraphics" keyword
  125. env['TEXINPUTS'] for "lstinputlisting" keyword
  126. env['BIBINPUTS'] for "bibliography" keyword
  127. env['BSTINPUTS'] for "bibliographystyle" keyword
  128. FIXME: also look for the class or style in document[class|style]{}
  129. FIXME: also look for the argument of bibliographystyle{}
  130. """
  131. keyword_paths = {'include': 'TEXINPUTS',
  132. 'input': 'TEXINPUTS',
  133. 'includegraphics': 'TEXINPUTS',
  134. 'bibliography': 'BIBINPUTS',
  135. 'bibliographystyle': 'BSTINPUTS',
  136. 'usepackage': 'TEXINPUTS',
  137. 'lstinputlisting': 'TEXINPUTS'}
  138. env_variables = SCons.Util.unique(list(keyword_paths.values()))
  139. def __init__(self, name, suffixes, graphics_extensions, *args, **kw):
  140. # We have to include \n with the % we exclude from the first part
  141. # part of the regex because the expression is compiled with re.M.
  142. # Without the \n, the ^ could match the beginning of a *previous*
  143. # line followed by one or more newline characters (i.e. blank
  144. # lines), interfering with a match on the next line.
  145. # add option for whitespace before the '[options]' or the '{filename}'
  146. regex = r'^[^%\n]*\\(include|includegraphics(?:\s*\[[^\]]+\])?|lstinputlisting(?:\[[^\]]+\])?|input|bibliography|usepackage)\s*{([^}]*)}'
  147. self.cre = re.compile(regex, re.M)
  148. self.comment_re = re.compile(r'^((?:(?:\\%)|[^%\n])*)(.*)$', re.M)
  149. self.graphics_extensions = graphics_extensions
  150. def _scan(node, env, path=(), self=self):
  151. node = node.rfile()
  152. if not node.exists():
  153. return []
  154. return self.scan_recurse(node, path)
  155. class FindMultiPathDirs(object):
  156. """The stock FindPathDirs function has the wrong granularity:
  157. it is called once per target, while we need the path that depends
  158. on what kind of included files is being searched. This wrapper
  159. hides multiple instances of FindPathDirs, one per the LaTeX path
  160. variable in the environment. When invoked, the function calculates
  161. and returns all the required paths as a dictionary (converted into
  162. a tuple to become hashable). Then the scan function converts it
  163. back and uses a dictionary of tuples rather than a single tuple
  164. of paths.
  165. """
  166. def __init__(self, dictionary):
  167. self.dictionary = {}
  168. for k,n in dictionary.items():
  169. self.dictionary[k] = ( SCons.Scanner.FindPathDirs(n),
  170. FindENVPathDirs(n) )
  171. def __call__(self, env, dir=None, target=None, source=None,
  172. argument=None):
  173. di = {}
  174. for k,(c,cENV) in self.dictionary.items():
  175. di[k] = ( c(env, dir=None, target=None, source=None,
  176. argument=None) ,
  177. cENV(env, dir=None, target=None, source=None,
  178. argument=None) )
  179. # To prevent "dict is not hashable error"
  180. return tuple(di.items())
  181. class LaTeXScanCheck(object):
  182. """Skip all but LaTeX source files, i.e., do not scan *.eps,
  183. *.pdf, *.jpg, etc.
  184. """
  185. def __init__(self, suffixes):
  186. self.suffixes = suffixes
  187. def __call__(self, node, env):
  188. current = not node.has_builder() or node.is_up_to_date()
  189. scannable = node.get_suffix() in env.subst_list(self.suffixes)[0]
  190. # Returning false means that the file is not scanned.
  191. return scannable and current
  192. kw['function'] = _scan
  193. kw['path_function'] = FindMultiPathDirs(LaTeX.keyword_paths)
  194. kw['recursive'] = 0
  195. kw['skeys'] = suffixes
  196. kw['scan_check'] = LaTeXScanCheck(suffixes)
  197. kw['name'] = name
  198. SCons.Scanner.Base.__init__(self, *args, **kw)
  199. def _latex_names(self, include):
  200. filename = include[1]
  201. if include[0] == 'input':
  202. base, ext = os.path.splitext( filename )
  203. if ext == "":
  204. return [filename + '.tex']
  205. if (include[0] == 'include'):
  206. return [filename + '.tex']
  207. if include[0] == 'bibliography':
  208. base, ext = os.path.splitext( filename )
  209. if ext == "":
  210. return [filename + '.bib']
  211. if include[0] == 'usepackage':
  212. base, ext = os.path.splitext( filename )
  213. if ext == "":
  214. return [filename + '.sty']
  215. if include[0] == 'includegraphics':
  216. base, ext = os.path.splitext( filename )
  217. if ext == "":
  218. #return [filename+e for e in self.graphics_extensions + TexGraphics]
  219. # use the line above to find dependencies for the PDF builder
  220. # when only an .eps figure is present. Since it will be found
  221. # if the user tells scons how to make the pdf figure, leave
  222. # it out for now.
  223. return [filename+e for e in self.graphics_extensions]
  224. return [filename]
  225. def sort_key(self, include):
  226. return SCons.Node.FS._my_normcase(str(include))
  227. def find_include(self, include, source_dir, path):
  228. try:
  229. sub_path = path[include[0]]
  230. except (IndexError, KeyError):
  231. sub_path = ()
  232. try_names = self._latex_names(include)
  233. for n in try_names:
  234. # see if we find it using the path in env[var]
  235. i = SCons.Node.FS.find_file(n, (source_dir,) + sub_path[0])
  236. if i:
  237. return i, include
  238. # see if we find it using the path in env['ENV'][var]
  239. i = SCons.Node.FS.find_file(n, (source_dir,) + sub_path[1])
  240. if i:
  241. return i, include
  242. return i, include
  243. def canonical_text(self, text):
  244. """Standardize an input TeX-file contents.
  245. Currently:
  246. * removes comments, unwrapping comment-wrapped lines.
  247. """
  248. out = []
  249. line_continues_a_comment = False
  250. for line in text.splitlines():
  251. line,comment = self.comment_re.findall(line)[0]
  252. if line_continues_a_comment == True:
  253. out[-1] = out[-1] + line.lstrip()
  254. else:
  255. out.append(line)
  256. line_continues_a_comment = len(comment) > 0
  257. return '\n'.join(out).rstrip()+'\n'
  258. def scan(self, node):
  259. # Modify the default scan function to allow for the regular
  260. # expression to return a comma separated list of file names
  261. # as can be the case with the bibliography keyword.
  262. # Cache the includes list in node so we only scan it once:
  263. # path_dict = dict(list(path))
  264. # add option for whitespace (\s) before the '['
  265. noopt_cre = re.compile('\s*\[.*$')
  266. if node.includes != None:
  267. includes = node.includes
  268. else:
  269. text = self.canonical_text(node.get_text_contents())
  270. includes = self.cre.findall(text)
  271. # 1. Split comma-separated lines, e.g.
  272. # ('bibliography', 'phys,comp')
  273. # should become two entries
  274. # ('bibliography', 'phys')
  275. # ('bibliography', 'comp')
  276. # 2. Remove the options, e.g., such as
  277. # ('includegraphics[clip,width=0.7\\linewidth]', 'picture.eps')
  278. # should become
  279. # ('includegraphics', 'picture.eps')
  280. split_includes = []
  281. for include in includes:
  282. inc_type = noopt_cre.sub('', include[0])
  283. inc_list = include[1].split(',')
  284. for j in range(len(inc_list)):
  285. split_includes.append( (inc_type, inc_list[j]) )
  286. #
  287. includes = split_includes
  288. node.includes = includes
  289. return includes
  290. def scan_recurse(self, node, path=()):
  291. """ do a recursive scan of the top level target file
  292. This lets us search for included files based on the
  293. directory of the main file just as latex does"""
  294. path_dict = dict(list(path))
  295. queue = []
  296. queue.extend( self.scan(node) )
  297. seen = {}
  298. # This is a hand-coded DSU (decorate-sort-undecorate, or
  299. # Schwartzian transform) pattern. The sort key is the raw name
  300. # of the file as specifed on the \include, \input, etc. line.
  301. # TODO: what about the comment in the original Classic scanner:
  302. # """which lets
  303. # us keep the sort order constant regardless of whether the file
  304. # is actually found in a Repository or locally."""
  305. nodes = []
  306. source_dir = node.get_dir()
  307. #for include in includes:
  308. while queue:
  309. include = queue.pop()
  310. try:
  311. if seen[include[1]] == 1:
  312. continue
  313. except KeyError:
  314. seen[include[1]] = 1
  315. #
  316. # Handle multiple filenames in include[1]
  317. #
  318. n, i = self.find_include(include, source_dir, path_dict)
  319. if n is None:
  320. # Do not bother with 'usepackage' warnings, as they most
  321. # likely refer to system-level files
  322. if include[0] != 'usepackage':
  323. SCons.Warnings.warn(SCons.Warnings.DependencyWarning,
  324. "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node))
  325. else:
  326. sortkey = self.sort_key(n)
  327. nodes.append((sortkey, n))
  328. # recurse down
  329. queue.extend( self.scan(n) )
  330. return [pair[1] for pair in sorted(nodes)]
  331. # Local Variables:
  332. # tab-width:4
  333. # indent-tabs-mode:nil
  334. # End:
  335. # vim: set expandtab tabstop=4 shiftwidth=4: