1"""SCons.Scanner.LaTeX 2 3This module implements the dependency scanner for LaTeX code. 4 5""" 6 7# 8# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation 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__="src/engine/SCons/Scanner/LaTeX.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" 31 32importos.path 33importre 34 35importSCons.Scanner 36importSCons.Util 37 38# list of graphics file extensions for TeX and LaTeX 39TexGraphics=['.eps','.ps'] 40LatexGraphics=['.pdf','.png','.jpg','.gif','.tif'] 41 42# Used as a return value of modify_env_var if the variable is not set.

45_null=_Null 46 47# The user specifies the paths in env[variable], similar to other builders. 48# They may be relative and must be converted to absolute, as expected 49# by LaTeX and Co. The environment may already have some paths in 50# env['ENV'][var]. These paths are honored, but the env[var] paths have 51# higher precedence. All changes are un-done on exit.

97"""Return a prototype Scanner instance for scanning LaTeX source files 98 when built with latex. 99 """100ds=LaTeX(name="LaTeXScanner",101suffixes='$LATEXSUFFIXES',102# in the search order, see below in LaTeX class docstring103graphics_extensions=TexGraphics,104recursive=0)105returnds

108"""Return a prototype Scanner instance for scanning LaTeX source files109 when built with pdflatex.110 """111ds=LaTeX(name="PDFLaTeXScanner",112suffixes='$LATEXSUFFIXES',113# in the search order, see below in LaTeX class docstring114graphics_extensions=LatexGraphics,115recursive=0)116returnds

119"""Class for scanning LaTeX files for included files.120121 Unlike most scanners, which use regular expressions that just122 return the included file name, this returns a tuple consisting123 of the keyword for the inclusion ("include", "includegraphics",124 "input", or "bibliography"), and then the file name itself. 125 Based on a quick look at LaTeX documentation, it seems that we 126 should append .tex suffix for the "include" keywords, append .tex if127 there is no extension for the "input" keyword, and need to add .bib128 for the "bibliography" keyword that does not accept extensions by itself.129130 Finally, if there is no extension for an "includegraphics" keyword131 latex will append .ps or .eps to find the file, while pdftex may use .pdf,132 .jpg, .tif, .mps, or .png.133134 The actual subset and search order may be altered by135 DeclareGraphicsExtensions command. This complication is ignored.136 The default order corresponds to experimentation with teTeX137 $ latex --version138 pdfeTeX 3.141592-1.21a-2.2 (Web2C 7.5.4)139 kpathsea version 3.5.4140 The order is:141 ['.eps', '.ps'] for latex142 ['.png', '.pdf', '.jpg', '.tif'].143144 Another difference is that the search path is determined by the type145 of the file being searched:146 env['TEXINPUTS'] for "input" and "include" keywords147 env['TEXINPUTS'] for "includegraphics" keyword148 env['TEXINPUTS'] for "lstinputlisting" keyword149 env['BIBINPUTS'] for "bibliography" keyword150 env['BSTINPUTS'] for "bibliographystyle" keyword151 env['INDEXSTYLE'] for "makeindex" keyword, no scanning support needed152 just allows user to set it if needed.153154 FIXME: also look for the class or style in document[class|style]{}155 FIXME: also look for the argument of bibliographystyle{}156 """157keyword_paths={'include':'TEXINPUTS',158'input':'TEXINPUTS',159'includegraphics':'TEXINPUTS',160'bibliography':'BIBINPUTS',161'bibliographystyle':'BSTINPUTS',162'addbibresource':'BIBINPUTS',163'addglobalbib':'BIBINPUTS',164'addsectionbib':'BIBINPUTS',165'makeindex':'INDEXSTYLE',166'usepackage':'TEXINPUTS',167'lstinputlisting':'TEXINPUTS'}168env_variables=SCons.Util.unique(list(keyword_paths.values()))169

171172# We have to include \n with the % we exclude from the first part173# part of the regex because the expression is compiled with re.M.174# Without the \n, the ^ could match the beginning of a *previous*175# line followed by one or more newline characters (i.e. blank176# lines), interfering with a match on the next line.177# add option for whitespace before the '[options]' or the '{filename}'178regex=r'^[^%\n]*\\(include|includegraphics(?:\s*\[[^\]]+\])?|lstinputlisting(?:\[[^\]]+\])?|input|bibliography|addbibresource|addglobalbib|addsectionbib|usepackage)\s*{([^}]*)}'179self.cre=re.compile(regex,re.M)180self.comment_re=re.compile(r'^((?:(?:\\%)|[^%\n])*)(.*)$',re.M)181182self.graphics_extensions=graphics_extensions183184def_scan(node,env,path=(),self=self):185node=node.rfile()186ifnotnode.exists():187return[]188returnself.scan_recurse(node,path)

189190classFindMultiPathDirs(object):191"""The stock FindPathDirs function has the wrong granularity:192 it is called once per target, while we need the path that depends193 on what kind of included files is being searched. This wrapper194 hides multiple instances of FindPathDirs, one per the LaTeX path195 variable in the environment. When invoked, the function calculates196 and returns all the required paths as a dictionary (converted into197 a tuple to become hashable). Then the scan function converts it198 back and uses a dictionary of tuples rather than a single tuple199 of paths.200 """201def__init__(self,dictionary):202self.dictionary={}203fork,nindictionary.items():204self.dictionary[k]=(SCons.Scanner.FindPathDirs(n),205FindENVPathDirs(n))

206207def__call__(self,env,dir=None,target=None,source=None,208argument=None):209di={}210fork,(c,cENV)inself.dictionary.items():211di[k]=(c(env,dir=None,target=None,source=None,212argument=None),213cENV(env,dir=None,target=None,source=None,214argument=None))215# To prevent "dict is not hashable error"216returntuple(di.items())217218classLaTeXScanCheck(object):219"""Skip all but LaTeX source files, i.e., do not scan *.eps,220 *.pdf, *.jpg, etc.221 """222def__init__(self,suffixes):223self.suffixes=suffixes224def__call__(self,node,env):225current=notnode.has_builder()ornode.is_up_to_date()226scannable=node.get_suffix()inenv.subst_list(self.suffixes)[0]227# Returning false means that the file is not scanned.228returnscannableandcurrent229230kw['function']=_scan231kw['path_function']=FindMultiPathDirs(LaTeX.keyword_paths)232kw['recursive']=0233kw['skeys']=suffixes234kw['scan_check']=LaTeXScanCheck(suffixes)235kw['name']=name236237SCons.Scanner.Base.__init__(self,*args,**kw)238

240filename=include[1]241ifinclude[0]=='input':242base,ext=os.path.splitext(filename)243ifext=="":244return[filename+'.tex']245if(include[0]=='include'):246return[filename+'.tex']247ifinclude[0]=='bibliography':248base,ext=os.path.splitext(filename)249ifext=="":250return[filename+'.bib']251ifinclude[0]=='usepackage':252base,ext=os.path.splitext(filename)253ifext=="":254return[filename+'.sty']255ifinclude[0]=='includegraphics':256base,ext=os.path.splitext(filename)257ifext=="":258#return [filename+e for e in self.graphics_extensions + TexGraphics]259# use the line above to find dependencies for the PDF builder260# when only an .eps figure is present. Since it will be found261# if the user tells scons how to make the pdf figure, leave262# it out for now.263return[filename+eforeinself.graphics_extensions]264return[filename]

270try:271sub_path=path[include[0]]272except(IndexError,KeyError):273sub_path=()274try_names=self._latex_names(include)275fornintry_names:276# see if we find it using the path in env[var]277i=SCons.Node.FS.find_file(n,(source_dir,)+sub_path[0])278ifi:279returni,include280# see if we find it using the path in env['ENV'][var]281i=SCons.Node.FS.find_file(n,(source_dir,)+sub_path[1])282ifi:283returni,include284returni,include

304# Modify the default scan function to allow for the regular305# expression to return a comma separated list of file names306# as can be the case with the bibliography keyword.307308# Cache the includes list in node so we only scan it once:309# path_dict = dict(list(path))310# add option for whitespace (\s) before the '['311noopt_cre=re.compile('\s*\[.*$')312ifnode.includes!=None:313includes=node.includes314else:315text=self.canonical_text(node.get_text_contents())316includes=self.cre.findall(text)317# 1. Split comma-separated lines, e.g.318# ('bibliography', 'phys,comp')319# should become two entries320# ('bibliography', 'phys')321# ('bibliography', 'comp')322# 2. Remove the options, e.g., such as323# ('includegraphics[clip,width=0.7\\linewidth]', 'picture.eps')324# should become325# ('includegraphics', 'picture.eps')326split_includes=[]327forincludeinincludes:328inc_type=noopt_cre.sub('',include[0])329inc_list=include[1].split(',')330forjinrange(len(inc_list)):331split_includes.append((inc_type,inc_list[j]))332#333includes=split_includes334node.includes=includes335336returnincludes

339""" do a recursive scan of the top level target file340 This lets us search for included files based on the341 directory of the main file just as latex does"""342343path_dict=dict(list(path))344345queue=[]346queue.extend(self.scan(node))347seen={}348349# This is a hand-coded DSU (decorate-sort-undecorate, or350# Schwartzian transform) pattern. The sort key is the raw name351# of the file as specifed on the \include, \input, etc. line.352# TODO: what about the comment in the original Classic scanner:353# """which lets354# us keep the sort order constant regardless of whether the file355# is actually found in a Repository or locally."""356nodes=[]357source_dir=node.get_dir()358#for include in includes:359whilequeue:360361include=queue.pop()362try:363ifseen[include[1]]==1:364continue365exceptKeyError:366seen[include[1]]=1367368#369# Handle multiple filenames in include[1]370#371n,i=self.find_include(include,source_dir,path_dict)372ifnisNone:373# Do not bother with 'usepackage' warnings, as they most374# likely refer to system-level files375ifinclude[0]!='usepackage':376SCons.Warnings.warn(SCons.Warnings.DependencyWarning,377"No dependency generated for file: %s (included from: %s) -- file not found"%(i,node))378else:379sortkey=self.sort_key(n)380nodes.append((sortkey,n))381# recurse down 382queue.extend(self.scan(n))383384return[pair[1]forpairinsorted(nodes)]