scripts/bib2dox.py
author Alpar Juttner <alpar@cs.elte.hu>
Mon, 14 Dec 2009 06:07:52 +0100
changeset 888 f903263902f6
parent 792 68792fb2870f
child 905 c841ae1aca29
permissions -rwxr-xr-x
Merge #180 and a bugfix in #51
kpeter@790
     1
#!/usr/bin/env /usr/local/Python/bin/python2.1
kpeter@790
     2
"""
kpeter@790
     3
  BibTeX to Doxygen converter
kpeter@790
     4
  Usage: python bib2dox.py bibfile.bib > bibfile.dox
kpeter@790
     5
kpeter@790
     6
  This code is the modification of the BibTeX to XML converter
kpeter@790
     7
  by Vidar Bronken Gundersen et al. See the original copyright notices below. 
kpeter@790
     8
kpeter@790
     9
  **********************************************************************
kpeter@790
    10
kpeter@790
    11
  Decoder for bibliographic data, BibTeX
kpeter@790
    12
  Usage: python bibtex2xml.py bibfile.bib > bibfile.xml
kpeter@790
    13
kpeter@790
    14
  v.8
kpeter@790
    15
  (c)2002-06-23 Vidar Bronken Gundersen
kpeter@790
    16
  http://bibtexml.sf.net/
kpeter@790
    17
  Reuse approved as long as this notification is kept.
kpeter@790
    18
  Licence: GPL.
kpeter@790
    19
kpeter@790
    20
  Contributions/thanks to:
kpeter@790
    21
  Egon Willighagen, http://sf.net/projects/jreferences/
kpeter@790
    22
  Richard Mahoney (for providing a test case)
kpeter@790
    23
kpeter@790
    24
  Editted by Sara Sprenkle to be more robust and handle more bibtex features.
kpeter@790
    25
  (c) 2003-01-15
kpeter@790
    26
kpeter@790
    27
  1.  Changed bibtex: tags to bibxml: tags.
kpeter@790
    28
  2.  Use xmlns:bibxml="http://bibtexml.sf.net/"
kpeter@790
    29
  3.  Allow spaces between @type and first {
kpeter@790
    30
  4.  "author" fields with multiple authors split by " and "
kpeter@790
    31
      are put in separate xml "bibxml:author" tags.
kpeter@790
    32
  5.  Option for Titles: words are capitalized
kpeter@790
    33
      only if first letter in title or capitalized inside braces
kpeter@790
    34
  6.  Removes braces from within field values
kpeter@790
    35
  7.  Ignores comments in bibtex file (including @comment{ or % )
kpeter@790
    36
  8.  Replaces some special latex tags, e.g., replaces ~ with '&#160;'
kpeter@790
    37
  9.  Handles bibtex @string abbreviations
kpeter@790
    38
        --> includes bibtex's default abbreviations for months
kpeter@790
    39
        --> does concatenation of abbr # " more " and " more " # abbr
kpeter@790
    40
  10. Handles @type( ... ) or @type{ ... }
kpeter@790
    41
  11. The keywords field is split on , or ; and put into separate xml
kpeter@790
    42
      "bibxml:keywords" tags
kpeter@790
    43
  12. Ignores @preamble
kpeter@790
    44
kpeter@790
    45
  Known Limitations
kpeter@790
    46
  1.  Does not transform Latex encoding like math mode and special
kpeter@790
    47
      latex symbols.
kpeter@790
    48
  2.  Does not parse author fields into first and last names.
kpeter@790
    49
      E.g., It does not do anything special to an author whose name is
kpeter@790
    50
      in the form LAST_NAME, FIRST_NAME
kpeter@790
    51
      In "author" tag, will show up as
kpeter@790
    52
      <bibxml:author>LAST_NAME, FIRST_NAME</bibxml:author>
kpeter@790
    53
  3.  Does not handle "crossref" fields other than to print
kpeter@790
    54
      <bibxml:crossref>...</bibxml:crossref>
kpeter@790
    55
  4.  Does not inform user of the input's format errors.  You just won't
kpeter@790
    56
      be able to transform the file later with XSL
kpeter@790
    57
kpeter@790
    58
  You will have to manually edit the XML output if you need to handle
kpeter@790
    59
  these (and unknown) limitations.
kpeter@790
    60
kpeter@790
    61
"""
kpeter@790
    62
kpeter@790
    63
import string, re
kpeter@790
    64
kpeter@790
    65
# set of valid name characters
kpeter@790
    66
valid_name_chars = '[\w\-:]'
kpeter@790
    67
kpeter@790
    68
#
kpeter@790
    69
# define global regular expression variables
kpeter@790
    70
#
kpeter@790
    71
author_rex = re.compile('\s+and\s+')
kpeter@790
    72
rembraces_rex = re.compile('[{}]')
kpeter@801
    73
capitalize_rex = re.compile('({[^}]*})')
kpeter@790
    74
kpeter@790
    75
# used by bibtexkeywords(data)
kpeter@790
    76
keywords_rex = re.compile('[,;]')
kpeter@790
    77
kpeter@790
    78
# used by concat_line(line)
kpeter@790
    79
concatsplit_rex = re.compile('\s*#\s*')
kpeter@790
    80
kpeter@790
    81
# split on {, }, or " in verify_out_of_braces
kpeter@790
    82
delimiter_rex = re.compile('([{}"])',re.I)
kpeter@790
    83
kpeter@790
    84
field_rex = re.compile('\s*(\w*)\s*=\s*(.*)')
kpeter@790
    85
data_rex = re.compile('\s*(\w*)\s*=\s*([^,]*),?')
kpeter@790
    86
kpeter@790
    87
url_rex = re.compile('\\\url\{([^}]*)\}')
kpeter@790
    88
kpeter@792
    89
#
kpeter@792
    90
# styles for html formatting
kpeter@792
    91
#
kpeter@792
    92
divstyle = 'margin-top: -4ex; margin-left: 8em;'
kpeter@790
    93
kpeter@790
    94
#
kpeter@790
    95
# return the string parameter without braces
kpeter@790
    96
#
kpeter@790
    97
def transformurls(str):
kpeter@790
    98
    return url_rex.sub(r'<a href="\1">\1</a>', str)
kpeter@790
    99
kpeter@790
   100
#
kpeter@790
   101
# return the string parameter without braces
kpeter@790
   102
#
kpeter@790
   103
def removebraces(str):
kpeter@790
   104
    return rembraces_rex.sub('', str)
kpeter@790
   105
kpeter@790
   106
#
kpeter@790
   107
# latex-specific replacements
kpeter@790
   108
# (do this after braces were removed)
kpeter@790
   109
#
kpeter@790
   110
def latexreplacements(line):
kpeter@790
   111
    line = string.replace(line, '~', '&nbsp;')
kpeter@790
   112
    line = string.replace(line, '\\\'a', '&aacute;')
kpeter@790
   113
    line = string.replace(line, '\\"a', '&auml;')
kpeter@790
   114
    line = string.replace(line, '\\\'e', '&eacute;')
kpeter@790
   115
    line = string.replace(line, '\\"e', '&euml;')
kpeter@790
   116
    line = string.replace(line, '\\\'i', '&iacute;')
kpeter@790
   117
    line = string.replace(line, '\\"i', '&iuml;')
kpeter@790
   118
    line = string.replace(line, '\\\'o', '&oacute;')
kpeter@790
   119
    line = string.replace(line, '\\"o', '&ouml;')
kpeter@790
   120
    line = string.replace(line, '\\\'u', '&uacute;')
kpeter@790
   121
    line = string.replace(line, '\\"u', '&uuml;')
kpeter@790
   122
    line = string.replace(line, '\\H o', '&otilde;')
kpeter@790
   123
    line = string.replace(line, '\\H u', '&uuml;')   # &utilde; does not exist
kpeter@790
   124
    line = string.replace(line, '\\\'A', '&Aacute;')
kpeter@790
   125
    line = string.replace(line, '\\"A', '&Auml;')
kpeter@790
   126
    line = string.replace(line, '\\\'E', '&Eacute;')
kpeter@790
   127
    line = string.replace(line, '\\"E', '&Euml;')
kpeter@790
   128
    line = string.replace(line, '\\\'I', '&Iacute;')
kpeter@790
   129
    line = string.replace(line, '\\"I', '&Iuml;')
kpeter@790
   130
    line = string.replace(line, '\\\'O', '&Oacute;')
kpeter@790
   131
    line = string.replace(line, '\\"O', '&Ouml;')
kpeter@790
   132
    line = string.replace(line, '\\\'U', '&Uacute;')
kpeter@790
   133
    line = string.replace(line, '\\"U', '&Uuml;')
kpeter@790
   134
    line = string.replace(line, '\\H O', '&Otilde;')
kpeter@790
   135
    line = string.replace(line, '\\H U', '&Uuml;')   # &Utilde; does not exist
kpeter@790
   136
kpeter@790
   137
    return line
kpeter@790
   138
kpeter@790
   139
#
kpeter@790
   140
# copy characters form a string decoding html expressions (&xyz;)
kpeter@790
   141
#
kpeter@790
   142
def copychars(str, ifrom, count):
kpeter@790
   143
    result = ''
kpeter@790
   144
    i = ifrom
kpeter@790
   145
    c = 0
kpeter@790
   146
    html_spec = False
kpeter@790
   147
    while (i < len(str)) and (c < count):
kpeter@790
   148
        if str[i] == '&':
kpeter@790
   149
            html_spec = True;
kpeter@790
   150
            if i+1 < len(str):
kpeter@790
   151
                result += str[i+1]
kpeter@790
   152
            c += 1
kpeter@790
   153
            i += 2
kpeter@790
   154
        else:
kpeter@790
   155
            if not html_spec:
kpeter@790
   156
                if ((str[i] >= 'A') and (str[i] <= 'Z')) or \
kpeter@790
   157
                   ((str[i] >= 'a') and (str[i] <= 'z')):
kpeter@790
   158
                    result += str[i]
kpeter@790
   159
                    c += 1
kpeter@790
   160
            elif str[i] == ';':
kpeter@790
   161
                html_spec = False;
kpeter@790
   162
            i += 1
kpeter@790
   163
    
kpeter@790
   164
    return result
kpeter@790
   165
kpeter@790
   166
kpeter@790
   167
# 
kpeter@790
   168
# Handle a list of authors (separated by 'and').
kpeter@790
   169
# It gives back an array of the follwing values:
kpeter@790
   170
#  - num: the number of authors,
kpeter@790
   171
#  - list: the list of the author names,
kpeter@790
   172
#  - text: the bibtex text (separated by commas and/or 'and')
kpeter@790
   173
#  - abbrev: abbreviation that can be used for indicate the
kpeter@790
   174
#    bibliography entries
kpeter@790
   175
#
kpeter@790
   176
def bibtexauthor(data):
kpeter@790
   177
    result = {}
kpeter@790
   178
    bibtex = ''
kpeter@790
   179
    result['list'] = author_rex.split(data)
kpeter@790
   180
    result['num'] = len(result['list'])
kpeter@790
   181
    for i, author in enumerate(result['list']):
kpeter@790
   182
        # general transformations
kpeter@790
   183
        author = latexreplacements(removebraces(author.strip()))
kpeter@790
   184
        # transform "Xyz, A. B." to "A. B. Xyz"
kpeter@790
   185
        pos = author.find(',')
kpeter@790
   186
        if pos != -1:
kpeter@790
   187
            author = author[pos+1:].strip() + ' ' + author[:pos].strip()
kpeter@790
   188
        result['list'][i] = author
kpeter@790
   189
        bibtex += author + '#'
kpeter@790
   190
    bibtex = bibtex[:-1]
kpeter@790
   191
    if result['num'] > 1:
kpeter@790
   192
        ix = bibtex.rfind('#')
kpeter@790
   193
        if result['num'] == 2:
kpeter@790
   194
            bibtex = bibtex[:ix] + ' and ' + bibtex[ix+1:]
kpeter@790
   195
        else:
kpeter@790
   196
            bibtex = bibtex[:ix] + ', and ' + bibtex[ix+1:]
kpeter@790
   197
    bibtex = bibtex.replace('#', ', ')
kpeter@790
   198
    result['text'] = bibtex
kpeter@790
   199
    
kpeter@790
   200
    result['abbrev'] = ''
kpeter@790
   201
    for author in result['list']:
kpeter@790
   202
        pos = author.rfind(' ') + 1
kpeter@790
   203
        count = 1
kpeter@790
   204
        if result['num'] == 1:
kpeter@790
   205
            count = 3
kpeter@790
   206
        result['abbrev'] += copychars(author, pos, count)
kpeter@790
   207
kpeter@790
   208
    return result
kpeter@790
   209
kpeter@790
   210
kpeter@790
   211
#
kpeter@790
   212
# data = title string
kpeter@790
   213
# @return the capitalized title (first letter is capitalized), rest are capitalized
kpeter@790
   214
# only if capitalized inside braces
kpeter@790
   215
#
kpeter@790
   216
def capitalizetitle(data):
kpeter@790
   217
    title_list = capitalize_rex.split(data)
kpeter@790
   218
    title = ''
kpeter@790
   219
    count = 0
kpeter@790
   220
    for phrase in title_list:
kpeter@790
   221
         check = string.lstrip(phrase)
kpeter@790
   222
kpeter@790
   223
         # keep phrase's capitalization the same
kpeter@790
   224
         if check.find('{') == 0:
kpeter@790
   225
              title += removebraces(phrase)
kpeter@790
   226
         else:
kpeter@790
   227
         # first word --> capitalize first letter (after spaces)
kpeter@790
   228
              if count == 0:
kpeter@790
   229
                  title += check.capitalize()
kpeter@790
   230
              else:
kpeter@790
   231
                  title += phrase.lower()
kpeter@790
   232
         count = count + 1
kpeter@790
   233
kpeter@790
   234
    return title
kpeter@790
   235
kpeter@790
   236
kpeter@790
   237
#
kpeter@790
   238
# @return the bibtex for the title
kpeter@790
   239
# @param data --> title string
kpeter@790
   240
# braces are removed from title
kpeter@790
   241
#
kpeter@790
   242
def bibtextitle(data, entrytype):
kpeter@790
   243
    if entrytype in ('book', 'inbook'):
kpeter@790
   244
        title = removebraces(data.strip())
kpeter@790
   245
    else:
kpeter@790
   246
        title = removebraces(capitalizetitle(data.strip()))
kpeter@790
   247
    bibtex = title
kpeter@790
   248
    return bibtex
kpeter@790
   249
kpeter@790
   250
kpeter@790
   251
#
kpeter@790
   252
# function to compare entry lists
kpeter@790
   253
#
kpeter@790
   254
def entry_cmp(x, y):
kpeter@790
   255
    return cmp(x[0], y[0])
kpeter@790
   256
kpeter@790
   257
kpeter@790
   258
#
kpeter@790
   259
# print the XML for the transformed "filecont_source"
kpeter@790
   260
#
kpeter@790
   261
def bibtexdecoder(filecont_source):
kpeter@790
   262
    filecont = []
kpeter@790
   263
    file = []
kpeter@790
   264
    
kpeter@790
   265
    # want @<alphanumeric chars><spaces>{<spaces><any chars>,
kpeter@790
   266
    pubtype_rex = re.compile('@(\w*)\s*{\s*(.*),')
kpeter@790
   267
    endtype_rex = re.compile('}\s*$')
kpeter@790
   268
    endtag_rex = re.compile('^\s*}\s*$')
kpeter@790
   269
kpeter@790
   270
    bracefield_rex = re.compile('\s*(\w*)\s*=\s*(.*)')
kpeter@790
   271
    bracedata_rex = re.compile('\s*(\w*)\s*=\s*{(.*)},?')
kpeter@790
   272
kpeter@790
   273
    quotefield_rex = re.compile('\s*(\w*)\s*=\s*(.*)')
kpeter@790
   274
    quotedata_rex = re.compile('\s*(\w*)\s*=\s*"(.*)",?')
kpeter@790
   275
kpeter@790
   276
    for line in filecont_source:
kpeter@790
   277
        line = line[:-1]
kpeter@790
   278
kpeter@790
   279
        # encode character entities
kpeter@790
   280
        line = string.replace(line, '&', '&amp;')
kpeter@790
   281
        line = string.replace(line, '<', '&lt;')
kpeter@790
   282
        line = string.replace(line, '>', '&gt;')
kpeter@790
   283
kpeter@790
   284
        # start entry: publication type (store for later use)
kpeter@790
   285
        if pubtype_rex.match(line):
kpeter@790
   286
        # want @<alphanumeric chars><spaces>{<spaces><any chars>,
kpeter@790
   287
            entrycont = {}
kpeter@790
   288
            entry = []
kpeter@790
   289
            entrytype = pubtype_rex.sub('\g<1>',line)
kpeter@790
   290
            entrytype = string.lower(entrytype)
kpeter@792
   291
            entryid   = pubtype_rex.sub('\g<2>', line)
kpeter@790
   292
kpeter@790
   293
        # end entry if just a }
kpeter@790
   294
        elif endtype_rex.match(line):
kpeter@790
   295
            # generate doxygen code for the entry
kpeter@790
   296
kpeter@790
   297
            # enty type related formattings
kpeter@790
   298
            if entrytype in ('book', 'inbook'):
kpeter@790
   299
                entrycont['title'] = '<em>' + entrycont['title'] + '</em>'
kpeter@790
   300
                if not entrycont.has_key('author'):
kpeter@790
   301
                    entrycont['author'] = entrycont['editor']
kpeter@790
   302
                    entrycont['author']['text'] += ', editors'
kpeter@790
   303
            elif entrytype == 'article':
kpeter@790
   304
                entrycont['journal'] = '<em>' + entrycont['journal'] + '</em>'
kpeter@790
   305
            elif entrytype in ('inproceedings', 'incollection', 'conference'):
kpeter@790
   306
                entrycont['booktitle'] = '<em>' + entrycont['booktitle'] + '</em>'
kpeter@790
   307
            elif entrytype == 'techreport':
kpeter@790
   308
                if not entrycont.has_key('type'):
kpeter@790
   309
                    entrycont['type'] = 'Technical report'
kpeter@790
   310
            elif entrytype == 'mastersthesis':
kpeter@790
   311
                entrycont['type'] = 'Master\'s thesis'
kpeter@790
   312
            elif entrytype == 'phdthesis':
kpeter@790
   313
                entrycont['type'] = 'PhD thesis'
kpeter@790
   314
kpeter@790
   315
            for eline in entrycont:
kpeter@790
   316
                if eline != '':
kpeter@790
   317
                    eline = latexreplacements(eline)
kpeter@790
   318
kpeter@790
   319
            if entrycont.has_key('pages') and (entrycont['pages'] != ''):
kpeter@790
   320
                entrycont['pages'] = string.replace(entrycont['pages'], '--', '-')
kpeter@790
   321
kpeter@790
   322
            if entrycont.has_key('author') and (entrycont['author'] != ''):
kpeter@790
   323
                entry.append(entrycont['author']['text'] + '.')
kpeter@790
   324
            if entrycont.has_key('title') and (entrycont['title'] != ''):
kpeter@790
   325
                entry.append(entrycont['title'] + '.')
kpeter@790
   326
            if entrycont.has_key('journal') and (entrycont['journal'] != ''):
kpeter@790
   327
                entry.append(entrycont['journal'] + ',')
kpeter@790
   328
            if entrycont.has_key('booktitle') and (entrycont['booktitle'] != ''):
kpeter@790
   329
                entry.append('In ' + entrycont['booktitle'] + ',')
kpeter@790
   330
            if entrycont.has_key('type') and (entrycont['type'] != ''):
kpeter@790
   331
                eline = entrycont['type']
kpeter@790
   332
                if entrycont.has_key('number') and (entrycont['number'] != ''):
kpeter@790
   333
                    eline += ' ' + entrycont['number']
kpeter@790
   334
                eline += ','
kpeter@790
   335
                entry.append(eline)
kpeter@790
   336
            if entrycont.has_key('institution') and (entrycont['institution'] != ''):
kpeter@790
   337
                entry.append(entrycont['institution'] + ',')
kpeter@790
   338
            if entrycont.has_key('publisher') and (entrycont['publisher'] != ''):
kpeter@790
   339
                entry.append(entrycont['publisher'] + ',')
kpeter@790
   340
            if entrycont.has_key('school') and (entrycont['school'] != ''):
kpeter@790
   341
                entry.append(entrycont['school'] + ',')
kpeter@790
   342
            if entrycont.has_key('address') and (entrycont['address'] != ''):
kpeter@790
   343
                entry.append(entrycont['address'] + ',')
kpeter@790
   344
            if entrycont.has_key('edition') and (entrycont['edition'] != ''):
kpeter@790
   345
                entry.append(entrycont['edition'] + ' edition,')
kpeter@790
   346
            if entrycont.has_key('howpublished') and (entrycont['howpublished'] != ''):
kpeter@790
   347
                entry.append(entrycont['howpublished'] + ',')
kpeter@790
   348
            if entrycont.has_key('volume') and (entrycont['volume'] != ''):
kpeter@790
   349
                eline = entrycont['volume'];
kpeter@790
   350
                if entrycont.has_key('number') and (entrycont['number'] != ''):
kpeter@790
   351
                    eline += '(' + entrycont['number'] + ')'
kpeter@790
   352
                if entrycont.has_key('pages') and (entrycont['pages'] != ''):
kpeter@790
   353
                    eline += ':' + entrycont['pages']
kpeter@790
   354
                eline += ','
kpeter@790
   355
                entry.append(eline)
kpeter@790
   356
            else:
kpeter@790
   357
                if entrycont.has_key('pages') and (entrycont['pages'] != ''):
kpeter@790
   358
                    entry.append('pages ' + entrycont['pages'] + ',')
kpeter@790
   359
            if entrycont.has_key('year') and (entrycont['year'] != ''):
kpeter@790
   360
                if entrycont.has_key('month') and (entrycont['month'] != ''):
kpeter@790
   361
                    entry.append(entrycont['month'] + ' ' + entrycont['year'] + '.')
kpeter@790
   362
                else:
kpeter@790
   363
                    entry.append(entrycont['year'] + '.')
kpeter@790
   364
            if entrycont.has_key('note') and (entrycont['note'] != ''):
kpeter@790
   365
                entry.append(entrycont['note'] + '.')
kpeter@801
   366
            if entrycont.has_key('url') and (entrycont['url'] != ''):
kpeter@801
   367
                entry.append(entrycont['url'] + '.')
kpeter@790
   368
kpeter@790
   369
            # generate keys for sorting and for the output
kpeter@790
   370
            sortkey = ''
kpeter@790
   371
            bibkey = ''
kpeter@790
   372
            if entrycont.has_key('author'):
kpeter@790
   373
                for author in entrycont['author']['list']:
kpeter@790
   374
                    sortkey += copychars(author, author.rfind(' ')+1, len(author))
kpeter@790
   375
                bibkey = entrycont['author']['abbrev']
kpeter@790
   376
            else:
kpeter@790
   377
                bibkey = 'x'
kpeter@790
   378
            if entrycont.has_key('year'):
kpeter@790
   379
                sortkey += entrycont['year']
kpeter@790
   380
                bibkey += entrycont['year'][-2:]
kpeter@790
   381
            if entrycont.has_key('title'):
kpeter@790
   382
                sortkey += entrycont['title']
kpeter@790
   383
            if entrycont.has_key('key'):
kpeter@790
   384
                sortkey = entrycont['key'] + sortkey
kpeter@790
   385
                bibkey = entrycont['key']
kpeter@790
   386
            entry.insert(0, sortkey)
kpeter@790
   387
            entry.insert(1, bibkey)
kpeter@792
   388
            entry.insert(2, entryid)
kpeter@790
   389
           
kpeter@790
   390
            # add the entry to the file contents
kpeter@790
   391
            filecont.append(entry)
kpeter@790
   392
kpeter@790
   393
        else:
kpeter@790
   394
            # field, publication info
kpeter@790
   395
            field = ''
kpeter@790
   396
            data = ''
kpeter@790
   397
            
kpeter@790
   398
            # field = {data} entries
kpeter@790
   399
            if bracedata_rex.match(line):
kpeter@790
   400
                field = bracefield_rex.sub('\g<1>', line)
kpeter@790
   401
                field = string.lower(field)
kpeter@790
   402
                data =  bracedata_rex.sub('\g<2>', line)
kpeter@790
   403
kpeter@790
   404
            # field = "data" entries
kpeter@790
   405
            elif quotedata_rex.match(line):
kpeter@790
   406
                field = quotefield_rex.sub('\g<1>', line)
kpeter@790
   407
                field = string.lower(field)
kpeter@790
   408
                data =  quotedata_rex.sub('\g<2>', line)
kpeter@790
   409
kpeter@790
   410
            # field = data entries
kpeter@790
   411
            elif data_rex.match(line):
kpeter@790
   412
                field = field_rex.sub('\g<1>', line)
kpeter@790
   413
                field = string.lower(field)
kpeter@790
   414
                data =  data_rex.sub('\g<2>', line)
kpeter@801
   415
kpeter@801
   416
            if field == 'url':
kpeter@801
   417
                data = '\\url{' + data.strip() + '}'
kpeter@790
   418
            
kpeter@790
   419
            if field in ('author', 'editor'):
kpeter@790
   420
                entrycont[field] = bibtexauthor(data)
kpeter@790
   421
                line = ''
kpeter@790
   422
            elif field == 'title':
kpeter@790
   423
                line = bibtextitle(data, entrytype)
kpeter@790
   424
            elif field != '':
kpeter@790
   425
                line = removebraces(transformurls(data.strip()))
kpeter@790
   426
kpeter@790
   427
            if line != '':
kpeter@790
   428
                line = latexreplacements(line)
kpeter@790
   429
                entrycont[field] = line
kpeter@790
   430
kpeter@790
   431
kpeter@790
   432
    # sort entries
kpeter@790
   433
    filecont.sort(entry_cmp)
kpeter@790
   434
    
kpeter@790
   435
    # count the bibtex keys
kpeter@790
   436
    keytable = {}
kpeter@790
   437
    counttable = {}
kpeter@790
   438
    for entry in filecont:
kpeter@790
   439
        bibkey = entry[1]
kpeter@790
   440
        if not keytable.has_key(bibkey):
kpeter@790
   441
            keytable[bibkey] = 1
kpeter@790
   442
        else:
kpeter@790
   443
            keytable[bibkey] += 1
kpeter@790
   444
kpeter@790
   445
    for bibkey in keytable.keys():
kpeter@790
   446
        counttable[bibkey] = 0
kpeter@790
   447
    
kpeter@790
   448
    # generate output
kpeter@790
   449
    for entry in filecont:
kpeter@790
   450
        # generate output key form the bibtex key
kpeter@790
   451
        bibkey = entry[1]
kpeter@792
   452
        entryid = entry[2]
kpeter@790
   453
        if keytable[bibkey] == 1:
kpeter@790
   454
            outkey = bibkey
kpeter@790
   455
        else:
kpeter@790
   456
            outkey = bibkey + chr(97 + counttable[bibkey])
kpeter@790
   457
        counttable[bibkey] += 1
kpeter@790
   458
        
kpeter@790
   459
        # append the entry code to the output
kpeter@792
   460
        file.append('\\section ' + entryid + ' [' + outkey + ']')
kpeter@792
   461
        file.append('<div style="' + divstyle + '">')
kpeter@792
   462
        for line in entry[3:]:
kpeter@790
   463
            file.append(line)
kpeter@792
   464
        file.append('</div>')
kpeter@790
   465
        file.append('')
kpeter@790
   466
kpeter@790
   467
    return file
kpeter@790
   468
kpeter@790
   469
kpeter@790
   470
#
kpeter@790
   471
# return 1 iff abbr is in line but not inside braces or quotes
kpeter@790
   472
# assumes that abbr appears only once on the line (out of braces and quotes)
kpeter@790
   473
#
kpeter@790
   474
def verify_out_of_braces(line, abbr):
kpeter@790
   475
kpeter@790
   476
    phrase_split = delimiter_rex.split(line)
kpeter@790
   477
kpeter@790
   478
    abbr_rex = re.compile( '\\b' + abbr + '\\b', re.I)
kpeter@790
   479
kpeter@790
   480
    open_brace = 0
kpeter@790
   481
    open_quote = 0
kpeter@790
   482
kpeter@790
   483
    for phrase in phrase_split:
kpeter@790
   484
        if phrase == "{":
kpeter@790
   485
            open_brace = open_brace + 1
kpeter@790
   486
        elif phrase == "}":
kpeter@790
   487
            open_brace = open_brace - 1
kpeter@790
   488
        elif phrase == '"':
kpeter@790
   489
            if open_quote == 1:
kpeter@790
   490
                open_quote = 0
kpeter@790
   491
            else:
kpeter@790
   492
                open_quote = 1
kpeter@790
   493
        elif abbr_rex.search(phrase):
kpeter@790
   494
            if open_brace == 0 and open_quote == 0:
kpeter@790
   495
                return 1
kpeter@790
   496
kpeter@790
   497
    return 0
kpeter@790
   498
kpeter@790
   499
kpeter@790
   500
#
kpeter@790
   501
# a line in the form phrase1 # phrase2 # ... # phrasen
kpeter@790
   502
# is returned as phrase1 phrase2 ... phrasen
kpeter@790
   503
# with the correct punctuation
kpeter@790
   504
# Bug: Doesn't always work with multiple abbreviations plugged in
kpeter@790
   505
#
kpeter@790
   506
def concat_line(line):
kpeter@790
   507
    # only look at part after equals
kpeter@790
   508
    field = field_rex.sub('\g<1>',line)
kpeter@790
   509
    rest = field_rex.sub('\g<2>',line)
kpeter@790
   510
kpeter@790
   511
    concat_line = field + ' ='
kpeter@790
   512
kpeter@790
   513
    pound_split = concatsplit_rex.split(rest)
kpeter@790
   514
kpeter@790
   515
    phrase_count = 0
kpeter@790
   516
    length = len(pound_split)
kpeter@790
   517
kpeter@790
   518
    for phrase in pound_split:
kpeter@790
   519
        phrase = phrase.strip()
kpeter@790
   520
        if phrase_count != 0:
kpeter@790
   521
            if phrase.startswith('"') or phrase.startswith('{'):
kpeter@790
   522
                phrase = phrase[1:]
kpeter@790
   523
        elif phrase.startswith('"'):
kpeter@790
   524
            phrase = phrase.replace('"','{',1)
kpeter@790
   525
kpeter@790
   526
        if phrase_count != length-1:
kpeter@790
   527
            if phrase.endswith('"') or phrase.endswith('}'):
kpeter@790
   528
                phrase = phrase[:-1]
kpeter@790
   529
        else:
kpeter@790
   530
            if phrase.endswith('"'):
kpeter@790
   531
                phrase = phrase[:-1]
kpeter@790
   532
                phrase = phrase + "}"
kpeter@790
   533
            elif phrase.endswith('",'):
kpeter@790
   534
                phrase = phrase[:-2]
kpeter@790
   535
                phrase = phrase + "},"
kpeter@790
   536
kpeter@790
   537
        # if phrase did have \#, add the \# back
kpeter@790
   538
        if phrase.endswith('\\'):
kpeter@790
   539
            phrase = phrase + "#"
kpeter@790
   540
        concat_line = concat_line + ' ' + phrase
kpeter@790
   541
kpeter@790
   542
        phrase_count = phrase_count + 1
kpeter@790
   543
kpeter@790
   544
    return concat_line
kpeter@790
   545
kpeter@790
   546
kpeter@790
   547
#
kpeter@790
   548
# substitute abbreviations into filecont
kpeter@790
   549
# @param filecont_source - string of data from file
kpeter@790
   550
#
kpeter@790
   551
def bibtex_replace_abbreviations(filecont_source):
kpeter@790
   552
    filecont = filecont_source.splitlines()
kpeter@790
   553
kpeter@790
   554
    #  These are defined in bibtex, so we'll define them too
kpeter@790
   555
    abbr_list = ['jan','feb','mar','apr','may','jun',
kpeter@790
   556
                 'jul','aug','sep','oct','nov','dec']
kpeter@790
   557
    value_list = ['January','February','March','April',
kpeter@790
   558
                  'May','June','July','August','September',
kpeter@790
   559
                  'October','November','December']
kpeter@790
   560
kpeter@790
   561
    abbr_rex = []
kpeter@790
   562
    total_abbr_count = 0
kpeter@790
   563
kpeter@790
   564
    front = '\\b'
kpeter@790
   565
    back = '(,?)\\b'
kpeter@790
   566
kpeter@790
   567
    for x in abbr_list:
kpeter@790
   568
        abbr_rex.append( re.compile( front + abbr_list[total_abbr_count] + back, re.I ) )
kpeter@790
   569
        total_abbr_count = total_abbr_count + 1
kpeter@790
   570
kpeter@790
   571
kpeter@790
   572
    abbrdef_rex = re.compile('\s*@string\s*{\s*('+ valid_name_chars +'*)\s*=(.*)',
kpeter@790
   573
                             re.I)
kpeter@790
   574
kpeter@790
   575
    comment_rex = re.compile('@comment\s*{',re.I)
kpeter@790
   576
    preamble_rex = re.compile('@preamble\s*{',re.I)
kpeter@790
   577
kpeter@790
   578
    waiting_for_end_string = 0
kpeter@790
   579
    i = 0
kpeter@790
   580
    filecont2 = ''
kpeter@790
   581
kpeter@790
   582
    for line in filecont:
kpeter@790
   583
        if line == ' ' or line == '':
kpeter@790
   584
            continue
kpeter@790
   585
kpeter@790
   586
        if waiting_for_end_string:
kpeter@790
   587
            if re.search('}',line):
kpeter@790
   588
                waiting_for_end_string = 0
kpeter@790
   589
                continue
kpeter@790
   590
kpeter@790
   591
        if abbrdef_rex.search(line):
kpeter@790
   592
            abbr = abbrdef_rex.sub('\g<1>', line)
kpeter@790
   593
kpeter@790
   594
            if abbr_list.count(abbr) == 0:
kpeter@790
   595
                val = abbrdef_rex.sub('\g<2>', line)
kpeter@790
   596
                abbr_list.append(abbr)
kpeter@790
   597
                value_list.append(string.strip(val))
kpeter@790
   598
                abbr_rex.append( re.compile( front + abbr_list[total_abbr_count] + back, re.I ) )
kpeter@790
   599
                total_abbr_count = total_abbr_count + 1
kpeter@790
   600
            waiting_for_end_string = 1
kpeter@790
   601
            continue
kpeter@790
   602
kpeter@790
   603
        if comment_rex.search(line):
kpeter@790
   604
            waiting_for_end_string = 1
kpeter@790
   605
            continue
kpeter@790
   606
kpeter@790
   607
        if preamble_rex.search(line):
kpeter@790
   608
            waiting_for_end_string = 1
kpeter@790
   609
            continue
kpeter@790
   610
kpeter@790
   611
kpeter@790
   612
        # replace subsequent abbreviations with the value
kpeter@790
   613
        abbr_count = 0
kpeter@790
   614
kpeter@790
   615
        for x in abbr_list:
kpeter@790
   616
kpeter@790
   617
            if abbr_rex[abbr_count].search(line):
kpeter@790
   618
                if verify_out_of_braces(line,abbr_list[abbr_count]) == 1:
kpeter@790
   619
                    line = abbr_rex[abbr_count].sub( value_list[abbr_count] + '\g<1>', line)
kpeter@790
   620
                # Check for # concatenations
kpeter@790
   621
                if concatsplit_rex.search(line):
kpeter@790
   622
                    line = concat_line(line)
kpeter@790
   623
            abbr_count = abbr_count + 1
kpeter@790
   624
kpeter@790
   625
kpeter@790
   626
        filecont2 = filecont2 + line + '\n'
kpeter@790
   627
        i = i+1
kpeter@790
   628
kpeter@790
   629
kpeter@790
   630
    # Do one final pass over file
kpeter@790
   631
kpeter@790
   632
    # make sure that didn't end up with {" or }" after the substitution
kpeter@790
   633
    filecont2 = filecont2.replace('{"','{{')
kpeter@790
   634
    filecont2 = filecont2.replace('"}','}}')
kpeter@790
   635
kpeter@790
   636
    afterquotevalue_rex = re.compile('"\s*,\s*')
kpeter@790
   637
    afterbrace_rex = re.compile('"\s*}')
kpeter@790
   638
    afterbracevalue_rex = re.compile('(=\s*{[^=]*)},\s*')
kpeter@790
   639
kpeter@790
   640
    # add new lines to data that changed because of abbreviation substitutions
kpeter@790
   641
    filecont2 = afterquotevalue_rex.sub('",\n', filecont2)
kpeter@790
   642
    filecont2 = afterbrace_rex.sub('"\n}', filecont2)
kpeter@790
   643
    filecont2 = afterbracevalue_rex.sub('\g<1>},\n', filecont2)
kpeter@790
   644
kpeter@790
   645
    return filecont2
kpeter@790
   646
kpeter@790
   647
#
kpeter@790
   648
# convert @type( ... ) to @type{ ... }
kpeter@790
   649
#
kpeter@790
   650
def no_outer_parens(filecont):
kpeter@790
   651
kpeter@790
   652
    # do checking for open parens
kpeter@790
   653
    # will convert to braces
kpeter@790
   654
    paren_split = re.split('([(){}])',filecont)
kpeter@790
   655
kpeter@790
   656
    open_paren_count = 0
kpeter@790
   657
    open_type = 0
kpeter@790
   658
    look_next = 0
kpeter@790
   659
kpeter@790
   660
    # rebuild filecont
kpeter@790
   661
    filecont = ''
kpeter@790
   662
kpeter@790
   663
    at_rex = re.compile('@\w*')
kpeter@790
   664
kpeter@790
   665
    for phrase in paren_split:
kpeter@790
   666
        if look_next == 1:
kpeter@790
   667
            if phrase == '(':
kpeter@790
   668
                phrase = '{'
kpeter@790
   669
                open_paren_count = open_paren_count + 1
kpeter@790
   670
            else:
kpeter@790
   671
                open_type = 0
kpeter@790
   672
            look_next = 0
kpeter@790
   673
kpeter@790
   674
        if phrase == '(':
kpeter@790
   675
            open_paren_count = open_paren_count + 1
kpeter@790
   676
kpeter@790
   677
        elif phrase == ')':
kpeter@790
   678
            open_paren_count = open_paren_count - 1
kpeter@790
   679
            if open_type == 1 and open_paren_count == 0:
kpeter@790
   680
                phrase = '}'
kpeter@790
   681
                open_type = 0
kpeter@790
   682
kpeter@790
   683
        elif at_rex.search( phrase ):
kpeter@790
   684
            open_type = 1
kpeter@790
   685
            look_next = 1
kpeter@790
   686
kpeter@790
   687
        filecont = filecont + phrase
kpeter@790
   688
kpeter@790
   689
    return filecont
kpeter@790
   690
kpeter@790
   691
kpeter@790
   692
#
kpeter@790
   693
# make all whitespace into just one space
kpeter@790
   694
# format the bibtex file into a usable form.
kpeter@790
   695
#
kpeter@790
   696
def bibtexwasher(filecont_source):
kpeter@790
   697
kpeter@790
   698
    space_rex = re.compile('\s+')
kpeter@790
   699
    comment_rex = re.compile('\s*%')
kpeter@790
   700
kpeter@790
   701
    filecont = []
kpeter@790
   702
kpeter@790
   703
    # remove trailing and excessive whitespace
kpeter@790
   704
    # ignore comments
kpeter@790
   705
    for line in filecont_source:
kpeter@790
   706
        line = string.strip(line)
kpeter@790
   707
        line = space_rex.sub(' ', line)
kpeter@790
   708
        # ignore comments
kpeter@790
   709
        if not comment_rex.match(line) and line != '':
kpeter@790
   710
            filecont.append(' '+ line)
kpeter@790
   711
kpeter@790
   712
    filecont = string.join(filecont, '')
kpeter@790
   713
kpeter@790
   714
    # the file is in one long string
kpeter@790
   715
kpeter@790
   716
    filecont = no_outer_parens(filecont)
kpeter@790
   717
kpeter@790
   718
    #
kpeter@790
   719
    # split lines according to preferred syntax scheme
kpeter@790
   720
    #
kpeter@790
   721
    filecont = re.sub('(=\s*{[^=]*)},', '\g<1>},\n', filecont)
kpeter@790
   722
kpeter@790
   723
    # add new lines after commas that are after values
kpeter@790
   724
    filecont = re.sub('"\s*,', '",\n', filecont)
kpeter@790
   725
    filecont = re.sub('=\s*([\w\d]+)\s*,', '= \g<1>,\n', filecont)
kpeter@790
   726
    filecont = re.sub('(@\w*)\s*({(\s*)[^,\s]*)\s*,',
kpeter@790
   727
                          '\n\n\g<1>\g<2>,\n', filecont)
kpeter@790
   728
kpeter@790
   729
    # add new lines after }
kpeter@790
   730
    filecont = re.sub('"\s*}','"\n}\n', filecont)
kpeter@790
   731
    filecont = re.sub('}\s*,','},\n', filecont)
kpeter@790
   732
kpeter@790
   733
kpeter@790
   734
    filecont = re.sub('@(\w*)', '\n@\g<1>', filecont)
kpeter@790
   735
kpeter@790
   736
    # character encoding, reserved latex characters
kpeter@790
   737
    filecont = re.sub('{\\\&}', '&', filecont)
kpeter@790
   738
    filecont = re.sub('\\\&', '&', filecont)
kpeter@790
   739
kpeter@790
   740
    # do checking for open braces to get format correct
kpeter@790
   741
    open_brace_count = 0
kpeter@790
   742
    brace_split = re.split('([{}])',filecont)
kpeter@790
   743
kpeter@790
   744
    # rebuild filecont
kpeter@790
   745
    filecont = ''
kpeter@790
   746
kpeter@790
   747
    for phrase in brace_split:
kpeter@790
   748
        if phrase == '{':
kpeter@790
   749
            open_brace_count = open_brace_count + 1
kpeter@790
   750
        elif phrase == '}':
kpeter@790
   751
            open_brace_count = open_brace_count - 1
kpeter@790
   752
            if open_brace_count == 0:
kpeter@790
   753
                filecont = filecont + '\n'
kpeter@790
   754
kpeter@790
   755
        filecont = filecont + phrase
kpeter@790
   756
kpeter@790
   757
    filecont2 = bibtex_replace_abbreviations(filecont)
kpeter@790
   758
kpeter@790
   759
    # gather
kpeter@790
   760
    filecont = filecont2.splitlines()
kpeter@790
   761
    i=0
kpeter@790
   762
    j=0         # count the number of blank lines
kpeter@790
   763
    for line in filecont:
kpeter@790
   764
        # ignore blank lines
kpeter@790
   765
        if line == '' or line == ' ':
kpeter@790
   766
            j = j+1
kpeter@790
   767
            continue
kpeter@790
   768
        filecont[i] = line + '\n'
kpeter@790
   769
        i = i+1
kpeter@790
   770
kpeter@790
   771
    # get rid of the extra stuff at the end of the array
kpeter@790
   772
    # (The extra stuff are duplicates that are in the array because
kpeter@790
   773
    # blank lines were removed.)
kpeter@790
   774
    length = len( filecont)
kpeter@790
   775
    filecont[length-j:length] = []
kpeter@790
   776
kpeter@790
   777
    return filecont
kpeter@790
   778
kpeter@790
   779
kpeter@790
   780
def filehandler(filepath):
kpeter@790
   781
    try:
kpeter@790
   782
        fd = open(filepath, 'r')
kpeter@790
   783
        filecont_source = fd.readlines()
kpeter@790
   784
        fd.close()
kpeter@790
   785
    except:
kpeter@790
   786
        print 'Could not open file:', filepath
kpeter@790
   787
    washeddata = bibtexwasher(filecont_source)
kpeter@790
   788
    outdata = bibtexdecoder(washeddata)
kpeter@790
   789
    print '/**'
kpeter@790
   790
    print '\page references References'
kpeter@790
   791
    print
kpeter@790
   792
    for line in outdata:
kpeter@790
   793
        print line
kpeter@790
   794
    print '*/'
kpeter@790
   795
kpeter@790
   796
kpeter@790
   797
# main program
kpeter@790
   798
kpeter@790
   799
def main():
kpeter@790
   800
    import sys
kpeter@790
   801
    if sys.argv[1:]:
kpeter@790
   802
        filepath = sys.argv[1]
kpeter@790
   803
    else:
kpeter@790
   804
        print "No input file"
kpeter@790
   805
        sys.exit()
kpeter@790
   806
    filehandler(filepath)
kpeter@790
   807
kpeter@790
   808
if __name__ == "__main__": main()
kpeter@790
   809
kpeter@790
   810
kpeter@790
   811
# end python script