Custom autokey generation and bibtex @string macro hack

"Rajiv Narayan" <[email protected]> Mon, 13 Aug 2007 16:56:53 -0400
Newsgroups gmane.comp.gnome.apps.pybliographer
Message-ID <[email protected]>
I find it useful to maintain abbreviated and full journal names in two
separate files (abbrevshort and abbrevlong) and use the appropriate
one in my LaTeX document depending on the format required.

For example:

thesis.bib
@Article{abc1990-3,
  Author         = {abc},
  Title          = {foo},
  Journal        = jfoo,
  Volume         = {1},
  Number         = {2},
  Pages          = {3-10},
  abstract       = {},
  keywords       = {},
  year           = 1990
}

abbrevshort.bib
@String{jfoo = "J Foo"}

abbrevfull.bib
@String{jfoo = "Journal of Foo"}

The to use the required expansion within the LaTeX document:

\bibliography{./abbrevshort,./thesis}
OR
\bibliography{./abbrevfull,./thesis}


However the journal names show up as <undefined> within Pybliographer
unless the bibtex macros are defined. I came up with a small hack to
fix this by updating the bibtex macros on startup. I thought others
might find it useful.

To use, save the python script as .pybrc.py and create a string
definition file called .pybmacros.bib as decribed in the script.

I've also included a routine to override the default key generation
routine to create keys in the format authorYYYY-firstpage.

-Rajiv

Rajiv Narayan
Boston University
Boston, MA

-----------------------------------------start----------------------------------------
#Pybliographer config file
#save as ~/.pybrc.py
#Add custom BibTeX @String{} Macros to expand journal names correctly
#Useful when using separate .bib files for the @String definitions,
#since Pybliographer can't deal with multiple .bib files yet.

#Save the BibTeX macros in ~/.pybmacros.bib
#Format: @string{abbrev = "expansion"}
#Example: @string{jneurosci = "Journal of neuroscience"}
#Note the single space on either side of the = sign

from string import *

import os, re

from Pyblio import Key, Autoload, recode, Config

#multiple string replace helper function
def multiple_replace(dict, text):

    """ Replace in 'text' all occurences of any key in the given
    dictionary by its corresponding value.  Returns the new tring."""

    # Create a regular expression  from the dictionary keys
    regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))

    # For each match, look-up corresponding value in dictionary
    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)

macros = Config.get('bibtex/macros').data

dictfile = os.path.expanduser('~/.pybmacros.bib')

replist = {'@string{':'','}':'','"':''}

if os.path.exists(dictfile):

    dict = open (dictfile, 'r')

    while 1:
        line = dict.readline ()
        if line == '': break

        line = string.strip (line)
        line=multiple_replace(replist,line)

        field = split(line,' = ')
        macros[field[0]]=(field[1],0)

    dict.close()

#Custom auto-key generation
# authorYYYY-startpage
def generate_key_ayp (entry, table):

    if   entry.has_key ('author'): aut = entry ['author']
    elif entry.has_key ('editor'): aut = entry ['editor']
    else:                          aut = ()

    if len (aut) == 0:
        global __entry
        key = 'entry-%d' % __entry
        __entry = __entry + 1
    else:
        honorific, first, last, lineage = aut [0].format ()
        key = lower(join (split (last, ' '), ''))

        if entry.has_key ('date'):
            year = entry ['date'].year

            if year: key = key + str (year)

        if entry.has_key('pages'):
            pages = entry ['pages'].text
            pages = split(pages,'-')[0]
            if pages: key = key + '-' + pages


    base = _flat (key)
    key  = Key.Key (table, base)

    if table.has_key (key):
        suff = ord ('a')

        while table.has_key (key):
            suff = suff + 1

            if suff > ord ('z'):
                suff = ord ('a')
                base = base + 'a'

                key  = Key.Key (table, base + chr (suff))

    return Key.Key (table, key)

#Create a new format accessible via Settings>Prefs>Base>Keyformat
#Autoload.register ('key', 'authorYYYY-startpg', generate_key_ayp)

#Override the default format
Autoload.register ('key', 'Default', generate_key_ayp)
-----------------------------------------stop----------------------------------------

-------------------------------------------------------------------------
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems?  Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >>  http://get.splunk.com/