#! /usr/bin/env python import os, sys, string, re, time, optparse citationRexp = re.compile(r'(?P\[!.+?!\])', re.S) def moveToBackup(infilename, timeformat='%y%m%d-%H%M'): inroot, extension = os.path.splitext(infilename) outname = '%s_%s%s' % (inroot, time.strftime(timeformat),extension) try: os.rename(infilename, outname) except IOError, msg: sys.exit("Error writing backup file %s: \n %s" % (outname,msg)) return outname def convertToBibtex(matchObj): """Converts [!Zhang, 1993, zhang1993-3345!] to \citestring{zhang1993-3345}; depends on the global citestring variable""" refDelim = ';' intraRefDelim = ',' #citestring = 'citep' orig = matchObj.group('ref') reflist = orig[2:-2].split(refDelim) # get last element in each list resulting from splitting using intraRefDelim labelList = [x.split(intraRefDelim)[-1].strip() for x in reflist if x.strip() != ''] labelList.sort() for l in labelList: all_refs_global[l] = '' out = (r'\%s{%s}') % (citestring, string.join(labelList,', ')) #print orig, '-->', out return out #def open_infile(): def replaceCitations(instring, rexp=citationRexp): """Replaces citations enclosed by the specified tags with \cite{ref} style citations.""" clist = citationRexp.findall(instring) outstring = rexp.sub(convertToBibtex, instring) return outstring, clist class Option (optparse.Option): ATTRS = optparse.Option.ATTRS + ['required'] def _check_required (self): if self.required and not self.takes_value(): raise OptionError( "required flag set for option that doesn't take a value", self) # Make sure _check_required() is called from the constructor! CHECK_METHODS = optparse.Option.CHECK_METHODS + [_check_required] def process (self, opt, value, values, parser): optparse.Option.process(self, opt, value, values, parser) parser.option_seen[self] = 1 class OptionParser(optparse.OptionParser): def _init_parsing_state (self): optparse.OptionParser._init_parsing_state(self) self.option_seen = {} def check_values (self, values, args): for option in self.option_list: if (isinstance(option, Option) and option.required and not self.option_seen.has_key(option)): self.error("%s not supplied" % option) return (values, args) def main(): usage = """usage: %prog [options] Converts all citations enclosed by temporary citation markers in the format [!Author, Year, Label!] to BibTeX format citations (i.e., \cite{Label}). Example: %prog -f infile.tex -o outfile.tex -c citep""" version = '$Id: texref.py,v 1.1 2004/10/10 02:53:10 nghoffma Exp $' make_option = optparse.make_option # -h,--help and --version options are built-in option_list=[ Option('-f','--infile', dest='infile', help='input file', required=1), Option('-o','--outfile', dest='outfile', help='name of outfile; replaces infile by default', default=None), Option('-c','--citestring', dest='citestring', help='command to precede citations (ie, \command{Label})', default='cite'), Option('-v', '--verbose', action='store_true', dest='verbose', help='be verbose'), Option('-l','--list', action='store_true', dest='list_only', help='print a list of all refs and stop'), #make_option("--secret", help=SUPPRESS_HELP) ] parser = OptionParser(usage=usage, version=version, option_list=option_list, #conflict_handler='resolve' ) (options, args) = parser.parse_args() v = options.verbose list_only = options.list_only global citestring citestring = options.citestring infilename = options.infile infile = open(infilename) instring = infile.read() infile.close() outfilename = options.outfile #################################### # global variable to hold all of the ref labels found global all_refs_global all_refs_global = {} newstring, citationList = replaceCitations(instring) all_refs = all_refs_global.keys() all_refs.sort() if all_refs == []: sys.exit('No unformatted references were found in %s ... Exiting' % infilename) elif v: print "Found %s references in %s citations." % (len(all_refs), len(citationList)) if list_only: for ref in all_refs: print ref sys.exit() if not outfilename: outfilename = infilename # make a backup copy if infile is to be replaced backup_filename = moveToBackup(infilename) if v: print 'Backed up "%s" to "%s"' % (infilename, backup_filename) # open a new file and write the output if v: print 'The LaTeX citation command is "%s"' % citestring print 'Writing %s with modified citations.' % outfilename outfile = open(outfilename,'w') outfile.write(newstring) outfile.close() if __name__ == '__main__': main()