B
    ]t\                @   sl  d Z ddlZddlmZ ddlZddlZddlZddlZddlZ	ddl
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ e  ddlmZmZm Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z' ddl(m)Z)m*Z*m+Z+ dd	l,m-Z-m.Z.m/Z/ dd
l0m1Z1m2Z2m3Z3m4Z4m5Z5 dddZ6e7de8Z9G dd de:Z;G dd de;Z<G dd de<Z=G dd de;Z>G dd de;Z?G dd de;Z@G dd de;ZAG dd de;ZBG dd  d e:ZCG d!d" d"eCZDG d#d$ d$eDZEG d%d& d&eDZFG d'd( d(eFZGG d)d* d*eGZHG d+d, d,eGZIG d-d. d.eFZJG d/d0 d0eJZKG d1d2 d2eCZLd3ZMd4eM ZNd5ZOG d6d7 d7e:ZPG d8d9 d9ePZQG d:d; d;ePZRG d<d= d=ePZSG d>d? d?ePZTG d@dA dAePZUeUeUeTeQeQeQeQeQeQeQeReReReReReReReUeUdBZVdCdD ZWG dEdF dFeXZYG dGdH dHe:ZZG dIdJ dJeZZ[G dKdL dLe[Z\G dMdN dNe[Z]G dOdP dPeZZ^G dQdR dRe^Z_G dSdT dTe[Z`G dUdV dVe`ZaG dWdX dXe`ZbG dYdZ dZe[ZcG d[d\ d\ecZdG d]d^ d^ecZeG d_d` d`eZZfG dadb dbe:Zgegdcd4dddcdegdcd4dedcdegdcd4dfdcdegdcdcdd4ddegdcdcdd4deegdcdcdd4dfegdcdcddcdegdcd4dddgdddheg_hG didj djefZiG dkdl dlefZjG dmdn dnefZkG dodp dpefZlG dqdr drefZmG dsdt dtefZnG dudv dvefZoG dwdx dxeaZpG dydz dzeaZqG d{d| d|eZZrG d}d~ d~eaZsG dd deaZtG dd deaZuG dd de:Zvev Zwdd ZxG dd de:ZyG dd de:ZzdddZ{dS )aK  
:mod:`~matplotlib.mathtext` is a module for parsing a subset of the
TeX math syntax and drawing them to a matplotlib backend.

For a tutorial of its usage see :doc:`/tutorials/text/mathtext`.  This
document is primarily concerned with implementation details.

The module uses pyparsing_ to parse the TeX expression.

.. _pyparsing: http://pyparsing.wikispaces.com/

The Bakoma distribution of the TeX Computer Modern fonts, and STIX
fonts are supported.  There is experimental support for using
arbitrary fonts, but results may vary without proper tweaking and
metrics for those fonts.
    N)StringIO)CombineEmpty
FollowedByForwardGroupLiteraloneOf	OneOrMoreOptionalParseBaseExceptionParseFatalExceptionParserElementQuotedStringRegex	StringEndSuppress
ZeroOrMore)_pngcbookcolorsget_data_pathrcParams)AFM)get_realpath_and_stat)FT2ImageKERNING_DEFAULTLOAD_NO_HINTING)findfontFontPropertiesget_font)latex_to_bakomalatex_to_standardtex2unilatex_to_cmexstix_virtual_fontsTc             C   sl   |st | S | dkrdS yt | S  tk
r4   Y nX yt| d S  tk
rf   td| Y nX dS )a'  get_unicode_index(symbol, [bool]) -> integer

Return the integer index (from the Unicode table) of symbol.  *symbol*
can be a single unicode character, a TeX command (i.e. r'\pi'), or a
Type1 symbol name (i.e. 'phi').
If math is False, the current symbol should be treated as a non-math symbol.
-i"  \z9'{}' is not a valid Unicode character or TeX/Type1 symbolN)ord	TypeErrorr#   stripKeyError
ValueErrorformat)symbolmath r0   2lib/python3.7/site-packages/matplotlib/mathtext.pyget_unicode_index2   s    	r2   z3.0c               @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )MathtextBackenda  
    The base class for the mathtext backend-specific code.  The
    purpose of :class:`MathtextBackend` subclasses is to interface
    between mathtext and a specific matplotlib graphics backend.

    Subclasses need to override the following:

      - :meth:`render_glyph`
      - :meth:`render_rect_filled`
      - :meth:`get_results`

    And optionally, if you need to use a FreeType hinting style:

      - :meth:`get_hinting_type`
    c             C   s   d| _ d| _d| _d S )Nr   )widthheightdepth)selfr0   r0   r1   __init__c   s    zMathtextBackend.__init__c             C   s   || _ || _|| _dS )zDimension the drawing canvasN)r4   r5   r6   )r7   whdr0   r0   r1   set_canvas_sizeh   s    zMathtextBackend.set_canvas_sizec             C   s
   t  dS )z_
        Draw a glyph described by *info* to the reference point (*ox*,
        *oy*).
        N)NotImplementedError)r7   oxoyinfor0   r0   r1   render_glyphn   s    zMathtextBackend.render_glyphc             C   s
   t  dS )zR
        Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*).
        N)r=   )r7   x1y1x2y2r0   r0   r1   render_rect_filledu   s    z"MathtextBackend.render_rect_filledc             C   s
   t  dS )zp
        Return a backend-specific tuple to return to the backend after
        all processing is done.
        N)r=   )r7   boxr0   r0   r1   get_results{   s    zMathtextBackend.get_resultsc             C   s   t S )z\
        Get the FreeType hinting type to use with this particular
        backend.
        )r   )r7   r0   r0   r1   get_hinting_type   s    z MathtextBackend.get_hinting_typeN)
__name__
__module____qualname____doc__r8   r<   rA   rF   rH   rI   r0   r0   r0   r1   r3   S   s   r3   c               @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )MathtextBackendAggz
    Render glyphs and rectangles to an FTImage buffer, which is later
    transferred to the Agg image by the Agg backend.
    c             C   s4   d| _ d| _d | _d| _ddddg| _t|  d S )Nr   bbox)r>   r?   imagemoderO   r3   r8   )r7   r0   r0   r1   r8      s    zMathtextBackendAgg.__init__c             C   sB   t | jd |t | jd |t| jd |t| jd |g| _d S )Nr            )minrO   max)r7   rB   rC   rD   rE   r0   r0   r1   _update_bbox   s    zMathtextBackendAgg._update_bboxc             C   s@   t | ||| | jdkr<tt|t|t|d | _d S )NrO   r   )r3   r<   rQ   r   npceilrV   rP   )r7   r9   r:   r;   r0   r0   r1   r<      s    
z"MathtextBackendAgg.set_canvas_sizec             C   sf   | j dkr<| ||jj ||jj ||jj ||jj  n&|jj| j	|||jj
 |jtd d d S )NrO   ztext.antialiased)Zantialiased)rQ   rW   metricsxminymaxxmaxyminfontZdraw_glyph_to_bitmaprP   icebergglyphr   )r7   r>   r?   r@   r0   r0   r1   rA      s    


zMathtextBackendAgg.render_glyphc             C   s   | j dkr| |||| nhtt|| d d}|dkr\|| d }t||d d  }nt|}| jt||t|||  d S )NrO   rR   r   g       @)rQ   rW   rV   intrP   Zdraw_rect_filledrX   rY   )r7   rB   rC   rD   rE   r5   centeryr0   r0   r1   rF      s    
z%MathtextBackendAgg.render_rect_filledc             C   s   d| _ |j}|j}tdd| | j}|d d |d d |d d |d d g}d| _ | |d |d  |d |d  | |d |d  |  t|d  |d  | | j| j| j| j| j | j| j	|f}d | _	|S )NrO   r   rR   rS   rT   render)
rQ   r5   r6   shiprO   r<   r>   r?   r4   rP   )r7   rG   used_charactersZorig_heightZ
orig_depthrO   resultr0   r0   r1   rH      s*    ,
zMathtextBackendAgg.get_resultsc             C   s   ddl m} | S )Nr   )backend_agg)matplotlib.backendsri   Zget_hinting_flag)r7   ri   r0   r0   r1   rI      s    z#MathtextBackendAgg.get_hinting_typeN)rJ   rK   rL   rM   r8   rW   r<   rA   rF   rH   rI   r0   r0   r0   r1   rN      s   rN   c               @   s   e Zd Zdd ZdS )MathtextBackendBitmapc       
      C   s$   t | ||\}}}}}}}	||fS )N)rN   rH   )
r7   rG   rg   r>   r?   r4   r5   r6   rP   Z
charactersr0   r0   r1   rH      s    z!MathtextBackendBitmap.get_resultsN)rJ   rK   rL   rH   r0   r0   r0   r1   rk      s   rk   c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )MathtextBackendPszX
    Store information to write a mathtext rendering to the PostScript
    backend.
    c             C   s   t  | _d | _d S )N)r   pswriterlastfont)r7   r0   r0   r1   r8      s    zMathtextBackendPs.__init__c             C   sj   | j | |j }|j}|j}|j}||f| jkrPdt  }||f| _| j| dt  }| j| d S )Nz=/%(postscript_name)s findfont
%(fontsize)s scalefont
setfont
z1%(ox)f %(oy)f moveto
/%(symbol_name)s glyphshow

)	r5   offsetpostscript_namefontsizesymbol_namern   localsrm   write)r7   r>   r?   r@   rp   rq   rr   psr0   r0   r1   rA      s    


zMathtextBackendPs.render_glyphc             C   s.   d|| j | || || f }| j| d S )Nz%f %f %f %f rectfill
)r5   rm   rt   )r7   rB   rC   rD   rE   ru   r0   r0   r1   rF      s    z$MathtextBackendPs.render_rect_filledc             C   s(   t dd| | j| j| j | j| j|fS )Nr   )rf   r4   r5   r6   rm   )r7   rG   rg   r0   r0   r1   rH      s    
zMathtextBackendPs.get_resultsN)rJ   rK   rL   rM   r8   rA   rF   rH   r0   r0   r0   r1   rl      s
   rl   c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )MathtextBackendPdfzQ
    Store information to write a mathtext rendering to the PDF
    backend.
    c             C   s   g | _ g | _d S )N)glyphsrects)r7   r0   r0   r1   r8     s    zMathtextBackendPdf.__init__c             C   s:   |j j}| j| |j }| j||||j|j|jf d S )N)	r_   fnamer5   ro   rw   appendrq   numrr   )r7   r>   r?   r@   filenamer0   r0   r1   rA   
  s
    
zMathtextBackendPdf.render_glyphc             C   s&   | j || j| || || f d S )N)rx   rz   r5   )r7   rB   rC   rD   rE   r0   r0   r1   rF     s    z%MathtextBackendPdf.render_rect_filledc             C   s,   t dd| | j| j| j | j| j| j|fS )Nr   )rf   r4   r5   r6   rw   rx   )r7   rG   rg   r0   r0   r1   rH     s    
zMathtextBackendPdf.get_resultsN)rJ   rK   rL   rM   r8   rA   rF   rH   r0   r0   r0   r1   rv     s
   rv   c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )MathtextBackendSvgzQ
    Store information to write a mathtext rendering to the SVG
    backend.
    c             C   s   g | _ g | _d S )N)
svg_glyphs	svg_rects)r7   r0   r0   r1   r8   "  s    zMathtextBackendSvg.__init__c             C   s4   | j | |j }| j|j|j|j|||jf d S )N)r5   ro   r~   rz   r_   rq   r{   rZ   )r7   r>   r?   r@   r0   r0   r1   rA   &  s    zMathtextBackendSvg.render_glyphc             C   s*   | j || j| d || || f d S )NrR   )r   rz   r5   )r7   rB   rC   rD   rE   r0   r0   r1   rF   ,  s    z%MathtextBackendSvg.render_rect_filledc             C   s8   t dd| tj| j| jd}| j| j| j | j||fS )Nr   )r~   r   )rf   typesSimpleNamespacer~   r   r4   r5   r6   )r7   rG   rg   Zsvg_elementsr0   r0   r1   rH   0  s    

zMathtextBackendSvg.get_resultsN)rJ   rK   rL   rM   r8   rA   rF   rH   r0   r0   r0   r1   r}     s
   r}   c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )MathtextBackendPathzY
    Store information to write a mathtext rendering to the text path
    machinery.
    c             C   s   g | _ g | _d S )N)rw   rx   )r7   r0   r0   r1   r8   @  s    zMathtextBackendPath.__init__c             C   s4   | j | |j }|j}| j|j|j|||f d S )N)r5   ro   r{   rw   rz   r_   rq   )r7   r>   r?   r@   thetextr0   r0   r1   rA   D  s    z MathtextBackendPath.render_glyphc             C   s&   | j || j| || || f d S )N)rx   rz   r5   )r7   rB   rC   rD   rE   r0   r0   r1   rF   J  s    z&MathtextBackendPath.render_rect_filledc             C   s*   t dd| | j| j| j | j| j| jfS )Nr   )rf   r4   r5   r6   rw   rx   )r7   rG   rg   r0   r0   r1   rH   N  s    
zMathtextBackendPath.get_resultsN)rJ   rK   rL   rM   r8   rA   rF   rH   r0   r0   r0   r1   r   :  s
   r   c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )MathtextBackendCairozS
    Store information to write a mathtext rendering to the Cairo
    backend.
    c             C   s   g | _ g | _d S )N)rw   rx   )r7   r0   r0   r1   r8   \  s    zMathtextBackendCairo.__init__c             C   s8   ||j  | j }t|j}| j|j|j|||f d S )N)ro   r5   chrr{   rw   rz   r_   rq   )r7   r>   r?   r@   r   r0   r0   r1   rA   `  s    
z!MathtextBackendCairo.render_glyphc             C   s&   | j ||| j || || f d S )N)rx   rz   r5   )r7   rB   rC   rD   rE   r0   r0   r1   rF   f  s    z'MathtextBackendCairo.render_rect_filledc             C   s*   t dd| | j| j| j | j| j| jfS )Nr   )rf   r4   r5   r6   rw   rx   )r7   rG   rg   r0   r0   r1   rH   j  s    
z MathtextBackendCairo.get_resultsN)rJ   rK   rL   rM   r8   rA   rF   rH   r0   r0   r0   r1   r   V  s
   r   c               @   sr   e Zd ZdZdd Zdd Zdd Zdd	d
Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd ZdS )Fontsz
    An abstract base class for a system of fonts to use for mathtext.

    The class must be able to take symbol keys and font file names and
    return the character metrics.  It also delegates to a backend class
    to do the actual drawing.
    c             C   s   || _ || _i | _dS )aH  
        *default_font_prop*: A
        :class:`~matplotlib.font_manager.FontProperties` object to use
        for the default non-math font, or the base font for Unicode
        (generic) font rendering.

        *mathtext_backend*: A subclass of :class:`MathTextBackend`
        used to delegate the actual rendering.
        N)default_font_propmathtext_backendrg   )r7   r   r   r0   r0   r1   r8   {  s    
zFonts.__init__c             C   s
   d| _ dS )za
        Fix any cyclical references before the object is about
        to be destroyed.
        N)rg   )r7   r0   r0   r1   destroy  s    zFonts.destroyc
       
      C   s   dS )av  
        Get the kerning distance for font between *sym1* and *sym2*.

        *fontX*: one of the TeX font names::

          tt, it, rm, cal, sf, bf or default/regular (non-math)

        *fontclassX*: TODO

        *symX*: a symbol in raw TeX form. e.g., '1', 'x' or '\sigma'

        *fontsizeX*: the fontsize in points

        *dpi*: the current dots-per-inch
        g        r0   )
r7   font1
fontclass1sym1	fontsize1font2
fontclass2sym2	fontsize2dpir0   r0   r1   get_kern  s    zFonts.get_kernTc             C   s   |  ||||||}|jS )a4  
        *font*: one of the TeX font names::

          tt, it, rm, cal, sf, bf or default/regular (non-math)

        *font_class*: TODO

        *sym*:  a symbol in raw TeX form. e.g., '1', 'x' or '\sigma'

        *fontsize*: font size in points

        *dpi*: current dots-per-inch

        *math*: whether sym is a math character

        Returns an object with the following attributes:

          - *advance*: The advance distance (in points) of the glyph.

          - *height*: The height of the glyph in points.

          - *width*: The width of the glyph in points.

          - *xmin*, *xmax*, *ymin*, *ymax* - the ink rectangle of the glyph

          - *iceberg* - the distance from the baseline to the top of
            the glyph.  This corresponds to TeX's definition of
            "height".
        )	_get_inforZ   )r7   r_   
font_classsymrq   r   r/   r@   r0   r0   r1   get_metrics  s    zFonts.get_metricsc             C   s6   t |||g\| _| _| _| j| j| j| j dS )z
        Set the size of the buffer used to render the math expression.
        Only really necessary for the bitmap backends.
        N)rX   rY   r4   r5   r6   r   r<   )r7   r9   r:   r;   r0   r0   r1   r<     s    zFonts.set_canvas_sizec             C   sZ   |  |||||}t|jj\}	}
| j|
|	t f}|d |j | j	
||| dS )a  
        Draw a glyph at

          - *ox*, *oy*: position

          - *facename*: One of the TeX face names

          - *font_class*:

          - *sym*: TeX symbol name or single character

          - *fontsize*: fontsize in points

          - *dpi*: The dpi to draw at.
        rR   N)r   r   r_   ry   rg   
setdefaultsetaddr{   r   rA   )r7   r>   r?   Zfacenamer   r   rq   r   r@   realpathZstat_keyrg   r0   r0   r1   rA     s    zFonts.render_glyphc             C   s   | j |||| dS )zL
        Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*).
        N)r   rF   )r7   rB   rC   rD   rE   r0   r0   r1   rF     s    zFonts.render_rect_filledc             C   s
   t  dS )zF
        Get the xheight for the given *font* and *fontsize*.
        N)r=   )r7   r_   rq   r   r0   r0   r1   get_xheight  s    zFonts.get_xheightc             C   s
   t  dS )z
        Get the line thickness that matches the given font.  Used as a
        base unit for drawing lines such as in a fraction or radical.
        N)r=   )r7   r_   rq   r   r0   r0   r1   get_underline_thickness  s    zFonts.get_underline_thicknessc             C   s   | j S )z
        Get the set of characters that were used in the math
        expression.  Used by backends that need to subset fonts so
        they know which glyphs to include.
        )rg   )r7   r0   r0   r1   get_used_characters  s    zFonts.get_used_charactersc             C   s   | j ||  }|   |S )z
        Get the data needed by the backend to render the math
        expression.  The return value is backend-specific.
        )r   rH   r   r   )r7   rG   rh   r0   r0   r1   rH     s    zFonts.get_resultsc             C   s
   ||fgS )a  
        Override if your font provides multiple sizes of the same
        symbol.  Should return a list of symbols matching *sym* in
        various sizes.  The expression renderer will select the most
        appropriate size for a given situation from this list.
        r0   )r7   fontnamer   r0   r0   r1   !get_sized_alternatives_for_symbol  s    z'Fonts.get_sized_alternatives_for_symbolN)T)rJ   rK   rL   rM   r8   r   r   r   r<   rA   rF   r   r   r   rH   r   r0   r0   r0   r1   r   r  s   
!		r   c               @   sR   e Zd ZdZdd Zdd Zdd Zdd	 ZdddZdd Z	dd Z
dd ZdS )TruetypeFontsza
    A generic base class for all font setups that use Truetype fonts
    (through FT2Font).
    c             C   sB   t | || i | _i | _t|}t|}|| jd< || jd< d S )Ndefaultregular)r   r8   glyphd_fontsr   r    )r7   r   r   r|   default_fontr0   r0   r1   r8     s    
zTruetypeFonts.__init__c             C   s   d | _ t|  d S )N)r   r   r   )r7   r0   r0   r1   r      s    zTruetypeFonts.destroyc             C   sl   || j kr| j | }n|}| j|}|d krhtj|rht|}|| j|< || j|j< || j|j < |S )N)	fontmapr   getospathexistsr    rp   lower)r7   r_   basenamecached_fontr0   r0   r1   	_get_font$  s    

zTruetypeFonts._get_fontc             C   s,   |j dkr(|jd d |d | d  S dS )NZCmex10g      P@g       @g      @g      R@g        )rp   r5   )r7   r_   ra   rq   r   r0   r0   r1   _get_offset1  s    
zTruetypeFonts._get_offsetTc             C   s   |||||f}| j |}|d k	r&|S | |||||\}	}
}}}|	|| |	j|
| j d}dd |jD \}}}}| |	|||}t	j
|jd |jd |jd |||| || |jd | |d	}t	j
|	||	j|||
||d }| j |< |S )N)flagsc             S   s   g | ]}|d  qS )g      P@r0   ).0valr0   r0   r1   
<listcomp>D  s    z+TruetypeFonts._get_info.<locals>.<listcomp>g      @g      P@)	advancer5   r4   r[   r]   r^   r\   r`   slanted)r_   rq   rp   rZ   rr   r{   ra   ro   )r   r   
_get_glyphset_sizeZ	load_charr   rI   rO   r   r   r   ZlinearHoriAdvancer5   r4   ZhoriBearingYrp   )r7   r   r   r   rq   r   r/   keyZbunchr_   r{   rr   r   ra   r[   r^   r]   r\   ro   rZ   rh   r0   r0   r1   r   6  s>    zTruetypeFonts._get_infoc             C   sd   |  |}||| |d}|d krD| |td d||}|jS |d d |d  |d  }|S )Npcltzmathtext.defaultxxHeightg      P@g      (@g      Y@)r   r   Zget_sfnt_tabler   r   r`   )r7   r   rq   r   r_   r   rZ   r   r0   r0   r1   r   _  s    

zTruetypeFonts.get_xheightc             C   s   d| | d S )Ng      ?g      R@r0   )r7   r_   rq   r   r0   r0   r1   r   j  s    z%TruetypeFonts.get_underline_thicknessc
             C   sl   ||krP||krP|  |||||	}
|  |||||	}|
j}||
j|jtd S t| |||||||||	
S )Ng      P@)r   r_   get_kerningr{   r   r   r   )r7   r   r   r   r   r   r   r   r   r   info1info2r_   r0   r0   r1   r   p  s    zTruetypeFonts.get_kernN)T)rJ   rK   rL   rM   r8   r   r   r   r   r   r   r   r0   r0   r0   r1   r     s   

)r   c               @   s0  e Zd ZdZdddddddd	Zd
d Zed Zd`ddZ	dddddgdddddgdddddgdd d!d"d#gd$d%d&d'gd(d)d*d+gd,d-d.d/gd0d1d2d3gd4d5d6d7gd8d9d:d;gd<d=d>d?gd@dAdBdCgdDdEdFdGgdHdIdJdKgdLdMdNdOdPgdQdRdSdTgdUdVdWdXgdYd=gdZdAgd[Z
xd\D ]\ZZe
e e
e< q
W d]d^ Zd_S )aBakomaFontsz
    Use the Bakoma TrueType fonts for rendering.

    Symbols are strewn about a number of font files, each of which has
    its own proprietary 8-bit encoding.
    cmsy10cmr10cmtt10cmmi10cmb10cmss10cmex10)calrmttitbfsfexc             O   s\   t ||| _tj| f|| i | _x2| j D ]$\}}t|}|| j|< || j|< q0W d S )N)	StixFonts_stix_fallbackr   r8   r   _fontmapitemsr   )r7   argskwargsr   r   fullpathr0   r0   r1   r8     s    
zBakomaFonts.__init__z
\int \ointTc             C   s   d }d }|| j krD|tkrDt| \}}	|dkp6|| jk}
| |}n.t|dkrr|dk}
| |}|d k	rrt|}	|d k	r||	}|dkr||}|d kr| j	|||||S ||	|||
fS )Nr   rR   r   r   )
r   r!   _slanted_symbolsr   lenr(   get_char_indexget_glyph_namer   r   )r7   r   r   r   rq   r/   rr   r_   r   r{   r   gidr0   r0   r1   r     s&    


zBakomaFonts._get_glyph)r   ()r      ¡)r      ³)r      µ)r      Ã)r   ))r      ¢)r      ´)r      ¶)r   !)r   {)r      ©)r   n)r      ½)r   r   )r   })r      ª)r   o)r      ¾)r   r   )r   [)r      £)r   r:   )r   ")r   ])r      ¤)r   i)r   #)r      ¥)r   j)r      ¹)r   $)r      ¦)r   k)r      º)r   %)r      §)r   l)r      »)r   &)r      ¨)r   m)r      ¼)r   ')r      ­)r   D)r      ¿)r   *)r      ®)r   E)r      À)r   +)r   p)r   q)r   r)r   s)r      ²)r   /)r      Â)r   r&   )r   r  )r      ±)r   .)r      Ë)r   ,)r   ^)r   b)r   c)r   r;   )r   ~)r   e)r   f)r   g)r   r:   )r   r   )r   r   r   r   r   r   z\lfloorz\rfloorz\lceilz\rceilz\langlez\ranglez	\__sqrt__z
\backslashr  z\widehatz
\widetilde<>)
)z
\leftparenr   )z\rightparentr   )z
\leftbracer   )z\rightbracer   )z\leftbracketr   )z\rightbracketr   )z\{r   )z\}r   )z\[r   )z\]r   c             C   s   | j |||fgS )N)_size_alternativesr   )r7   r   r   r0   r0   r1   r     s    z-BakomaFonts.get_sized_alternatives_for_symbolN)T)rJ   rK   rL   rM   r   r8   r   splitr   r   r   aliastargetr   r0   r0   r0   r1   r   z  sd   

r   c               @   sB   e Zd ZdZdZdd Zed Zdd Z	ddd	Z
d
d ZdS )UnicodeFontsaa  
    An abstract base class for handling Unicode fonts.

    While some reasonably complete Unicode fonts (such as DejaVu) may
    work in some situations, the only Unicode font I'm aware of with a
    complete set of math symbols is STIX.

    This class will "fallback" on the Bakoma fonts when a required
    symbol can not be found in the font.
    Tc             O   s   t d rt||| _nd | _tj| f|| i | _x.d D ]"}t d|  }t|}|| j|< q>W td}t|}|| jd< d S )Nzmathtext.fallback_to_cmzcal rm tt it bf sfz	mathtext.r   r   )	r   r   cm_fallbackr   r8   r   r!  r   r   )r7   r   r   Ztexfontpropr_   r0   r0   r1   r8     s    zUnicodeFonts.__init__z
\int \ointc             C   s   ||fS )Nr0   )r7   r   r   uniindexr0   r0   r1   _map_virtual_font	  s    zUnicodeFonts._map_virtual_fontc             C   s  d}| j r$t|}|d k	r$d}d}|sjyt||}d}W n. tk
rh   td}td|t	 Y nX | 
|||\}}|}|r|dkr|dk rt|}	t|	d d	krt|	d
rd}|dkp|| jk}
d}| |}|d k	r||}|dkrd}|s| jrlt| jtr.tdt	 |dkrXt| jtrX| jd|||S | j||||S n`|dkrt| tr| d|||S td|||t	 d}|}| |}d}||}d}
||}|||||
fS )NFr   T?z#No TeX to unicode mapping for {!a}.r   i   r   LzGREEK CAPITALr   z0Substituting with a symbol from Computer Modern.)r   r   zTFont {!r} does not have a glyph for {!a} [U+{:x}], substituting with a dummy symbol.   )use_cmexr$   r   r2   r,   r(   warningswarnr-   MathTextWarningr(  r   unicodedatacategoryname
startswithr   r   r   r%  
isinstancer   r   r   r   )r7   r   r   r   rq   r/   found_symbolr'  Znew_fontnameZ	unistringr   r_   
glyphindexrr   r0   r0   r1   r     sv    










zUnicodeFonts._get_glyphc             C   s   | j r| j ||S ||fgS )N)r%  r   )r7   r   r   r0   r0   r1   r   V  s    z.UnicodeFonts.get_sized_alternatives_for_symbolN)T)rJ   rK   rL   rM   r,  r8   r   r!  r   r(  r   r   r0   r0   r0   r1   r$    s   

Jr$  c                   s*   e Zd ZdZdd Zd fdd	Z  ZS )DejaVuFontsFc             O   s   t | trt||| _nt||| _t||| _tj| f|| i | _	| j
dddddd x2| j
 D ]$\}}t|}|| j	|< || j	|< qlW d S )NSTIXSizeOneSymSTIXSizeTwoSymSTIXSizeThreeSymSTIXSizeFourSymSTIXSizeFiveSym)rR   rS   rT         )r4  DejaVuSerifFontsr   r%  StixSansFontsr   bakomar   r8   r   r   updater   r   )r7   r   r   r   r2  r   r0   r0   r1   r8   `  s     


zDejaVuFonts.__init__Tc       	         st   |dkr| j |||||S t|}| d}|dk	r\||}|dkr\t d||||S t |||||S dS )z% Override prime symbol to use Bakoma z\primer   Nr   )rA  r   r2   r   r   super)	r7   r   r   r   rq   r/   r'  r_   r6  )	__class__r0   r1   r   u  s    

zDejaVuFonts._get_glyph)T)rJ   rK   rL   r,  r8   r   __classcell__r0   r0   )rD  r1   r7  ]  s   r7  c               @   s$   e Zd ZdZddddddddZd	S )
r?  zv
    A font handling class for the DejaVu Serif fonts

    If a glyph is not found it will fallback to Stix Serif
    zDejaVu SerifzDejaVu Serif:italiczDejaVu Serif:weight=boldzDejaVu SanszDejaVu Sans MonozDejaVu Serif Display)r   r   r   r   r   r   r   N)rJ   rK   rL   rM   r   r0   r0   r0   r1   r?    s   r?  c               @   s$   e Zd ZdZddddddddZdS )	DejaVuSansFontszt
    A font handling class for the DejaVu Sans fonts

    If a glyph is not found it will fallback to Stix Sans
    zDejaVu SanszDejaVu Sans:italiczDejaVu Sans:weight=boldzDejaVu Sans MonozDejaVu Sans Display)r   r   r   r   r   r   r   N)rJ   rK   rL   rM   r   r0   r0   r0   r1   rF    s   rF  c               @   sV   e Zd ZdZddddddddd	d
dddZdZdZdZdd Zdd Z	i Z
dd ZdS )r   aa  
    A font handling class for the STIX fonts.

    In addition to what UnicodeFonts provides, this class:

    - supports "virtual fonts" which are complete alpha numeric
      character sets with different font styles at special Unicode
      code points, such as "Blackboard".

    - handles sized alternative characters for the STIXSizeX fonts.
    STIXGeneralzSTIXGeneral:italiczSTIXGeneral:weight=boldSTIXNonUnicodezSTIXNonUnicode:italiczSTIXNonUnicode:weight=boldr8  r9  r:  r;  r<  )r   r   r   ZnonunirmZnonuniitZnonunibfr   rR   rS   rT   r=  r>  Fc             O   sP   t j| f|| i | _x2| j D ]$\}}t|}|| j|< || j|< q$W d S )N)r   r8   r   r   r   r   )r7   r   r   r   r2  r   r0   r0   r1   r8     s    
zStixFonts.__init__c       
      C   sH  t |}| jr.|d kr.|dkr.t d }d}nd}|d k	rt|trpy|| }W n tk
rn   |d }Y nX d}t|}xJ||k r|| d }|| }	||	d k r|}q~||	d krP q~|d }q~W |	d |  kr|	d krn n||	d  |	d	  }|	d }n|sd}td
 }|dkr@|dkr@|dkr@d| }||fS )N)r   r   r   TFr   r   rS   rR   rT   zmathtext.default)r   r   r   i   i  Znonuni)r%   r   _sansr4  dictr+   r   r   )
r7   r   r   r'  mappingZdoing_sans_conversionlohiZmidranger0   r0   r1   r(    s@    



"

zStixFonts._map_virtual_fontc       
      C   s   ddddd}| ||}| j |}|r.|S g }yt|}W n tk
rX   ||fgS X tddtdd	i}| ||}x>td
D ]2}| |}||}	|	dkr||t	|f qW |dkr|d d }|| j|< |S )Nr   r   r   r   )z\{z\}z\[z\]r  i'  r  i'     r   z	\__sqrt__)
r   r   r2   r,   r(   rN  r   r   rz   r   )
r7   r   r   fixesalternativesr'  Zfix_upsr   r_   r6  r0   r0   r1   r     s,    


z+StixFonts.get_sized_alternatives_for_symbolN)rJ   rK   rL   rM   r   r,  r%  rI  r8   r(  r   r   r0   r0   r0   r1   r     s(   .r   c               @   s   e Zd ZdZdZdS )r@  zd
    A font handling class for the STIX fonts (that uses sans-serif
    characters by default).
    TN)rJ   rK   rL   rM   rI  r0   r0   r0   r1   r@    s   r@  c               @   sh   e Zd ZdZeje ddZdddddd	d
dZ	dd Z
dd ZdddZdd Zdd Zdd ZdS )StandardPsFontsz
    Use the standard postscript fonts for rendering to backend_ps

    Unlike the other font classes, BakomaFont and UnicodeFont, this
    one requires the Ps backend.
    fontsafmZpzcmi8aZpncr8aZpcrr8aZpncri8aZphvr8aZpncb8aZpsyr)r   r   r   r   r   r   Nc          	   C   s   t | |t  i | _i | _t|d| jd}|d krDtdd| jd}t|d}t|}W d Q R X ||_	|| jd< || jd< t
 | _d S )NrU  )ZfontextZ	directoryZ	Helveticarbr   r   )r   r8   rl   r   rT  r   basepathopenr   ry   r   rm   )r7   r   r|   fdr   r0   r0   r1   r8   6  s    



zStandardPsFonts.__init__c          	   C   s   || j kr| j | }n|}| j|}|d kr~tj| j|d }t|d}t|}W d Q R X ||_	|| j|< || j|
 < |S )Nz.afmrV  )r   rT  r   r   r   joinrW  rX  r   ry   get_fontname)r7   r_   r   r   ry   rY  r0   r0   r1   r   H  s    

zStandardPsFonts._get_fontTc                s  ||||f}| j |}|dk	r$|S |dkrLt|dksHt|dsLd}d}	|tkrrt| \}}
t|
}d}	n0t|dkr|}t|}
d}	nt	
d|t |dk}| |}|	ry||}W n0 tk
r   t	
d	| |t d}	Y nX |	sd
 }}t|}
||}d}d|   fdd||D \}}}}tj||  ||  ||  |||| || || |d	}tj||| |||
||d| j |< | j | S )z/load the cmfont, metrics and glyph with cachingNr   rR   r*  r   FTz.No TeX to built-in Postscript mapping for {!r}z2No glyph in standard Postscript font {!r} for {!r}r)  r   gMbP?c                s   g | ]}|  qS r0   r0   )r   r   )scaler0   r1   r     s   z-StandardPsFonts._get_info.<locals>.<listcomp>)	r   r4   r5   r[   r]   r^   r\   r`   r   )r_   rq   rp   rZ   rr   r{   ra   ro   )r   r   r   r0  r1  r3  r"   r   r(   r-  r.  r-   r/  r   Zget_name_charr+   r[  Zget_bbox_charr   r   Zget_width_charZget_height_char)r7   r   r   r   rq   r   r/   r   tupr5  r{   ra   r   r_   rr   ro   r[   r^   r]   r\   rZ   r0   )r\  r1   r   X  st    




zStandardPsFonts._get_infoc
             C   sn   ||krR||krR|  |||||	}
|  |||||	}|
j}||
j|jd | S t| |||||||||	
S )NgMbP?)r   r_   Zget_kern_distra   r   r   )r7   r   r   r   r   r   r   r   r   r   r   r   r_   r0   r0   r1   r     s    zStandardPsFonts.get_kernc             C   s   |  |}| d | S )NgMbP?)r   r   )r7   r_   rq   r   r0   r0   r1   r     s    
zStandardPsFonts.get_xheightc             C   s   |  |}| d | S )NgMbP?)r   r   )r7   r_   rq   r   r0   r0   r1   r     s    
z'StandardPsFonts.get_underline_thicknessN)T)rJ   rK   rL   rM   r   r   rZ  r   rW  r   r8   r   r   r   r   r   r0   r0   r0   r1   rS  $  s   
OrS  gffffff?g      ?rO  c               @   s0   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
S )FontConstantsBasez
    A set of constants that controls how certain things, such as sub-
    and superscripts are laid out.  These are all metrics that can't
    be reliably retrieved from the font metrics in the font itself.
    g?g?gffffff?g333333?g      ?g?g?g?N)rJ   rK   rL   rM   script_spacesubdropsup1sub1sub2deltadelta_slanteddelta_integralr0   r0   r0   r1   r^    s   r^  c               @   s,   e Zd ZdZdZdZdZdZdZdZ	dZ
dS )ComputerModernFontConstantsg333333?g?g?g333333?N)rJ   rK   rL   r_  r`  ra  rb  rc  rd  re  rf  r0   r0   r0   r1   rg     s   rg  c               @   s$   e Zd ZdZdZdZdZdZdZdS )STIXFontConstantsg?g?g333333?g?g333333?N)	rJ   rK   rL   r_  ra  rc  rd  re  rf  r0   r0   r0   r1   rh    s   rh  c               @   s   e Zd ZdZdZdZdZdS )STIXSansFontConstantsg?g?g333333?g333333?N)rJ   rK   rL   r_  ra  re  rf  r0   r0   r0   r1   ri    s   ri  c               @   s   e Zd ZdS )DejaVuSerifFontConstantsN)rJ   rK   rL   r0   r0   r0   r1   rj    s   rj  c               @   s   e Zd ZdS )DejaVuSansFontConstantsN)rJ   rK   rL   r0   r0   r0   r1   rk    s   rk  )zDejaVu SanszDejaVu Sans MonozDejaVu Serifr   r   r   r   r   r   r   rG  rH  r<  r;  r:  r9  r8  zBitstream Vera SanszBitstream Verac             C   s4   t | j| jjt}|tkr0t| jt	r0t
S |S )N)_font_constant_mappingr   font_outputr   r_   Zfamily_namer^  rh  r4  r@  ri  )state	constantsr0   r0   r1   _get_font_constant_set<  s    rp  c               @   s   e Zd ZdS )r/  N)rJ   rK   rL   r0   r0   r0   r1   r/  H  s   r/  c               @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )Nodez%
    A node in the TeX box model
    c             C   s
   d| _ d S )Nr   )size)r7   r0   r0   r1   r8   O  s    zNode.__init__c             C   s   | j jS )N)rD  rJ   )r7   r0   r0   r1   __repr__R  s    zNode.__repr__c             C   s   dS )Ng        r0   )r7   nextr0   r0   r1   r   U  s    zNode.get_kerningc             C   s   |  j d7  _ dS )z
        Shrinks one level smaller.  There are only three levels of
        sizes, after which things will no longer get smaller.
        rR   N)rr  )r7   r0   r0   r1   shrinkX  s    zNode.shrinkc             C   s   |  j d8  _ dS )zb
        Grows one level larger.  There is no limit to how big
        something can get.
        rR   N)rr  )r7   r0   r0   r1   grow_  s    z	Node.growc             C   s   d S )Nr0   )r7   r   rd   r0   r0   r1   re   f  s    zNode.renderN)
rJ   rK   rL   rM   r8   rs  r   ru  rv  re   r0   r0   r0   r1   rq  K  s   rq  c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )Boxz7
    Represents any node with a physical location.
    c             C   s    t |  || _|| _|| _d S )N)rq  r8   r4   r5   r6   )r7   r4   r5   r6   r0   r0   r1   r8   m  s    
zBox.__init__c             C   sB   t |  | jtk r>|  jt9  _|  jt9  _|  jt9  _d S )N)rq  ru  rr  NUM_SIZE_LEVELSr4   SHRINK_FACTORr5   r6   )r7   r0   r0   r1   ru  s  s
    

z
Box.shrinkc             C   s8   t |  |  jt9  _|  jt9  _|  jt9  _d S )N)rq  rv  r4   GROW_FACTORr5   r6   )r7   r0   r0   r1   rv  z  s    
zBox.growc             C   s   d S )Nr0   )r7   rB   rC   rD   rE   r0   r0   r1   re     s    z
Box.renderN)rJ   rK   rL   rM   r8   ru  rv  re   r0   r0   r0   r1   rw  i  s
   rw  c               @   s   e Zd ZdZdd ZdS )Vboxz.
    A box with only height (zero width).
    c             C   s   t | d|| d S )Ng        )rw  r8   )r7   r5   r6   r0   r0   r1   r8     s    zVbox.__init__N)rJ   rK   rL   rM   r8   r0   r0   r0   r1   r{    s   r{  c               @   s   e Zd ZdZdd ZdS )Hboxz8
    A box with only width (zero height and depth).
    c             C   s   t | |dd d S )Ng        )rw  r8   )r7   r4   r0   r0   r1   r8     s    zHbox.__init__N)rJ   rK   rL   rM   r8   r0   r0   r0   r1   r|    s   r|  c               @   sR   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd ZdS )Chara#  
    Represents a single character.  Unlike TeX, the font information
    and metrics are stored with each :class:`Char` to make it easier
    to lookup the font metrics when needed.  Note that TeX boxes have
    a width, height, and depth, unlike Type1 and Truetype which use a
    full bounding box and an advance in the x-direction.  The metrics
    must be converted to the TeX way, and the advance (if different
    from width) must be converted into a :class:`Kern` node when the
    :class:`Char` is added to its parent :class:`Hlist`.
    Tc             C   sJ   t |  || _|j| _|j| _|j| _|j| _|j| _|| _| 	  d S )N)
rq  r8   r  rm  r_   r   rq   r   r/   _update_metrics)r7   r  rn  r/   r0   r0   r1   r8     s    
zChar.__init__c             C   s
   d| j  S )Nz`%s`)r  )r7   r0   r0   r1   rs    s    zChar.__repr__c             C   s`   | j | j| j| j| j| j| j }| _| jdkr<|j	| _
n|j
| _
|j| _|j|j  | _d S )N )rm  r   r_   r   r  rq   r   r/   _metricsr   r4   r`   r5   r6   )r7   rZ   r0   r0   r1   r~    s    "

zChar._update_metricsc             C   s   | j jS )N)r  r   )r7   r0   r0   r1   
is_slanted  s    zChar.is_slantedc             C   sR   | j j| j }d}t|trJ| j| j| j| j	| j
|j|j|j	|j
| j	}|| S )z
        Return the amount of kerning between this and the given
        character.  Called when characters are strung together into
        :class:`Hlist` to create :class:`Kern` nodes.
        g        )r  r   r4   r4  r}  rm  r   r_   r   r  rq   r   )r7   rt  r   kernr0   r0   r1   r     s    
zChar.get_kerningc          	   C   s&   | j ||| j| j| j| j| j dS )z4
        Render the character to the canvas
        N)rm  rA   r_   r   r  rq   r   )r7   r   rd   r0   r0   r1   re     s    zChar.renderc             C   sP   t |  | jtk rL|  jt9  _|  jt9  _|  jt9  _|  jt9  _d S )N)	rq  ru  rr  rx  rq   ry  r4   r5   r6   )r7   r0   r0   r1   ru    s    

zChar.shrinkc             C   sF   t |  |  jt9  _|  jt9  _|  jt9  _|  jt9  _d S )N)rq  rv  rq   rz  r4   r5   r6   )r7   r0   r0   r1   rv    s
    
z	Char.growN)T)rJ   rK   rL   rM   r8   rs  r~  r  r   re   ru  rv  r0   r0   r0   r1   r}    s   


r}  c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )Accentz
    The font metrics need to be dealt with differently for accents,
    since they are already offset correctly from the baseline in
    TrueType fonts.
    c             C   sJ   | j | j| j| j| j| j }| _|j|j	 | _
|j|j | _d| _d S )Nr   )rm  r   r_   r   r  rq   r   r  r]   r[   r4   r\   r^   r5   r6   )r7   rZ   r0   r0   r1   r~    s
    zAccent._update_metricsc             C   s   t |  |   d S )N)r}  ru  r~  )r7   r0   r0   r1   ru    s    
zAccent.shrinkc             C   s   t |  |   d S )N)r}  rv  r~  )r7   r0   r0   r1   rv    s    
zAccent.growc          	   C   s6   | j || jj || jj | j| j| j| j| j	 dS )z5
        Render the character to the canvas.
        N)
rm  rA   r  r[   r^   r_   r   r  rq   r   )r7   r   rd   r0   r0   r1   re     s    zAccent.renderN)rJ   rK   rL   rM   r~  ru  rv  re   r0   r0   r0   r1   r    s
   r  c                   sL   e Zd ZdZdd Z fddZedd Zdd	 Zd
d Z	dd Z
  ZS )Listz:
    A list of nodes (either horizontal or vertical).
    c             C   s2   t | ddd d| _|| _d| _d| _d| _d S )Ng        r   )rw  r8   shift_amountchildrenglue_set	glue_sign
glue_order)r7   elementsr0   r0   r1   r8      s    zList.__init__c          
      s4   dt   | j| j| j| jddd | jD f S )Nz![%s <%.02f %.02f %.02f %.02f> %s]r  c             S   s   g | ]}t |qS r0   )repr)r   r   r0   r0   r1   r     s    z!List.__repr__.<locals>.<listcomp>)rC  rs  r4   r5   r6   r  rZ  r  )r7   )rD  r0   r1   rs  	  s
    zList.__repr__c             C   s4   x.t t| ddd D ]}| | dkr|S qW dS )z
        Determine the highest order of glue used by the members of this list.

        Helper function used by vpack and hpack.
        NrP  r   )rN  r   )totalsr   r0   r0   r1   _determine_order  s    zList._determine_orderc             C   sn   |  |}|| _|| _|| dkr2|||  | _nd| _d| _|dkrjt| jrjtd|| j	j
| f t d S )Ng        r   z	%s %s: %r)r  r  r  r  
glue_ratior   r  r-  r.  rD  rJ   r/  )r7   r   Zsignr  Z
error_typer   r0   r0   r1   	_set_glue  s    

zList._set_gluec             C   sL   x| j D ]}|  qW t|  | jtk rH|  jt9  _|  jt9  _d S )N)r  ru  rw  rr  rx  r  ry  r  )r7   childr0   r0   r1   ru  +  s    

zList.shrinkc             C   sB   x| j D ]}|  qW t|  |  jt9  _|  jt9  _d S )N)r  rv  rw  r  rz  r  )r7   r  r0   r0   r1   rv  3  s
    
z	List.grow)rJ   rK   rL   rM   r8   rs  staticmethodr  r  ru  rv  rE  r0   r0   )rD  r1   r    s   	r  c               @   s,   e Zd ZdZdddZdd Zdd	d
ZdS )Hlistz%
    A horizontal list of boxes.
            
additionalTc             C   s$   t | | |r|   |   d S )N)r  r8   r  hpack)r7   r  r9   r  do_kernr0   r0   r1   r8   >  s    zHlist.__init__c             C   s   g }t | j}|rxht|D ]\}| j| }||d k rF| j|d  }nd}|| ||}|dkrt|}|| qW || _dS )a)  
        Insert :class:`Kern` nodes between :class:`Char` nodes to set
        kerning.  The :class:`Char` nodes themselves determine the
        amount of kerning they need (in :meth:`~Char.get_kerning`),
        and this function just creates the linked list in the correct
        way.
        rR   Ng        )r   r  rN  rz   r   Kern)r7   new_childrenZnum_childrenr   elemrt  Zkerning_distancer  r0   r0   r1   r  D  s    



z
Hlist.kernc             C   s  d}d}d}dgd }dgd }x| j D ]}t|trZ||j7 }t||j}t||j}q(t|tr||j7 }t	|jst	|jst
|dd}	t||j|	 }t||j|	 }q(t|tr|j}
||
j7 }||
j  |
j7  < ||
j  |
j7  < q(t|tr(||j7 }q(W || _|| _|dkr.||7 }|| _|| }|dkr\d| _d| _d| _dS |dkrx| |d|d n| |d	|d
 dS )a  
        The main duty of :meth:`hpack` is to compute the dimensions of
        the resulting boxes, and to adjust the glue if one of those
        dimensions is pre-specified.  The computed sizes normally
        enclose all of the material inside the new box; but some items
        may stick out if negative glue is used, if the box is
        overfull, or if a ``\vbox`` includes other boxes that have
        been shifted left.

          - *w*: specifies a width

          - *m*: is either 'exactly' or 'additional'.

        Thus, ``hpack(w, 'exactly')`` produces a box whose width is
        exactly *w*, while ``hpack(w, 'additional')`` yields a box
        whose width is the natural width plus *w*.  The default values
        produce a box with the natural width.
        g        r=  r  r  r   NrR   OverfullrP  	Underfull)r  r4  r}  r4   rV   r5   r6   rw  rX   isinfgetattrGlue	glue_specstretch_orderstretchshrink_orderru  r  r  r  r  r  )r7   r9   r  r:   r;   r   total_stretchtotal_shrinkr  r  r  r0   r0   r1   r  j  sJ    











zHlist.hpackN)r  r  T)r  r  )rJ   rK   rL   rM   r8   r  r  r0   r0   r0   r1   r  :  s   
&r  c               @   s,   e Zd ZdZd	ddZddejfddZdS )
Vlistz#
    A vertical list of boxes.
            r  c             C   s   t | | |   d S )N)r  r8   vpack)r7   r  r:   r  r0   r0   r1   r8     s    zVlist.__init__c             C   s  d}d}d}dgd }dgd }x| j D ]}	t|	trt|||	j 7 }|	j}t|	jst|	dd}
t	||	j|
 }q(t|	t
r||7 }d}|	j}||j7 }||j  |j7  < ||j  |j7  < q(t|	tr|||	j 7 }d}q(t|	tr(tdq(W || _||kr||| 7 }|| _n|| _|dkr4||7 }|| _|| }|dkrbd| _d| _d| _dS |dkr~| |d|d	 n| |d
|d dS )a6  
        The main duty of :meth:`vpack` is to compute the dimensions of
        the resulting boxes, and to adjust the glue if one of those
        dimensions is pre-specified.

          - *h*: specifies a height
          - *m*: is either 'exactly' or 'additional'.
          - *l*: a maximum height

        Thus, ``vpack(h, 'exactly')`` produces a box whose height is
        exactly *h*, while ``vpack(h, 'additional')`` yields a box
        whose height is the natural height plus *h*.  The default
        values produce a box with the natural width.
        g        r=  r  z2Internal mathtext error: Char node found in Vlist.r  r   NrR   r  rP  r  )r  r4  rw  r5   r6   rX   r  r4   r  rV   r  r  r  r  r  ru  r  r}  RuntimeErrorr  r  r  r  )r7   r:   r  r   r9   r;   r   r  r  r  r  r  r0   r0   r1   r    sR    










zVlist.vpackN)r  r  )rJ   rK   rL   rM   r8   rX   infr  r0   r0   r0   r1   r    s   
r  c               @   s    e Zd ZdZdd Zdd ZdS )Rulea  
    A :class:`Rule` node stands for a solid black rectangle; it has
    *width*, *depth*, and *height* fields just as in an
    :class:`Hlist`. However, if any of these dimensions is inf, the
    actual value will be determined by running the rule up to the
    boundary of the innermost enclosing box. This is called a "running
    dimension." The width is never running in an :class:`Hlist`; the
    height and depth are never running in a :class:`Vlist`.
    c             C   s   t | ||| |j| _d S )N)rw  r8   rm  )r7   r4   r5   r6   rn  r0   r0   r1   r8     s    zRule.__init__c             C   s   | j |||| ||  d S )N)rm  rF   )r7   r   rd   r9   r:   r0   r0   r1   re     s    zRule.renderN)rJ   rK   rL   rM   r8   re   r0   r0   r0   r1   r    s   	r  c               @   s   e Zd ZdZdddZdS )Hrulez8
    Convenience class to create a horizontal rule.
    Nc             C   sB   |d kr|j |j|j|j}|d  }}t| tj||| d S )Ng      ?)	rm  r   r_   rq   r   r  r8   rX   r  )r7   rn  	thicknessr5   r6   r0   r0   r1   r8     s
    zHrule.__init__)N)rJ   rK   rL   rM   r8   r0   r0   r0   r1   r    s   r  c               @   s   e Zd ZdZdd ZdS )Vrulez6
    Convenience class to create a vertical rule.
    c             C   s0   |j |j|j|j}t| |tjtj| d S )N)	rm  r   r_   rq   r   r  r8   rX   r  )r7   rn  r  r0   r0   r1   r8     s    zVrule.__init__N)rJ   rK   rL   rM   r8   r0   r0   r0   r1   r    s   r  c               @   s*   e Zd ZdZd
ddZdd Zdd Zd	S )r  a  
    Most of the information in this object is stored in the underlying
    :class:`GlueSpec` class, which is shared between multiple glue objects.
    (This is a memory optimization which probably doesn't matter anymore, but
    it's easier to stick to what TeX does.)
    Fc             C   sT   t |  d| _t|tr&t|}nt|tr6|}ntd|rJ| }|| _	d S )NZnormalz.glue_type must be a glue spec name or instance)
rq  r8   Zglue_subtyper4  strGlueSpecfactoryr,   copyr  )r7   	glue_typer  r  r0   r0   r1   r8     s    


zGlue.__init__c             C   s@   t |  | jtk r<| jjdkr<| j | _| j jt9  _d S )Ng        )rq  ru  rr  rx  r  r4   r  ry  )r7   r0   r0   r1   ru  ,  s
    

zGlue.shrinkc             C   s6   t |  | jjdkr2| j | _| j jt9  _d S )Ng        )rq  rv  r  r4   r  rz  )r7   r0   r0   r1   rv  3  s    
z	Glue.growN)F)rJ   rK   rL   rM   r8   ru  rv  r0   r0   r0   r1   r    s   
r  c               @   s2   e Zd ZdZdddZdd Zdd	 ZeeZd
S )r  z
    See :class:`Glue`.
            r   c             C   s"   || _ || _|| _|| _|| _d S )N)r4   r  r  ru  r  )r7   r4   r  r  ru  r  r0   r0   r1   r8   =  s
    zGlueSpec.__init__c             C   s   t | j| j| j| j| jS )N)r  r4   r  r  ru  r  )r7   r0   r0   r1   r  D  s    zGlueSpec.copyc             C   s
   | j | S )N)_types)clsr  r0   r0   r1   r  L  s    zGlueSpec.factoryN)r  r  r   r  r   )rJ   rK   rL   rM   r8   r  r  classmethodr0   r0   r0   r1   r  9  s
   
r  g        rR   rS   rT   g      )filfillfilllneg_filneg_fill	neg_filllemptyssc               @   s   e Zd Zdd ZdS )Filc             C   s   t | d d S )Nr  )r  r8   )r7   r0   r0   r1   r8   ^  s    zFil.__init__N)rJ   rK   rL   r8   r0   r0   r0   r1   r  ]  s   r  c               @   s   e Zd Zdd ZdS )Fillc             C   s   t | d d S )Nr  )r  r8   )r7   r0   r0   r1   r8   b  s    zFill.__init__N)rJ   rK   rL   r8   r0   r0   r0   r1   r  a  s   r  c               @   s   e Zd Zdd ZdS )Filllc             C   s   t | d d S )Nr  )r  r8   )r7   r0   r0   r1   r8   f  s    zFilll.__init__N)rJ   rK   rL   r8   r0   r0   r0   r1   r  e  s   r  c               @   s   e Zd Zdd ZdS )NegFilc             C   s   t | d d S )Nr  )r  r8   )r7   r0   r0   r1   r8   j  s    zNegFil.__init__N)rJ   rK   rL   r8   r0   r0   r0   r1   r  i  s   r  c               @   s   e Zd Zdd ZdS )NegFillc             C   s   t | d d S )Nr  )r  r8   )r7   r0   r0   r1   r8   n  s    zNegFill.__init__N)rJ   rK   rL   r8   r0   r0   r0   r1   r  m  s   r  c               @   s   e Zd Zdd ZdS )NegFilllc             C   s   t | d d S )Nr  )r  r8   )r7   r0   r0   r1   r8   r  s    zNegFilll.__init__N)rJ   rK   rL   r8   r0   r0   r0   r1   r  q  s   r  c               @   s   e Zd Zdd ZdS )SsGluec             C   s   t | d d S )Nr  )r  r8   )r7   r0   r0   r1   r8   v  s    zSsGlue.__init__N)rJ   rK   rL   r8   r0   r0   r0   r1   r  u  s   r  c               @   s   e Zd ZdZdd ZdS )	HCenteredzs
    A convenience class to create an :class:`Hlist` whose contents are
    centered within its enclosing box.
    c             C   s$   t j| t g| t g dd d S )NF)r  )r  r8   r  )r7   r  r0   r0   r1   r8   ~  s    zHCentered.__init__N)rJ   rK   rL   rM   r8   r0   r0   r0   r1   r  y  s   r  c               @   s   e Zd ZdZdd ZdS )	VCenteredzr
    A convenience class to create a :class:`Vlist` whose contents are
    centered within its enclosing box.
    c             C   s    t | t g| t g  d S )N)r  r8   r  )r7   r  r0   r0   r1   r8     s    zVCentered.__init__N)rJ   rK   rL   rM   r8   r0   r0   r0   r1   r    s   r  c               @   s8   e Zd ZdZdZdZdd Zdd Zdd Zd	d
 Z	dS )r  a  
    A :class:`Kern` node has a width field to specify a (normally
    negative) amount of spacing. This spacing correction appears in
    horizontal lists between letters like A and V when the font
    designer said that it looks better to move them closer together or
    further apart. A kern node can also appear in a vertical list,
    when its *width* denotes additional spacing in the vertical
    direction.
    r   c             C   s   t |  || _d S )N)rq  r8   r4   )r7   r4   r0   r0   r1   r8     s    
zKern.__init__c             C   s
   d| j  S )Nzk%.02f)r4   )r7   r0   r0   r1   rs    s    zKern.__repr__c             C   s&   t |  | jtk r"|  jt9  _d S )N)rq  ru  rr  rx  r4   ry  )r7   r0   r0   r1   ru    s    

zKern.shrinkc             C   s   t |  |  jt9  _d S )N)rq  rv  r4   rz  )r7   r0   r0   r1   rv    s    
z	Kern.growN)
rJ   rK   rL   rM   r5   r6   r8   rs  ru  rv  r0   r0   r0   r1   r    s   	r  c               @   s   e Zd ZdZdd ZdS )SubSuperClusteraR  
    :class:`SubSuperCluster` is a sort of hack to get around that fact
    that this code do a two-pass parse like TeX.  This lets us store
    enough information in the hlist itself, namely the nucleus, sub-
    and super-script, such that if another script follows that needs
    to be attached, it can be reconfigured on the fly.
    c             C   s"   d | _ d | _d | _t| g  d S )N)nucleussubrC  r  r8   )r7   r0   r0   r1   r8     s    zSubSuperCluster.__init__N)rJ   rK   rL   rM   r8   r0   r0   r0   r1   r    s   r  c               @   s   e Zd ZdZdddZdS )AutoHeightCharaG  
    :class:`AutoHeightChar` will create a character as close to the
    given height and depth as possible.  When using a font with
    multiple height versions of some characters (such as the BaKoMa
    fonts), the correct glyph will be selected, otherwise this will
    always just return a scaled version of the glyph.
    FNc             C   s   |j |j|}|j |j|j|j}| }|| }	x:|D ]2\}
}|
|_t||}|j|j	 |	d|  kr<P q<W d}|jdkr|d kr|	|j|j	  }| j|9  _t||}||j	 }t
| |g || _d S )Ng?r   )rm  r   r_   r   rq   r   r  r}  r5   r6   r  r8   r  )r7   r  r5   r6   rn  alwaysfactorrR  r   Ztarget_totalr   r   charshiftr0   r0   r1   r8     s(    




zAutoHeightChar.__init__)FN)rJ   rK   rL   rM   r8   r0   r0   r0   r1   r    s   r  c               @   s   e Zd ZdZdefddZdS )AutoWidthChara:  
    :class:`AutoWidthChar` will create a character as close to the
    given width as possible.  When using a font with multiple width
    versions of some characters (such as the BaKoMa fonts), the
    correct glyph will be selected, otherwise this will always just
    return a scaled version of the glyph.
    Fc             C   s   |j |j|}| }x,|D ]$\}}||_|||}	|	j|krP qW ||	j }
| j|
9  _|||}	t| |	g |	j| _d S )N)rm  r   r_   r  r4   rq   r  r8   )r7   r  r4   rn  r  
char_classrR  r   r   r  r  r0   r0   r1   r8     s    




zAutoWidthChar.__init__N)rJ   rK   rL   rM   r}  r8   r0   r0   r0   r1   r    s   r  c               @   s8   e Zd ZdZdd Zdd ZeeZdd Zdd	 Zd
S )Shipa  
    Once the boxes have been set up, this sends them to output.  Since
    boxes can be inside of boxes inside of boxes, the main work of
    :class:`Ship` is done by two mutually recursive routines,
    :meth:`hlist_out` and :meth:`vlist_out`, which traverse the
    :class:`Hlist` nodes and :class:`Vlist` nodes inside of horizontal
    and vertical boxes.  The global variables used in TeX to store
    state as it processes have become member variables here.
    c             C   s8   d| _ d| _d| _d| _|| _||j | _| | d S )Nr   g        )max_pushcur_scur_vcur_hoff_hr5   off_v	hlist_out)r7   r>   r?   rG   r0   r0   r1   __call__  s    zShip.__call__c             C   s   | dk rdS | dkrdS | S )Ng    eg    eAr0   )valuer0   r0   r1   clamp  s
    z
Ship.clampc             C   sj  d}d}|j }|j}| j}| j}|  jd7  _t| j| j| _| j}x|jD ]}	t	|	t
r|	| j| j | j| j  |  j|	j7  _qNt	|	tr|  j|	j7  _qNt	|	trt|	jdkr|  j|	j7  _nF| j}
||	j | _t	|	t r| |	 n
| |	 |
|	j | _|| _qNt	|	tr|	j}|	j}|	j}t|rL|j}t|r^|j}|dkr|dkr|| | _|	| j| j | j| j || || _|  j|7  _qNt	|	trN|	j}|j| }|dkr>|dkr|j|kr>||j7 }t|t |j!| }n.|j"|kr>||j#7 }t|t |j!| }||7 }|  j|7  _qNW |  jd8  _d S )Nr   g        rR   )$r  r  r  r  r  rV   r  r  r  r4  r}  re   r  r  r4   r  r  r   r  r  r  	vlist_outrw  r5   r6   rX   r  r  r  r  r  roundfloatr  r  ru  )r7   rG   cur_gcur_gluer  r  Z	base_line	left_edger  r  Zedgerule_height
rule_depth
rule_widthr  r0   r0   r1   r    sl    










zShip.hlist_outc             C   sZ  d}d}|j }|j}|  jd7  _t| j| j| _| j}|  j|j8  _| j}| j}x|j	D ]}	t
|	tr|  j|	j7  _q^t
|	trt|	j	dkr|  j|	j|	j 7  _n\|  j|	j7  _||	j | _| j}
|j|	_t
|	tr| |	 n
| |	 |
|	j | _|| _q^t
|	tr|	j}|	j}|	j}t|r@|j}||7 }|dkrD|dkrD|  j|7  _|	| j| j | j| j || q^t
|	tr2|	j}|j| }|dkr|dkr|j|kr||j7 }t|t|j | }n.|j!|kr||j"7 }t|t|j | }||7 }|  j|7  _q^t
|	t#r^t$dq^W |  jd8  _d S )Nr   g        rR   z1Internal mathtext error: Char node found in vlist)%r  r  r  rV   r  r  r  r5   r  r  r4  r  r4   r  r   r6   r  r  r  r  rw  rX   r  re   r  r  r  r  r  r  r  r  r  r  ru  r}  r  )r7   rG   r  r  r  r  r  Ztop_edger  r  Zsave_vr  r  r  r  r0   r0   r1   r  O  sj    










zShip.vlist_outN)	rJ   rK   rL   rM   r  r  r  r  r  r0   r0   r0   r1   r    s   		?r  c                s     fdd}t  }|| |S )z.
    Helper class to raise parser errors.
    c                s   t | | d S )N)r   )r  loctoks)msgr0   r1   raise_error  s    zError.<locals>.raise_error)r   setParseAction)r  r  r  r0   )r  r1   Error  s    
r  c                   sr  e Zd ZdZedddddZed Zed Z	ed	 Z
ee	B e
B Zed
 Zed Zed Zed Zed Zed Zed Zed Zed Zdd Zdd ZG dd deZdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Z d)d)d)d*d*d+d,d-ddd.d/Z!d0d1 Z"d2d3 Z#d4d5 Z$e$Z%d6d7 Z&d8d9iZ'd:d; Z(d<d=d>d?d@dAdBdCdDdCd?d@dAdBd<dEdFdGdHZ)edI Z*dJdK ee)Z+dLdM Z,dNdO Z-dPdQ Z.dRdS Z/dTdU Z0e0 Z1Z2dVdW Z3dXdY Z4dZd[ Z5d\d] Z6d^d_ Z7d`da Z8 fdbdcZ9ddde Z:dfdg Z;dhdi Z<djdk Z=dldm Z>dndo Z?dpdq Z@drds ZAdtdu ZBdvdw ZC  ZDS )xParsera  
    This is the pyparsing-based parser for math expressions.  It
    actually parses full strings *containing* math expressions, in
    that raw text may also appear outside of pairs of ``$``.

    The grammar is based directly on that in TeX, though it cuts a few
    corners.
    r   rR   rS   rT   )displaystyle	textstyleZscriptstyleZscriptscriptstylea  
      + * -
      \pm             \sqcap                   \rhd
      \mp             \sqcup                   \unlhd
      \times          \vee                     \unrhd
      \div            \wedge                   \oplus
      \ast            \setminus                \ominus
      \star           \wr                      \otimes
      \circ           \diamond                 \oslash
      \bullet         \bigtriangleup           \odot
      \cdot           \bigtriangledown         \bigcirc
      \cap            \triangleleft            \dagger
      \cup            \triangleright           \ddagger
      \uplus          \lhd                     \amalga  
      = < > :
      \leq            \geq             \equiv           \models
      \prec           \succ            \sim             \perp
      \preceq         \succeq          \simeq           \mid
      \ll             \gg              \asymp           \parallel
      \subset         \supset          \approx          \bowtie
      \subseteq       \supseteq        \cong            \Join
      \sqsubset       \sqsupset        \neq             \smile
      \sqsubseteq     \sqsupseteq      \doteq           \frown
      \in             \ni              \propto          \vdash
      \dashv          \dots            \dotplus         \doteqdota  
      \leftarrow              \longleftarrow           \uparrow
      \Leftarrow              \Longleftarrow           \Uparrow
      \rightarrow             \longrightarrow          \downarrow
      \Rightarrow             \Longrightarrow          \Downarrow
      \leftrightarrow         \longleftrightarrow      \updownarrow
      \Leftrightarrow         \Longleftrightarrow      \Updownarrow
      \mapsto                 \longmapsto              \nearrow
      \hookleftarrow          \hookrightarrow          \searrow
      \leftharpoonup          \rightharpoonup          \swarrow
      \leftharpoondown        \rightharpoondown        \nwarrow
      \rightleftharpoons      \leadstoz, ; . ! \ldotp \cdotpz}
       \sum \prod \coprod \bigcap \bigcup \bigsqcup \bigvee
       \bigwedge \bigodot \bigotimes \bigoplus \biguplus
       zlim liminf limsup sup max minz
\int \ointz6rm cal it tt sf bf default bb frak circled scr regularz
      arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim
      liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan
      coth inf max tanhzr
      | \| / \backslash \uparrow \downarrow \updownarrow \Uparrow
      \Downarrow \Updownarrow . \vert \Vert \\|z( [ \{ < \lfloor \langle \lceilz) ] \} > \rfloor \rangle \rceilc          
   C   s  t  }t |_t |_t |_t |_t |_t |_t |_	t |_
t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_t |_ t |_!t |_"t |_#t |_$t |_%t |_&t |_'t |_(t |_)t |_*t |_+t |_,t |_-t |_.t |_/t |_0t |_1x0t2|3 D ] \}}|4ds|5| qW | jt6dK  _| jt6dK  _| jt7d8 K  _| jt7d8 K  _| jt7d8 K  _| j t7d8 K  _ | jt7dK  _| j(t9t:| j;K  _(| j
t<t7d	|j|j |j t=d
B  K  _
d}| j&t6d| K  _&| j't<|jt9| j> K  _'| j/t?|jt9t:t@ tAt6dB tC B  K  _/| j.|j&|j/B B K  _.| jt6dK  _| j	t<|jt9t:| jD K  _	| jtEt<|jt9| jF| jG |j K  _| jt<|jt9t:| jH K  _| j+tI|j|j K  _+| j|jJ K  _| j%tE|jtK|j0 |j K  _%| j!tE|jtL|j0 |j K  _!| jtE|j+tK|j0 |j K  _| jt<|jt9t:| jM K  _| jt<|jt9dd | jMD  K  _| jtEt<t7d|j!|j! t=dB  K  _| jtEt<t7d|j!|j! t=dB  K  _| j*tEt<t7d|j!|j! t=dB  K  _*| jtEt<t7d|j!|j! t=dB  K  _| jt9t:| jNK  _| jt9t:| jOK  _| j"t9t:| jPK  _"| j#t9| jPdh d-K  _#| jtEt<t7d|jtI|j|jB dd |j |jtI|j|j#B dd |j  |j|j |j  |j% |j! |j! t=dB  K  _| j)tEt<t7dtI|j|j |j  d d|j! t=dB  K  _)| jtEt<t7d |j!t=d!B  K  _| j1t?|jt6d" K  _1| jtEt<t7d#|jtK|j$|j1B  |j t=d$B  K  _| j|j'|jB |j.B |j	B |jB |jB |jB |jB |j*B |jB |jB |j)B |jB |jB K  _| j$|j(|j
B |jB |j,B K  _$| j-t9dd%gK  _-| j,tEtI|jtL|j-|j  tI|j |jtI|j B |jB K  _,| j0|j$|jB |j1B K  _0| jt<t7d&|j|jB t=d'B  tEtK|j$|jB  t<t7d( |j"|jB t=d'B  K  _| jtL|j0K  _| jtQd)dd*d+K  _| jt6d,B K  _| j|jtK|j|j  tC  K  _xBt2|3 D ]2\}}|4dstR| |r|StT| | qW |j| _U|j| _Vd S ).N_z[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)z[-+]?[0-9]+r   r   r   r   r'   z\hspacezExpected \hspace{n}u   -🿿z;([a-zA-Z0-9 +\-*/<>=:,.;!\?&'@()\[\]|%s])|(\\[%%${}\[\]_|])z	[^A-Za-z]z'+c             S   s   g | ]}d | qS )r/   r0   )r   r   r0   r0   r1   r   N	  s    z#Parser.__init__.<locals>.<listcomp>z\fraczExpected \frac{num}{den}z\dfraczExpected \dfrac{num}{den}z	\stackrelzExpected \stackrel{num}{den}z\binomzExpected \binom{num}{den}\}z\genfrac )r   z<Expected \genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}z\sqrtzExpected \sqrt{value}z	\overlinezExpected \overline{value}z	[A-Za-z]*z\operatornamezExpected \operatorname{value}r  z\leftzExpected a delimiterz\rightr   F)ZunquoteResultsz(?:(?:\\[$])|[^$])*)r  )Wr   r   r   accentZ
ambi_delimZ
apostrophe
auto_delimbinomZbslashc_over_ccustomspace	end_groupZfloat_literalr_   fracdfracfunctiongenfracgroupZint_literalZ	latexfontZlbracketZ
left_delimZlbracemainr/   math_stringnon_mathoperatornameoverlineZ	placeableZrbraceZrbracketrequired_groupZright_delimZright_delim_safeZsimplesimple_groupZsingle_symbol	snowflakespacesqrtstackrelstart_groupsubsuperZ
subsuperopr.   rr   tokenunknown_symbolvarsr   r3  ZsetNamer   r   suppressr	   list_space_widthsr   r  
_snowflaker   r#   r   ZleaveWhitespacer   _char_over_charsr   _accent_map_wide_accents_function_namesr   r  r   r
   
_fontnames_ambi_delim_left_delim_right_delimr   hasattrr  r  _expression_math_expression)r7   r  r   r   Zunicode_ranger0   r0   r1   r8     s   
"&"$$$"(




b


X@X&zParser.__init__c             C   s   |  |dd||g| _i | _y| j|}W nL tk
rx } z.tdd|jd|j	d  d t
|gW dd}~X Y nX d| _i | _| j  |d	 S )
z
        Parse expression *s* using the given *fonts_object* for
        output, at the given *fontsize* and *dpi*.

        Returns the parse tree of :class:`Node` instances.
        r   r   
r  r  rR   r  Nr   )State_state_stack_em_width_cacher  parseStringr   r,   rZ  linecolumnr  Z
resetCache)r7   r  Zfonts_objectrq   r   rh   errr0   r0   r1   parse	  s     
zParser.parsec               @   s:   e Zd ZdZdd Zdd Zdd Zdd	 ZeeeZ	d
S )zParser.Statez
        Stores the state of the parser.

        States are pushed and popped from a stack as necessary, and
        the "current" state is always at the top of the stack.
        c             C   s"   || _ || _|| _|| _|| _d S )N)rm  _fontr   rq   r   )r7   rm  r_   r   rq   r   r0   r0   r1   r8   	  s
    zParser.State.__init__c             C   s   t | j| j| j| j| jS )N)r  r  rm  r_   r   rq   r   )r7   r0   r0   r1   r  	  s    zParser.State.copyc             C   s   | j S )N)r%  )r7   r0   r0   r1   r   	  s    zParser.State._get_fontc             C   s   |dkr|| _ || _d S )N)r   r   r   )r   r%  )r7   r2  r0   r0   r1   	_set_font	  s    zParser.State._set_fontN)
rJ   rK   rL   rM   r8   r  r   r&  propertyr_   r0   r0   r0   r1   r  	  s   r  c             C   s
   | j d S )z?
        Get the current :class:`State` of the parser.
        rP  )r  )r7   r0   r0   r1   	get_state	  s    zParser.get_statec             C   s   | j   dS )z8
        Pop a :class:`State` off of the stack.
        N)r  pop)r7   r0   r0   r1   	pop_state	  s    zParser.pop_statec             C   s   | j |    dS )zm
        Push a new :class:`State` onto the stack which is just a copy
        of the current state.
        N)r  rz   r(  r  )r7   r0   r0   r1   
push_state
  s    zParser.push_statec             C   s
   t |gS )N)r  )r7   r  r  r  r0   r0   r1   r  
  s    zParser.mainc             C   s   | j |d dd S )Nr   rR   rP  )r  r   )r7   r  r  r  r0   r0   r1   r  
  s    zParser.math_stringc             C   s   t |}|   |gS )N)r  r*  )r7   r  r  r  hlistr0   r0   r1   r/   
  s    zParser.mathc                sF   |d  dd} fdd|D }t|}   td   _|gS )Nr   z\$r   c                s   g | ]}t |  d dqS )F)r/   )r}  r(  )r   r  )r7   r0   r1   r   
  s    z#Parser.non_math.<locals>.<listcomp>zmathtext.default)replacer  r+  r   r(  r_   )r7   r  r  r  Zsymbolsr,  r0   )r7   r1   r  
  s    zParser.non_mathc             C   sf   |   }|j|j|jf}| j|}|d krZ|j|jtd d|j|j}|j	}|| j|< t
|| S )Nzmathtext.defaultr  )r(  r_   rq   r   r  r   rm  r   r   r   r  )r7   Z
percentagern  r   r4   rZ   r0   r0   r1   _make_space 
  s    
zParser._make_spacegKqU?g0Bxq?g%?g1ZGU?g      ?gKqUſ)z\,z
\thinspacez\/z\>z\:z\;z\ z\enspacez\quadz\qquadz\!c             C   s.   t |dkst| j|d  }| |}|gS )NrR   r   )r   AssertionErrorr  r.  )r7   r  r  r  r{   rG   r0   r0   r1   r  8
  s    
zParser.spacec             C   s   |  t|d gS )Nr   )r.  r  )r7   r  r  r  r0   r0   r1   r  >
  s    zParser.customspacec             C   s  |d }yt ||  }W n$ tk
r>   t||d| Y nX || jkrtdd |d | d d d D d}|| jkrt|d |  dks|dks|| j	kr|gS t
| d|| dgd	d
gS n|| jkr|dkrBtdd |d | d d d D d}tdd ||d d  D d}|dkrB|dkrB|gS |dkrv||d   rv||d   rv|gS t
|| dgd	d
gS |gS )Nr   zUnknown symbol: %sc             s   s   | ]}|d kr|V  qdS )r  Nr0   )r   r  r0   r0   r1   	<genexpr>K
  s    z Parser.symbol.<locals>.<genexpr>rP  r  r   g?T)r  r  c             s   s   | ]}|d kr|V  qdS )r  Nr0   )r   r  r0   r0   r1   r0  Z
  s    c             s   s   | ]}|d kr|V  qdS )r  Nr0   )r   r  r0   r0   r1   r0  [
  s    rR   r   r  )r}  r(  r,   r   _spaced_symbolsrt  _binary_operatorsr   r!  r  r  r.  _punctuation_symbolsisdigit)r7   r  r  r  r  r  Z	prev_charZ	next_charr0   r0   r1   r.   A
  s6    
&
 



& .

zParser.symbolc             C   s   |d }t ||d| d S )Nr   zUnknown symbol: %s)r   )r7   r  r  r  r  r0   r0   r1   r  j
  s    zParser.unknown_symbolZAA))r   Ag      ?)Nz\circg      ?g        c             C   s  |d }|   }|j|j|j|j}| j|d\}}}	|d krJtd|	 }
|d d k	rh|d |
_|
 j|d 9  _t
|d |
}|	 }|d d k	r|d |_| j|d 9  _t|d |}t|j|j}t|g}||d t|g}||d t|td||	 |gS )Nr   )NNg        zError parsing symbolrS   rR   exactlyg        )r(  rm  r   r_   rq   r   r  r   r   r  r  r}  rV   r4   r  r  r  r{  )r7   r  r  r  r   rn  r  Z
under_descZ	over_descr  Z
over_stateZoverZunder_stateZunderr4   Zover_centeredZunder_centeredr0   r0   r1   r  u
  s4    



zParser.c_over_cz\circumflexaccentz\combiningbrevez\combiningoverlinez\combininggraveaccentz\combiningacuteaccentz\combiningtildez\combiningdotabovez\combiningdiaeresisz\combiningrightarrowabovez\rightarrowz
\leftarrowz\circ)ZhatZbreveZbarZgraveZacutetildedotZddotZvecr   `r  r  r  r  ZoverrightarrowZoverleftarrowmathringzwidehat widetilde widebarc                s    fddt D S )Nc                s&   g | ] t  fd dD r qS )c             3   s    | ]}  |o| kV  qd S )N)r3  )r   a)r  r0   r1   r0  
  s    z-Parser.<lambda>.<locals>.<listcomp>.<genexpr>)any)r   )am)r  r1   r   
  s    z#Parser.<lambda>.<locals>.<listcomp>)r#   )r=  r0   )r=  r1   <lambda>
  s    zParser.<lambda>c       
      C   s   t |dkst|  }|j|j|j|j}t |d dkrFtd|d \}}|| j	krtt
d| |j|td}nt| j| |}|dkr|  |  tt|jd |g}	|	|jd	 t|	td
|d t|ggS )NrR   r   rS   zError parsing accentr'   )r  r:  g      @r6  g        g       @)r   r/  r(  rm  r   r_   rq   r   r   r  r  r4   r  r  ru  r  r|  r  r  r{  r  )
r7   r  r  r  rn  r  r  r   Z
accent_boxZcenteredr0   r0   r1   r  
  s(    
zParser.accentc                sF   |    |   d _t fdd|d D }|   |d |_|S )Nr   c                s   g | ]}t | qS r0   )r}  )r   r  )rn  r0   r1   r   
  s    z#Parser.function.<locals>.<listcomp>r   )r+  r(  r_   r  r*  function_name)r7   r  r  r  r,  r0   )rn  r1   r  
  s    
zParser.functionc             C   sT   |    |  }d|_x(|d D ]}t|tr d|_|  q W |   t|d S )Nr   r   )r+  r(  r_   r4  r}  r~  r*  r  )r7   r  r  r  rn  r  r0   r0   r1   r   
  s    
zParser.operatornamec             C   s*   |    t|r&|d dd  |  _g S )Nr   r=  )r+  r   r(  r_   )r7   r  r  r  r0   r0   r1   r  
  s    zParser.start_groupc             C   s   t |d }|gS )Nr   )r  )r7   r  r  r  Zgrpr0   r0   r1   r  
  s    zParser.groupc             C   s   |    g S )N)r*  )r7   r  r  r  r0   r0   r1   r  
  s    zParser.end_groupc             C   s&   t |dkst|d }||  _g S )NrR   r   )r   r/  r(  r_   )r7   r  r  r  r2  r0   r0   r1   r_   
  s    
zParser.fontc             C   s:   t |tr|j| jkS t |tr6t|dr6|j| jkS dS )Nr?  F)r4  r}  r  _overunder_symbolsr  r  r?  _overunder_functions)r7   r  r0   r0   r1   is_overunder
  s
    
zParser.is_overunderc             C   s   t |tr|j| jkS dS )NF)r4  r}  r  _dropsub_symbols)r7   r  r0   r0   r1   
is_dropsub   s    
zParser.is_dropsubc             C   s   t |tr| S dS )NF)r4  r}  r  )r7   r  r0   r0   r1   r    s    
zParser.is_slantedc             C   s   dS )NFr0   )r7   r  r  r0   r0   r1   is_between_brackets
  s    zParser.is_between_bracketsc       %         s  t |dkstd }d }d }d}g }xX|d D ]L}	t|	trR|	dkrR|t |	7 }q.t|	trp|	jdkrp|d7 }q.||	 q.W |}t |dkr|sttd} nt |dkr|s|d S |d }nt |dkrt |dkr|d ntd}|dd  \}
}|
d	kr|}n|}nt |d
krt |dkr8|d ntd}|dd  \}}}}||krz|d	krrtdntd|d	kr|}|}n|}|}ntd| 	 }|j
|j|j|j}|j
|j|j|j}|r(|d krtg }x*t|D ]}|j| ||dg qW |  |  | |r4g }d}|j}|d k	r`|  t||j}|d k	r~|  t||j}|d k	rt|g}||d ||t|d g t|g}||d || |d k	rt|g}||d |t|d |g |j}t|}||j |_ t|g}|gS |}t|tr|j}t |rt|d trt!|d dr|d d }|d }t!|dr|j"j#|_t|dd}n t|tr|j"j#|_t|g}t$|}|j}d}| %|r|j}|j&| }|j&| }| '|rr||j&| 7 }||j(||d d   7 }| %|rnd|j& |j) | }d|j& |j) | }nd}|d krtt||g} |   | %|r||j*|  }!n
|j+| }!|!| _ ntt||g} |   | %|r||j*|  }"n
|j,| }"|d kr|" | _ ntt||g}#|#  | %|rH||j*|  }!n
|j-| }!d| |"| j |#j|!   }$|$dkr|"|$7 }"t| t|"| j |#j|!  |#g} |!| _ | %|s|  j|j.| 7  _t|| g}|gS )NrR   r   )r  r  r  g        )rS   rT   rT   r  )r=  r>  r>  zDouble subscriptzDouble superscriptzOSubscript/superscript sequence is too long. Use braces { } to remove ambiguity.z\primer6  g      @rP  r  F)r  g       @)/r   r/  r4  r  r}  r  rz   r|  r   r(  rm  r   r_   rq   r   r   r  rN  r  extendr.   r  r  rB  r4   ru  rV   r  r  r5   r  r6   r  r  r  r   rp  rD  rd  r  re  rf  r`  rb  ra  rc  r_  )%r7   r  r  r  r  r  rC  ZnapostrophesZnew_tokstokoprt  Zop1Znext1Zop2Znext2rn  Zrule_thicknessr   r   vlistr  r4   r,  rh   Z	last_charr  ro  Z	lc_heightZlc_baselineZ	superkernZsubkernr   Z
shift_downZshift_uprd   Zclr)rD  r0   r1   r	    s   
















	












zParser.subsuperc             C   s<  |   }|j|j|j|j}t|}|| jd krD|  |  t	|g}	t	|g}
t
|j|j}|	|d |
|d t|	td|d t||td|d |
g}|j|jtd d|j|j}|
j|j|j d |d   }||_t|t|d gg}|s|r8|d	krd
}|d	kr*d
}| |||S |S )Nr  r6  r   g       @zmathtext.default=rS   g      @r  r  )r(  rm  r   r_   rq   r   r  _math_style_dictru  r  rV   r4   r  r  r{  r  r   r   r5   r\   r^   r  r  r|  _auto_sized_delimiter)r7   ZldelimZrdelimZruleZstyler{   denrn  r  ZcnumZcdenr4   rK  rZ   r  rh   r0   r0   r1   _genfrac  s@    




zParser._genfracc             C   s6   t |dkstt |d dks$t| jt|d  S )NrR   r   rO  )r   r/  rP  tuple)r7   r  r  r  r0   r0   r1   r    s    zParser.genfracc             C   sh   t |dkstt |d dks$t|  }|j|j|j|j}|d \}}| dd|| j	d ||S )NrR   r   rS   r  r  )
r   r/  r(  rm  r   r_   rq   r   rP  rM  )r7   r  r  r  rn  r  r{   rO  r0   r0   r1   r    s    
zParser.fracc             C   sh   t |dkstt |d dks$t|  }|j|j|j|j}|d \}}| dd|| j	d ||S )NrR   r   rS   r  r  )
r   r/  r(  rm  r   r_   rq   r   rP  rM  )r7   r  r  r  rn  r  r{   rO  r0   r0   r1   r    s    
zParser.dfracc             C   sJ   t |dkstt |d dks$t|d \}}| ddd| jd ||S )NrR   r   rS   r  g        r  )r   r/  rP  rM  )r7   r  r  r  r{   rO  r0   r0   r1   r    s
    
zParser.stackrelc             C   sJ   t |dkstt |d dks$t|d \}}| ddd| jd ||S )NrR   r   rS   r   r   g        r  )r   r/  rP  rM  )r7   r  r  r  r{   rO  r0   r0   r1   r    s
    
zParser.binomc                sD  |d \}}|     j j j j}|j|j |d  }|j|j }t	d|| dd}	|	j|	j }|	j|	j }t
t|d |t|d g}
tt t |
g}|| j j d  d| |d krt|	jd	 d
d
}n&t
 fdd|D }|  |  tt
|gg}| d |_t
|t|	j d	 |	|g}|gS )Nr   g      @z	\__sqrt__T)r  g       @g     @r6  g      ?g        c                s   g | ]}t | qS r0   )r}  )r   r   )rn  r0   r1   r   ?  s    zParser.sqrt.<locals>.<listcomp>g333333?)r(  rm  r   r_   rq   r   r5   r  r6   r  r  r|  r  r  r  r  rw  r4   ru  r  )r7   r  r  r  rootbodyr  r5   r6   ZcheckZpadded_body	rightsideZ
root_vlistr,  r0   )rn  r1   r  !  s:    zParser.sqrtc             C   s   t |dkstt |d dks$t|d d }|  }|j|j|j|j}|j|j	 |d  }|j
|j	 }tt|t t|gg}	|	||j|j d  d| t|	g}
|
gS )NrR   r   g      @g     @r6  )r   r/  r(  rm  r   r_   rq   r   r5   r  r6   r  r  r  r  r  )r7   r  r  r  rS  rn  r  r5   r6   rT  r,  r0   r0   r1   r  M  s    
zParser.overlinec       
   	   C   s   |   }t|r:tdd |D }tdd |D }d }nd}d}d}g }|dkrj|t|||||d || |dkr|t|||||d t|}	|	S )Nc             s   s   | ]}|j V  qd S )N)r5   )r   r   r0   r0   r1   r0  i  s    z/Parser._auto_sized_delimiter.<locals>.<genexpr>c             s   s   | ]}|j V  qd S )N)r6   )r   r   r0   r0   r1   r0  j  s    r   g      ?r  )r  )r(  r   rV   rz   r  rH  r  )
r7   frontmiddlebackrn  r5   r6   r  partsr,  r0   r0   r1   rN  f  s     
zParser._auto_sized_delimiterc             C   s   |\}}}|  || |S )N)rN  ZasList)r7   r  r  r  rU  rV  rW  r0   r0   r1   r  z  s    
zParser.auto_delim)ErJ   rK   rL   rM   rJ  rM  r   r!  r2  Z_relation_symbolsZ_arrow_symbolsr1  r3  r@  rA  rC  r  r  r  r  r  r8   r$  objectr  r(  r*  r+  r  r  r/   r  r.  r  r  r  r.   r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r_   rB  rD  r  rE  r	  rP  r  r  r  r  r  r  r  rN  r  rE  r0   r0   )rD  r1   r    s   







 V	'&
	 =*,r  c            	   @   s|   e Zd ZdZeeeeee	e
edZeeeeeedZdd Zedddd	ZdddZdddZdddZdddZdS )MathTextParserN)bitmapZaggru   ZpdfZsvgr   ZcairoZmacosx)cmZdejavuserifZ
dejavusansZstixZstixsansZcustomc             C   s   |  | _dS )zI
        Create a MathTextParser for the given backend *output*.
        N)r   _output)r7   outputr0   r0   r1   r8     s    zMathTextParser.__init__2   H   c       
      C   s   |dkrt  }| jdkr*td r*t|}nB| j| j  }td }| j| }|dk	rd|||}ntd|	 }| j
dkrt | j_
| j
||||}	||	j|	j|	j ||	S )a  
        Parse the given math expression *s* at the given *dpi*.  If
        *prop* is provided, it is a
        :class:`~matplotlib.font_manager.FontProperties` object
        specifying the "default" font to use in the math expression,
        used for all non-math text.

        The results are cached, so multiple calls to :meth:`parse`
        with the same expression should be fast.
        Nru   z	ps.useafmzmathtext.fontsetzbmathtext.fontset must be either 'cm', 'dejavuserif', 'dejavusans', 'stix', 'stixsans', or 'custom')r   r]  r   rS  _backend_mapping_font_type_mappingr   r   r,   Zget_size_in_points_parserr  rD  r$  r<   r4   r5   r6   rH   )
r7   r  r   r&  rm  ZbackendZfontsetZfontset_classrq   rG   r0   r0   r1   r$    s"    


zMathTextParser.parsex      c             C   s<   | j dkstt|d}| j|||d\}}| }||fS )a  
        *texstr*
            A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'

        *dpi*
            The dots-per-inch to render the text

        *fontsize*
            The font size in points

        Returns a tuple (*array*, *depth*)

          - *array* is an NxM uint8 alpha ubyte mask array of
            rasterized tex.

          - depth is the offset of the baseline from the bottom of the
            image in pixels.
        r[  )rr  )r   r&  )r]  r/  r   r$  Zas_array)r7   texstrr   rq   r&  ftimager6   r   r0   r0   r1   to_mask  s
    
zMathTextParser.to_maskblackc             C   s   | j |||d\}}t|\}}}	}
tj|jd |jd dftjd}d| |dddddf< d| |dddddf< d|	 |dddddf< ||ddddd	f< ||fS )
a  
        *texstr*
            A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'

        *color*
            Any matplotlib color argument

        *dpi*
            The dots-per-inch to render the text

        *fontsize*
            The font size in points

        Returns a tuple (*array*, *depth*)

          - *array* is an NxM uint8 alpha ubyte mask array of
            rasterized tex.

          - depth is the offset of the baseline from the bottom of the
            image in pixels.
        )r   rq   r   rR   r=  )Zdtype   NrS   rT   )rh  mcolorsto_rgbarX   ZzerosshapeZuint8)r7   rf  colorr   rq   r   r6   r  r  r  r;  ZRGBAr0   r0   r1   rl    s    "zMathTextParser.to_rgbac             C   s&   | j ||||d\}}t|| |S )a;  
        Writes a tex expression to a PNG file.

        Returns the offset of the baseline from the bottom of the
        image in pixels.

        *filename*
            A writable filename or fileobject

        *texstr*
            A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'

        *color*
            A valid matplotlib color argument

        *dpi*
            The dots-per-inch to render the text

        *fontsize*
            The font size in points

        Returns the offset of the baseline from the bottom of the
        image in pixels.
        )rn  r   rq   )rl  r   Z	write_png)r7   r|   rf  rn  r   rq   Zrgbar6   r0   r0   r1   to_png  s    zMathTextParser.to_pngc             C   s0   | j dkstt|d}| j|||d\}}|S )a.  
        Returns the offset of the baseline from the bottom of the
        image in pixels.

        *texstr*
            A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'

        *dpi*
            The dots-per-inch to render the text

        *fontsize*
            The font size in points
        r[  )rr  )r   r&  )r]  r/  r   r$  )r7   rf  r   rq   r&  rg  r6   r0   r0   r1   	get_depth   s    
zMathTextParser.get_depth)r`  N)rd  re  )ri  rd  re  )ri  rd  re  )rd  re  )rJ   rK   rL   rc  rk   rN   rl   rv   r}   r   r   ra  r   r?  rF  r   r@  r$  rb  r8   	functools	lru_cacher$  rh  rl  ro  rp  r0   r0   r0   r1   rZ    s,   '

 
rZ  c             C   s   ddl m} ddlm} |dkr&t }td}|j| d|d\}}	}
}}|j|d |	d fd	}|jd|
|	 | |d
 |	| |j
|||d |
S )a  
    Given a math expression, renders it in a closely-clipped bounding
    box to an image file.

    *s*
       A math expression.  The math portion should be enclosed in
       dollar signs.

    *filename_or_obj*
       A filepath or writable file-like object to write the image data
       to.

    *prop*
       If provided, a FontProperties() object describing the size and
       style of the text.

    *dpi*
       Override the output dpi, otherwise use the default associated
       with the output format.

    *format*
       The output format, e.g., 'svg', 'pdf', 'ps' or 'png'.  If not
       provided, will be deduced from the filename.
    r   )figure)ri   Nr   r`  )r   r&  g      R@)Zfigsize)Zfontproperties)r   r-   )
matplotlibrs  rj   ri   r   rZ  r$  ZFiguretextZFigureCanvasAggZsavefig)r  Zfilename_or_objr&  r   r-   rs  ri   parserr4   r5   r6   r  Zfigr0   r0   r1   math_to_image3  s    
rw  )T)NNN)|rM   rq  ior   r   r   r0  r-  ZnumpyrX   Z	pyparsingr   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   ZenablePackratrt  r   r   r   rk  r   r   Zmatplotlib.afmr   Zmatplotlib.cbookr   Zmatplotlib.ft2fontr   r   r   Zmatplotlib.font_managerr   r   r    Zmatplotlib._mathtext_datar!   r"   r#   r$   r%   r2   Z
deprecatedr   Zunichr_saferY  r3   rN   rk   rl   rv   r}   r   r   r   r   r   r$  r7  r?  rF  r   r@  rS  ry  rz  rx  r^  rg  rh  ri  rj  rk  rl  rp  Warningr/  rq  rw  r{  r|  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rf   r  r  rZ  rw  r0   r0   r0   r1   <module>   s   L
6J(  ips+w 2$	N>oJ	!	%        q 0