3 This module implements the dependency scanner for LaTeX code.
10 # Permission is hereby granted, free of charge, to any person obtaining
11 # a copy of this software and associated documentation files (the
12 # "Software"), to deal in the Software without restriction, including
13 # without limitation the rights to use, copy, modify, merge, publish,
14 # distribute, sublicense, and/or sell copies of the Software, and to
15 # permit persons to whom the Software is furnished to do so, subject to
16 # the following conditions:
18 # The above copyright notice and this permission notice shall be included
19 # in all copies or substantial portions of the Software.
21 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
22 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
23 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
39 """Return a prototype Scanner instance for scanning LaTeX source files
40 when built with latex.
42 ds = LaTeX(name = "LaTeXScanner",
43 suffixes = '$LATEXSUFFIXES',
44 # in the search order, see below in LaTeX class docstring
45 graphics_extensions = ['.eps', '.ps'],
49 def PDFLaTeXScanner():
50 """Return a prototype Scanner instance for scanning LaTeX source files
51 when built with pdflatex.
53 ds = LaTeX(name = "PDFLaTeXScanner",
54 suffixes = '$LATEXSUFFIXES',
55 # in the search order, see below in LaTeX class docstring
56 graphics_extensions = ['.png', '.pdf', '.jpg', '.tif'],
60 class LaTeX(SCons.Scanner.Base):
61 """Class for scanning LaTeX files for included files.
63 Unlike most scanners, which use regular expressions that just
64 return the included file name, this returns a tuple consisting
65 of the keyword for the inclusion ("include", "includegraphics",
66 "input", or "bibliography"), and then the file name itself.
67 Based on a quick look at LaTeX documentation, it seems that we
68 should append .tex suffix for the "include" keywords, append .tex if
69 there is no extension for the "input" keyword, and need to add .bib
70 for the "bibliography" keyword that does not accept extensions by itself.
72 Finally, if there is no extension for an "includegraphics" keyword
73 latex will append .ps or .eps to find the file, while pdftex may use .pdf,
74 .jpg, .tif, .mps, or .png.
76 The actual subset and search order may be altered by
77 DeclareGraphicsExtensions command. This complication is ignored.
78 The default order corresponds to experimentation with teTeX
80 pdfeTeX 3.141592-1.21a-2.2 (Web2C 7.5.4)
81 kpathsea version 3.5.4
83 ['.eps', '.ps'] for latex
84 ['.png', '.pdf', '.jpg', '.tif'].
86 Another difference is that the search path is determined by the type
87 of the file being searched:
88 env['TEXINPUTS'] for "input" and "include" keywords
89 env['TEXPICTS'] for "includegraphics" keyword
90 env['BIBINPUTS'] for "bibliography" keyword
91 env['BSTINPUTS'] for "bibliographystyle" keyword
93 FIXME: also look for the class or style in document[class|style]{}
94 FIXME: also look for the argument of bibliographystyle{}
96 keyword_paths = {'include': 'TEXINPUTS',
98 'includegraphics': 'TEXPICTS',
99 'bibliography': 'BIBINPUTS',
100 'bibliographystyle': 'BSTINPUTS',
101 'usepackage': 'TEXINPUTS'}
102 env_variables = SCons.Util.unique(keyword_paths.values())
104 def __init__(self, name, suffixes, graphics_extensions, *args, **kw):
106 regex = '\\\\(include|includegraphics(?:\[[^\]]+\])?|input|bibliography|usepackage){([^}]*)}'
107 self.cre = re.compile(regex, re.M)
108 self.graphics_extensions = graphics_extensions
110 def _scan(node, env, path=(), self=self):
112 if not node.exists():
114 return self.scan(node, path)
116 class FindMultiPathDirs:
117 """The stock FindPathDirs function has the wrong granularity:
118 it is called once per target, while we need the path that depends
119 on what kind of included files is being searched. This wrapper
120 hides multiple instances of FindPathDirs, one per the LaTeX path
121 variable in the environment. When invoked, the function calculates
122 and returns all the required paths as a dictionary (converted into
123 a tuple to become hashable). Then the scan function converts it
124 back and uses a dictionary of tuples rather than a single tuple
127 def __init__(self, dictionary):
129 for k,n in dictionary.items():
130 self.dictionary[k] = SCons.Scanner.FindPathDirs(n)
132 def __call__(self, env, dir=None, target=None, source=None,
135 for k,c in self.dictionary.items():
136 di[k] = c(env, dir=None, target=None, source=None,
138 # To prevent "dict is not hashable error"
139 return tuple(di.items())
141 class LaTeXScanCheck:
142 """Skip all but LaTeX source files, i.e., do not scan *.eps,
145 def __init__(self, suffixes):
146 self.suffixes = suffixes
147 def __call__(self, node, env):
148 current = not node.has_builder() or node.is_up_to_date()
149 scannable = node.get_suffix() in env.subst(self.suffixes)
150 # Returning false means that the file is not scanned.
151 return scannable and current
153 kw['function'] = _scan
154 kw['path_function'] = FindMultiPathDirs(LaTeX.keyword_paths)
156 kw['skeys'] = suffixes
157 kw['scan_check'] = LaTeXScanCheck(suffixes)
160 apply(SCons.Scanner.Base.__init__, (self,) + args, kw)
162 def _latex_names(self, include):
163 filename = include[1]
164 if include[0] == 'input':
165 base, ext = os.path.splitext( filename )
167 return [filename + '.tex']
168 if (include[0] == 'include'):
169 return [filename + '.tex']
170 if include[0] == 'bibliography':
171 base, ext = os.path.splitext( filename )
173 return [filename + '.bib']
174 if include[0] == 'usepackage':
175 base, ext = os.path.splitext( filename )
177 return [filename + '.sty']
178 if include[0] == 'includegraphics':
179 base, ext = os.path.splitext( filename )
181 #FUTURE return [filename + e for e in self.graphics_extensions]
182 return map(lambda e, f=filename: f+e, self.graphics_extensions)
185 def sort_key(self, include):
186 return SCons.Node.FS._my_normcase(str(include))
188 def find_include(self, include, source_dir, path):
190 sub_path = path[include[0]]
193 try_names = self._latex_names(include)
195 i = SCons.Node.FS.find_file(n, (source_dir,) + sub_path)
200 def scan(self, node, path=()):
201 # Modify the default scan function to allow for the regular
202 # expression to return a comma separated list of file names
203 # as can be the case with the bibliography keyword.
205 # Cache the includes list in node so we only scan it once:
206 path_dict = dict(list(path))
207 noopt_cre = re.compile('\[.*$')
208 if node.includes != None:
209 includes = node.includes
211 includes = self.cre.findall(node.get_contents())
212 # 1. Split comma-separated lines, e.g.
213 # ('bibliography', 'phys,comp')
214 # should become two entries
215 # ('bibliography', 'phys')
216 # ('bibliography', 'comp')
217 # 2. Remove the options, e.g., such as
218 # ('includegraphics[clip,width=0.7\\linewidth]', 'picture.eps')
220 # ('includegraphics', 'picture.eps')
222 for include in includes:
223 inc_type = noopt_cre.sub('', include[0])
224 inc_list = string.split(include[1],',')
225 for j in range(len(inc_list)):
226 split_includes.append( (inc_type, inc_list[j]) )
228 includes = split_includes
229 node.includes = includes
231 # This is a hand-coded DSU (decorate-sort-undecorate, or
232 # Schwartzian transform) pattern. The sort key is the raw name
233 # of the file as specifed on the \include, \input, etc. line.
234 # TODO: what about the comment in the original Classic scanner:
236 # us keep the sort order constant regardless of whether the file
237 # is actually found in a Repository or locally."""
239 source_dir = node.get_dir()
240 for include in includes:
242 # Handle multiple filenames in include[1]
244 n, i = self.find_include(include, source_dir, path_dict)
246 # Do not bother with 'usepackage' warnings, as they most
247 # likely refer to system-level files
248 if include[0] != 'usepackage':
249 SCons.Warnings.warn(SCons.Warnings.DependencyWarning,
250 "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node))
252 sortkey = self.sort_key(n)
253 nodes.append((sortkey, n))
256 nodes = map(lambda pair: pair[1], nodes)