Fix syntax and semantic errors preventing regression tests from running on 1.5.2
[scons.git] / src / engine / SCons / Scanner / LaTeX.py
1 """SCons.Scanner.LaTeX
2
3 This module implements the dependency scanner for LaTeX code.
4
5 """
6
7 #
8 # __COPYRIGHT__
9 #
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:
17 #
18 # The above copyright notice and this permission notice shall be included
19 # in all copies or substantial portions of the Software.
20 #
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.
28 #
29
30 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
31
32 import os.path
33 import string
34 import re
35
36 import SCons.Scanner
37
38 def LaTeXScanner():
39     """Return a prototype Scanner instance for scanning LaTeX source files
40     when built with latex.
41     """
42     ds = LaTeX(name = "LaTeXScanner",
43                suffixes =  '$LATEXSUFFIXES',
44                # in the search order, see below in LaTeX class docstring
45                graphics_extensions = ['.eps', '.ps'],
46                recursive = 0)
47     return ds
48
49 def PDFLaTeXScanner():
50     """Return a prototype Scanner instance for scanning LaTeX source files
51     when built with pdflatex.
52     """
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'],
57                recursive = 0)
58     return ds
59
60 class LaTeX(SCons.Scanner.Base):
61     """Class for scanning LaTeX files for included files.
62
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.
71
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.
75     
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
79         $ latex --version
80         pdfeTeX 3.141592-1.21a-2.2 (Web2C 7.5.4)
81         kpathsea version 3.5.4
82     The order is:
83         ['.eps', '.ps'] for latex
84         ['.png', '.pdf', '.jpg', '.tif'].
85
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
92
93     FIXME: also look for the class or style in document[class|style]{}
94     FIXME: also look for the argument of bibliographystyle{}
95     """
96     keyword_paths = {'include': 'TEXINPUTS',
97                      'input': 'TEXINPUTS',
98                      'includegraphics': 'TEXPICTS',
99                      'bibliography': 'BIBINPUTS',
100                      'bibliographystyle': 'BSTINPUTS',
101                      'usepackage': 'TEXINPUTS'}
102     env_variables = SCons.Util.unique(keyword_paths.values())
103
104     def __init__(self, name, suffixes, graphics_extensions, *args, **kw):
105
106         regex = '\\\\(include|includegraphics(?:\[[^\]]+\])?|input|bibliography|usepackage){([^}]*)}'
107         self.cre = re.compile(regex, re.M)
108         self.graphics_extensions = graphics_extensions
109
110         def _scan(node, env, path=(), self=self):
111             node = node.rfile()
112             if not node.exists():
113                 return []
114             return self.scan(node, path)
115
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
125             of paths.
126             """
127             def __init__(self, dictionary):
128                 self.dictionary = {}
129                 for k,n in dictionary.items():
130                     self.dictionary[k] = SCons.Scanner.FindPathDirs(n)
131
132             def __call__(self, env, dir=None, target=None, source=None,
133                                     argument=None):
134                 di = {}
135                 for k,c  in self.dictionary.items():
136                     di[k] = c(env, dir=None, target=None, source=None,
137                                    argument=None)
138                 # To prevent "dict is not hashable error"
139                 return tuple(di.items())
140
141         class LaTeXScanCheck:
142             """Skip all but LaTeX source files, i.e., do not scan *.eps,
143             *.pdf, *.jpg, etc.
144             """
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
152
153         kw['function'] = _scan
154         kw['path_function'] = FindMultiPathDirs(LaTeX.keyword_paths)
155         kw['recursive'] = 1
156         kw['skeys'] = suffixes
157         kw['scan_check'] = LaTeXScanCheck(suffixes)
158         kw['name'] = name
159
160         apply(SCons.Scanner.Base.__init__, (self,) + args, kw)
161
162     def _latex_names(self, include):
163         filename = include[1]
164         if include[0] == 'input':
165             base, ext = os.path.splitext( filename )
166             if ext == "":
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 )
172             if ext == "":
173                 return [filename + '.bib']
174         if include[0] == 'usepackage':
175             base, ext = os.path.splitext( filename )
176             if ext == "":
177                 return [filename + '.sty']
178         if include[0] == 'includegraphics':
179             base, ext = os.path.splitext( filename )
180             if ext == "":
181                 #FUTURE return [filename + e for e in self.graphics_extensions]
182                 return map(lambda e, f=filename: f+e, self.graphics_extensions)
183         return [filename]
184
185     def sort_key(self, include):
186         return SCons.Node.FS._my_normcase(str(include))
187
188     def find_include(self, include, source_dir, path):
189         try:
190             sub_path = path[include[0]]
191         except:
192             sub_path = ()
193         try_names = self._latex_names(include)
194         for n in try_names:
195             i = SCons.Node.FS.find_file(n, (source_dir,) + sub_path)
196             if i:
197                 return i, include
198         return i, include
199
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.
204
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
210         else:
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')
219             #    should become
220             #      ('includegraphics', 'picture.eps')
221             split_includes = []
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]) )
227             #
228             includes = split_includes
229             node.includes = includes
230
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:
235         # """which lets
236         # us keep the sort order constant regardless of whether the file
237         # is actually found in a Repository or locally."""
238         nodes = []
239         source_dir = node.get_dir()
240         for include in includes:
241             #
242             # Handle multiple filenames in include[1]
243             #
244             n, i = self.find_include(include, source_dir, path_dict)
245             if n is None:
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))
251             else:
252                 sortkey = self.sort_key(n)
253                 nodes.append((sortkey, n))
254         #
255         nodes.sort()
256         nodes = map(lambda pair: pair[1], nodes)
257         return nodes