Logo Search packages:      
Sourcecode: zope-cmfbibliographyat version File versions  Download package

bibtex.py

############################################################################
#                                                                          #
#             copyright (c) 2003 ITB, Humboldt-University Berlin           #
#             written by: Raphael Ritz, r.ritz@biologie.hu-berlin.de       #
#                                                                          #
############################################################################

"""BibtexRenderer class"""

# Python stuff
import re
from urllib import unquote

# Zope stuff
from Globals import InitializeClass
from App.Dialogs import MessageDialog

# CMF stuff
from Products.CMFCore.utils import getToolByName

# Bibliography stuff
from Products.CMFBibliographyAT.tool.renderers.base \
     import IBibliographyRenderer, BibliographyRenderer

_entity_mapping = {'—':'---',
                   '–':'--',
                   }

00029 class BibtexRenderer(BibliographyRenderer):
    """
    specific parser to process input in BiBTeX-format
    """

    __implements__ = (IBibliographyRenderer ,)

    meta_type = "Bibtex Renderer"

    format = {'name':'BibTeX',
              'extension':'bib'}

00041     def __init__(self,
                 id = 'bibtex',
                 title = "BibTeX renderer"):
        """
        initializes only id and title
        """
        self.id = id
        self.title = title

00050     def render(self, object):
        """
        renders a bibliography object in BiBTex format
        """
        bib_tool = getToolByName(object, 'portal_bibliography')
        ref_types = bib_tool.getReferenceTypes()
        if object.portal_type in ref_types:
            return self.renderEntry(object)
        if object.isPrincipiaFolderish:
            entries = object.contentValues(ref_types)
            rendered = [self.renderEntry(entry) \
                        for entry in entries]
            return ''.join(rendered)
        return ''

00065     def renderEntry(self, entry):
        """
        renders a BibliographyEntry object in BiBTex format
        """
        bib_key = self._validKey(entry)
        bibtex = "\n@%s{%s," % \
                 (entry.meta_type[:-9], bib_key)
        # [:-9] assumes we have a "...Reference" type 
        bibtex += "\n  author = {%s}," % \
                  entry.Authors(sep=' and ',
                                lastsep=' and ',
                                format="%F %M %L",
                                abbrev=0,
                                lastnamefirst=0)
        aURLs = self.AuthorURLs(entry)
        if aURLs.find('http') > -1:
            bibtex += "\n  authorURLs = {%s}," % aURLs
        bibtex += "\n  title = {%s}," % entry.Title()
        bibtex += "\n  year = {%s}," % entry.getPublication_year()
        url = entry.getURL()
        if url: bibtex += "\n  URL = {%s}," % url
        bibtex += "\n  abstract = {%s}," % entry.getAbstract()

        if hasattr(entry, 'source_fields') and entry.source_fields:
            source_fields = entry.source_fields
            field_values = [entry.getFieldValue(name) \
                            for name in source_fields]
            for key, value in zip(source_fields, field_values):
                if value:
                    bibtex += "\n  %s = {%s}," % (key, value)

        kws = ', '.join(entry.Subject())
        if kws:
            bibtex += "\n  keywords = {%s}," % kws
        note = entry.getNote()
        if note:
            bibtex += "\n  note = {%s}" % note
        else:
            bibtex = bibtex[:-1] # remove the trialing comma
        bibtex += "\n}\n"
        bibtex = self._normalize(bibtex)
##         bibtex = self._escapeSpecialCharacters(bibtex)
        return bibtex

    def _validKey(self, entry):
        """
        uses the Zope object id but
        removes characters not allowed in BibTeX keys
        """
        raw_id = entry.getId()
        return re.sub('[^a-zA-Z0-9]', '', raw_id)

    def AuthorURLs(self, entry):
        """a string with all the known author's URLs;
        helper method for bibtex output"""
        a_list = entry.getAuthorList()
        a_URLs = ''
        for a in a_list:
            url = a.get('homepage', ' ')
            a_URLs += "%s and " % url
        return a_URLs[:-5]

    def _normalize(self, text):
        text = self._resolveEntities(text)
        text = self._escapeSpecialCharacters(text)
        return text

    def _resolveEntities(self, text):
        for entity in _entity_mapping.keys():
            text = text.replace(entity, _entity_mapping[entity])
        return text

    def _escapeSpecialCharacters(self, text):
        """
        latex escaping some (not all) special characters
        """
        escape = ['~', '#', '&', '%', '_']
        for c in escape:
            text = text.replace(c, '\\' + c )
        return text

            
# Class instanciation
InitializeClass(BibtexRenderer)

   
def manage_addBibtexRenderer(self, REQUEST=None):
    """ """
    try:
        self._setObject('bibtex', BibtexRenderer())
    except:
        return MessageDialog(
            title='Bibliography tool warning message',
            message='The renderer you attempted to add already exists.',
            action='manage_main')
    return self.manage_main(self, REQUEST)

Generated by  Doxygen 1.6.0   Back to index