Changeset 854

Show
Ignore:
Timestamp:
09/18/05 06:58:08 (3 years ago)
Author:
rkern
Message:

Equation support for HTML.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • nbdoc/trunk/notabene/docbook.py

    r853 r854  
    88import tempfile 
    99import subprocess 
     10import shutil 
     11import warnings 
    1012 
    1113from lxml import etree as ET 
     
    1315from notabene.formatter import Formatter 
    1416from PyFontify import fontify 
     17 
     18def relpath(target, base=os.curdir): 
     19    """ 
     20    Return a relative path to the target from either the current dir or an optional base dir. 
     21    Base can be a directory specified either as absolute or relative to current dir. 
     22 
     23    This function is by Richard Barran. 
     24    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302594 
     25    """ 
     26 
     27    if not os.path.exists(target): 
     28        raise OSError, 'Target does not exist: '+target 
     29 
     30    if not os.path.isdir(base): 
     31        raise OSError, 'Base is not a directory or does not exist: '+base 
     32 
     33    base_list = (os.path.abspath(base)).split(os.sep) 
     34    target_list = (os.path.abspath(target)).split(os.sep) 
     35 
     36    # On the windows platform the target may be on a completely different drive from the base. 
     37    if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]: 
     38        raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper() 
     39 
     40    # Starting from the filepath root, work out how much of the filepath is 
     41    # shared by base and target. 
     42    for i in range(min(len(base_list), len(target_list))): 
     43        if base_list[i] <> target_list[i]: break 
     44    else: 
     45        # If we broke out of the loop, i is pointing to the first differing path elements. 
     46        # If we didn't break out of the loop, i is pointing to identical path elements. 
     47        # Increment i so that in all cases it points to the first differing path elements. 
     48        i+=1 
     49 
     50    rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:] 
     51    return os.path.join(*rel_list) 
     52 
     53 
     54 
    1555 
    1656def dbify(text): 
     
    120160        verbatim = equ.get('verb', None) 
    121161        if verbatim != '1': 
    122             tex = r'\begin{equation}%s\end{equation}' % tex 
     162            tex = r'$$%s$$' % tex 
    123163        mo = ET.SubElement(dbeq, 'mediaobject') 
    124164        to = ET.SubElement(mo, 'textobject') 
     
    219259         
    220260    @classmethod 
    221     def prep_fo(cls, tree): 
     261    def equation_images(cls, tree, name): 
     262        can_tex = False 
     263        try: 
     264            from matplotlib import texmanager 
     265        except ImportError: 
     266            warnings.warn('matplotlib not available') 
     267        try: 
     268            texmgr = texmanager.TexManager() 
     269            texmgr.get_dvipng_version() 
     270            can_tex = True 
     271        except RuntimeError: 
     272            warnings.warn('dvipng not up-to-date') 
     273        if can_tex == False: 
     274            warnings.warn('Cannot convert equations to images') 
     275            return 
     276        else: 
     277            if name is None: 
     278                raise ValueError("must provide a name") 
     279            eqdir = name + '_files' 
     280            if not os.path.isdir(eqdir): 
     281                os.mkdir(eqdir) 
     282            equations = tree.xpath('//informalequation') 
     283            equations.extend(tree.xpath('//inlineequation')) 
     284            for eq in equations: 
     285                mo = eq.find('mediaobject') 
     286                if mo is None: 
     287                    mo = eq.find('inlinemediaobject') 
     288                phrase = mo.find('textobject/phrase') 
     289                latex = phrase.text 
     290                pngfile = texmgr.make_png(latex, dpi=120) 
     291                pngbase = os.path.basename(pngfile) 
     292                newpng = os.path.join(eqdir, pngbase) 
     293                shutil.copyfile(pngfile, newpng) 
     294                io = ET.SubElement(mo, 'imageobject') 
     295                data = ET.SubElement(io, 'imagedata',  
     296                    fileref=relpath(newpng, os.path.split(os.path.abspath(name))[0]), 
     297                    format='PNG') 
     298     
     299    @classmethod 
     300    def prep_fo(cls, tree, name=None): 
    222301        pass 
    223302 
    224303    @classmethod 
    225     def prep_html(cls, tree): 
    226         pass 
     304    def prep_html(cls, tree, name=None): 
     305        cls.equation_images(tree, name) 
    227306     
    228307    @classmethod 
    229     def prep_latex(cls, tree): 
     308    def prep_latex(cls, tree, name=None): 
    230309        listings = tree.xpath('//programlisting')  
    231310        for listing in listings:   
     
    236315 
    237316    @classmethod 
    238     def to_formatted(cls, dbxml, kind='html', style=None): 
     317    def to_formatted(cls, dbxml, kind='html', name=None, style=None): 
    239318        """Convert a DocBook document to the final format. 
    240319 
     
    247326        if ET.iselement(dbxml): 
    248327            dbxml = ET.ElementTree(dbxml) 
    249         getattr(cls, 'prep_%s' % kind)(dbxml
     328        getattr(cls, 'prep_%s' % kind)(dbxml, name
    250329        newtree = xslt.apply(dbxml) 
    251330        return xslt.tostring(newtree) 
     
    283362            toPDF = True 
    284363             
    285         doc = cls.to_formatted(dbxml, kind=format).encode('utf-8') 
     364        doc = cls.to_formatted(dbxml, kind=format, name=base).encode('utf-8') 
    286365 
    287366        if toPDF: 
  • nbdoc/trunk/notabene/notebook.py

    r853 r854  
    33import os 
    44import warnings 
     5import copy 
    56 
    67from lxml import etree as ET 
     
    910from notabene import validate 
    1011from notabene.xmlutils import nsmap, rdf, dc, xlink 
     12 
     13def element_copy(element): 
     14    return ET.XML(ET.tostring(element, encoding='utf-8')) 
    1115 
    1216class SubelemWrapper(object): 
     
    478482        parent = child2parent[link] 
    479483        path, frag = spliturl(basedir, link.get(xlink.href)) 
    480         print path, frag 
    481484        nb = Notebook.from_file(path) 
    482485        sheet = nb.xpath.evaluate('/notebook/sheet[@id="%s"]' % frag) 
     
    489492        dbxml = dbf.transform_sheet(sheet, nodetype=link.tag) 
    490493        idx = parent.index(link) 
    491         parent[idx] = dbxml 
     494        del parent[idx] 
     495        parent.insert(idx, dbxml) 
    492496    return book 
    493497 
  • nbdoc/trunk/notabene/styles.py

    r845 r854  
    127127    padding: 0; 
    128128} 
     129 
     130div.mediaobject { 
     131    text-align: center; 
     132    margin: 1em; 
     133} 
     134 
     135span.inlinemediaobject > img { 
     136    vertical-align: middle; 
     137} 
     138 
    129139""" 
    130140 
     
    149159        fvopt = ET.SubElement(sheet, xsl.template, name="latex.fancyvrb.options") 
    150160        fvopt.text = r",commandchars=\\\{\}" 
     161 
     162        # turn off fancyhdr 
     163        fancyhdr = ET.SubElement(sheet, xsl.param, name='latex.use.fancyhdr') 
     164        fancyhdr.text = '0' 
    151165 
    152166        docclass = ET.SubElement(sheet, xsl.param, 
     
    198212        comment = ET.SubElement(css_style, xsl.comment) 
    199213        comment.text = self.html_css() 
     214        ET.SubElement(sheet, xsl.param, name="section.autolabel", select="1") 
     215        ET.SubElement(sheet, xsl.param,  
     216            name="section.label.includes.component.label", select="1") 
    200217 
    201218        return ET.ElementTree(sheet) 
  • nbdoc/trunk/scipy_tutorial/chapter02.pybk

    r845 r854  
    3434>>> scipy.sqrt(-1) </para> 
    3535</section> 
    36  
     36<section> 
     37<title>Alter numeric</title> 
     38<para>With the command scipy.alter_numeric() you can now use index and mask arrays inside brackets and the coercion rules of Numeric will be changed so that Python scalars will not be used to determine the type of the output of an expression. 
     39</para> 
     40</section> 
    3741<section> 
    3842<title>scipy_base routines</title>