ó
±éRc           @   sÓ  d  Z  d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z y d d l m Z Wn! e	 k
 r… d d l m Z n Xd d l
 Z
 d d l Z d d l m Z d d l m Z d d l m Z e
 j d ƒ y: d d l m Z m Z d d	 l m Z d d
 l m Z Wn e	 k
 r4e	 d ƒ ‚ n Xe d ƒ \ Z Z Z d „  Z d e f d „  ƒ  YZ  d e f d „  ƒ  YZ! d „  Z" d „  Z# e$ d k rÏe j% j& d ƒ rÀe j' d ƒ n  e# ƒ  d GHn  d S(   s&  Sphinx directive to support embedded IPython code.

This directive allows pasting of entire interactive IPython sessions, prompts
and all, and their code will actually get re-executed at doc build time, with
all prompts renumbered sequentially. It also allows you to input code as a pure
python input by giving the argument python to the directive. The output looks
like an interactive ipython section.

To enable this directive, simply list it in your Sphinx ``conf.py`` file
(making sure the directory where you placed it is visible to sphinx, as is
needed for all Sphinx directives).

By default this directive assumes that your prompts are unchanged IPython ones,
but this can be customized. The configurable options that can be placed in
conf.py are

ipython_savefig_dir:
    The directory in which to save the figures. This is relative to the
    Sphinx source directory. The default is `html_static_path`.
ipython_rgxin:
    The compiled regular expression to denote the start of IPython input
    lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You
    shouldn't need to change this.
ipython_rgxout:
    The compiled regular expression to denote the start of IPython output
    lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You
    shouldn't need to change this.
ipython_promptin:
    The string to represent the IPython input prompt in the generated ReST.
    The default is 'In [%d]:'. This expects that the line numbers are used
    in the prompt.
ipython_promptout:

    The string to represent the IPython prompt in the generated ReST. The
    default is 'Out [%d]:'. This expects that the line numbers are used
    in the prompt.

ToDo
----

- Turn the ad-hoc test() function into a real test suite.
- Break up ipython-specific functionality from matplotlib stuff into better
  separated code.

Authors
-------

- John D Hunter: orignal author.
- Fernando Perez: refactoring, documentation, cleanups, port to 0.11.
- VÃ¡clavÅ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
- Skipper Seabold, refactoring, cleanups, pure python addition
iÿÿÿÿN(   t   md5(   t
   directives(   t   nodes(   t	   Directivet   Agg(   t   Configt   InteractiveShell(   t
   ProfileDir(   t   iosr   Unable to import the necessary objects from IPython. You may need to install or upgrade your IPython installation.i   c         C   sI  g  } |  j  d ƒ } t | ƒ } d } d
 }	 x| | k r@ Pn  | | }
 | d 7} |
 j ƒ  } | j d ƒ rˆ | j t |
 f ƒ q0 n  | j d ƒ r£ | }	 q0 n  | j |
 ƒ } | rÄt | j	 d ƒ ƒ | j	 d ƒ } } d d j
 d	 g t t | ƒ ƒ d ƒ } t | ƒ } g  } x} | | k  r˜| | } | j | ƒ } | sV| j d ƒ rZPn1 | j | ƒ r~| d | | 7} n | j | ƒ | d 7} qW| j t |	 | d j
 | ƒ f f ƒ q0 n  | j |
 ƒ } | r0 t | j	 d ƒ ƒ | j	 d ƒ } } | | d k  r+d j
 | g | | ƒ } n  | j t | f ƒ Pq0 q0 | S(   s”  
    part is a string of ipython text, comprised of at most one
    input, one ouput, comments, and blank lines.  The block parser
    parses the text into a list of::

      blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]

    where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
    data is, depending on the type of token::

      COMMENT : the comment string

      INPUT: the (DECORATOR, INPUT_LINE, REST) where
         DECORATOR: the input decorator (or None)
         INPUT_LINE: the input as string (possibly multi-line)
         REST : any stdout generated by the input line (not OUTPUT)


      OUTPUT: the output string, possibly multi-line
    s   
i    i   t   #t   @i   s      %s:t    t   .N(   t   splitt   lent   Nonet   stript
   startswitht   appendt   COMMENTt   matcht   intt   groupt   joint   strt   INPUTt   OUTPUT(   t   partt   rgxint   rgxoutt   fmtint   fmtoutt   blockt   linest   Nt   it	   decoratort   linet   line_strippedt   matchint   linenot	   inputlinet   continuationt   Nct   restt   nextlinet   matchoutt   output(    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   block_parserf   sT    

%*
%%t   EmbeddedSphinxShellc           B   st   e  Z d  Z d „  Z d „  Z e d „ Z d „  Z d „  Z d „  Z	 d „  Z
 d „  Z d	 „  Z d
 „  Z d „  Z RS(   s1   An embedded IPython instance to run inside Sphinxc         C   s'  t  j ƒ  |  _ t ƒ  } t | j _ d d g | j _ t | j _	 t | j _
 d | j _ t j d d ƒ } d } t j j | | ƒ } t j | ƒ } t j d | d | ƒ } |  j t _ |  j t _ | |  _ |  j j |  _ |  j j |  _ d	 |  _ d	 |  _ t |  _ t |  _ t |  _ t |  _ d  S(
   Ns   import numpy as nps   from pylab import *t   NoColort   prefixt   profile_t   auto_profile_sphinx_buildt   configt   profile_dirR   (    t	   cStringIOt   StringIOt   coutR   t   Falset   Globalt   display_bannert
   exec_linesR   t   autocallt
   autoindentt   colorst   tempfilet   mkdtempt   ost   pathR   R   t   create_profile_dirt   instanceR   t   stdoutt   stderrt   IPt   user_nst   user_global_nst   inputR/   t   is_verbatimt
   is_doctestt   is_suppresst   _pyplot_imported(   t   selfR6   t   tmp_profile_dirt   profnamet   pdirt   profileRJ   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   __init__Ç   s0    							c         C   s$   |  j  j d ƒ |  j  j d ƒ d  S(   Ni    (   R:   t   seekt   truncate(   RR   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt
   clear_cout÷   s    c         C   s~   t  j } |  j j } zX |  j t  _ | j | ƒ | j ƒ  } | sl | j ƒ  d } |  j j | d | ƒn  Wd | t  _ Xd S(   s#   process the input, capturing stdouti   t   store_historyN(	   t   sysRH   RJ   t   input_splitterR:   t   pusht   push_accepts_moret   source_raw_resett   run_cell(   RR   R%   R[   RH   t   splittert   moret
   source_raw(    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   process_input_lineû   s    	c         C   sà   |  j  } |  j } | j d ƒ } | d } t j j t j j | | ƒ | ƒ } d | g } xV | d D]J } | j d ƒ \ }	 }
 |	 j ƒ  }	 |
 j ƒ  }
 | j d |	 |
 f ƒ qg Wt j j	 | ƒ } d j | ƒ } | | f S(   s¿   
        # build out an image directive like
        # .. image:: somefile.png
        #    :width 4in
        #
        # from an input like
        # savefig somefile.png width=4in
        t    i   s   .. image:: %si   t   =s
      :%s: %ss   
(
   t   savefig_dirt
   source_dirR   RD   RE   t   relpathR   R   R   t   basename(   RR   R$   Rh   Ri   t   saveargst   filenamet   outfilet	   imagerowst   kwargt   argt   valt
   image_filet   image_directive(    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   process_image
  s    			
	c         C   s’  | \ } } } d } d } | d k p- |  j }	 | d k pB |  j }
 | d k pW |  j } | d k	 or | j d ƒ } | j d ƒ } t | ƒ d k r¹ | d d k r¹ | j d ƒ q¹ n  d	 d j d
 g t t	 | ƒ ƒ d ƒ } t | ƒ } | r|  j
 | ƒ \ } } n  g  } t } xÎ t | ƒ D]À \ } } | j d ƒ rJt } n  | d k r¤|	 r~|  j d ƒ |  j j d 7_ n |  j | d t ƒd | | f } n, |	 sÀ|  j | d t ƒn  d | | f } | s&| j | ƒ q&q&W| rt | j ƒ  ƒ r|	 r| j | ƒ n  |  j j d ƒ |  j j ƒ  } | rV| rV| j | ƒ n | rl| j d ƒ n  |  j j d ƒ | | | |
 | | f S(   s#   Process data block for INPUT token.s	   @verbatims   @doctests	   @suppresss   @savefigs   
i   iÿÿÿÿR   s      %s:R   i   t   ;i    R[   s   %s %sN(   R   RN   RO   RP   R   R   R   R   R   R   Ru   R;   t	   enumeratet   endswitht   TrueRe   RJ   t   execution_countR   R:   RX   t   readRY   (   RR   t   datat   input_promptR(   R$   RM   R,   Rs   Rt   RN   RO   RP   t
   is_savefigt   input_linesR*   R+   t   rett   is_semicolonR#   R%   t   formatted_lineR/   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   process_input)  sV    *	c         C   s¸   | r´ | j  ƒ  } | } | d k	 r´ | j  ƒ  } | j | ƒ }	 |	 d k  rj d | | f }
 t |
 ƒ ‚ n  | t | ƒ j  ƒ  } | | k r± d | | | f }
 t |
 ƒ ‚ q± q´ n  d S(   s$   Process data block for OUTPUT token.i    s-   output prompt="%s" does not match out line=%ssU   doctest failure for input_lines="%s" with found_output="%s" and submitted output="%s"N(   R   R   t   findt   RuntimeErrorR   (   RR   R|   t   output_promptR   R/   RO   Rs   t	   submittedt   foundt   indt   e(    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   process_outputm  s    c         C   s   |  j  s | g Sd S(   s'   Process data fPblock for COMMENT token.N(   RP   (   RR   R|   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   process_commentŠ  s    	c         C   s�   |  j  ƒ  d | } |  j d d t ƒ|  j d d t ƒ|  j | d t ƒ|  j d d t ƒ|  j d d t ƒ|  j ƒ  d S(   s/   
        Saves the image file to disk.
        s   plt.gcf().savefig("%s")s   bookmark ipy_thisdirR[   s   cd -b ipy_savedirs   cd -b ipy_thisdirs   bookmark -d ipy_thisdirN(   t   ensure_pyplotRe   R;   RZ   (   RR   Rs   t   command(    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt
   save_image�  s    

c         C   s  g  } d } d } |  j j } |  j | } |  j | } d } d }	 x« | D]£ \ }
 } |
 t k ru |  j | ƒ } nc |
 t k r« |  j | | | ƒ \ } } } } } }	 n- |
 t	 k rØ |  j
 | | | | | | ƒ } n  | rK | j | ƒ qK qK W| d k	 r|  j | ƒ n  | |	 f S(   sZ   
        process block from the block_parser and return a list of processed lines
        N(   R   RJ   Rz   t   promptint	   promptoutR   RŒ   R   Rƒ   R   R‹   t   extendR�   (   RR   R    R€   R/   R   R(   R}   R†   Rs   Rt   t   tokenR|   t   out_dataRO   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   process_blockž  s,    *	c         C   s$   |  j  r d  S|  j d d t ƒd  S(   Ns   import matplotlib.pyplot as pltR[   (   RQ   Re   R;   (   RR   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyR�   Á  s    	c         C   sa  g  } t  } t  } d } |  j } d } x3t | ƒ D]%\ } }	 |	 j ƒ  }
 t |	 ƒ sk | j |	 ƒ q4 n  |
 j d ƒ r¥ | j |	 g ƒ d |	 k r4 t	 } q4 q4 n  |
 j d ƒ rÊ | j |	 g ƒ q4 n  d d j
 d g t t | ƒ ƒ d ƒ } | sfd	 | | |
 f } | j | ƒ | d
 7} y t j |
 ƒ | j d ƒ Wq#t k
 rbt	 } | } q#Xn½ d	 | |	 f } | j | ƒ yŒ t j d j
 | | | d
 !ƒ ƒ } t | j d t j ƒ rûxI | j d j D]! } t | t j ƒ rÓt  } qÓqÓWn | j d ƒ t  } Wn t k
 r"n X| r4 |  j ƒ  |  j d d t  ƒ|  j ƒ  t  } q4 q4 W| S(   s  
        content is a list of strings. it is unedited directive conent

        This runs it line by line in the InteractiveShell, prepends
        prompts as needed capturing stderr and stdout, then returns
        the content as a list as if it were ipython code
        i    R
   t   savefigR	   u      %s:R   R   i   u   %s %si   u    s   
s	   plt.clf()R[   N(   R;   R   R�   Rw   R   R   R   R   R’   Ry   R   R   t   astt   parset	   Exceptiont
   isinstancet   bodyt   FunctionDeft   ReturnR�   Re   RZ   (   RR   t   contentR/   R–   t	   multilinet   multiline_startR   t   ctR(   R%   R&   R*   t   modifiedt   modt   element(    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   process_pure_pythonÇ  sb    		*



(   t   __name__t
   __module__t   __doc__RW   RZ   Ry   Re   Ru   Rƒ   R‹   RŒ   R�   R•   R�   R¥   (    (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyR1   Ä   s   	0			D				#	t   IpythonDirectivec           B   s{   e  Z e Z d  Z d Z e Z i e j d 6e j	 d 6e j	 d 6e j	 d 6Z
 e ƒ  Z d „  Z d „  Z d „  Z d	 „  Z RS(
   i    i   t   pythont   suppresst   verbatimt   doctestc   	      C   sÔ   |  j  j j j j } |  j  j j j j j } | j } t j	 j
 |  j  j j ƒ } | d  k ri | j } n  t | t ƒ r… | d } n  t j	 j | | ƒ } | j } | j } | j } | j } | | | | | | f S(   Ni    (   t   statet   documentt   settingst   envR6   t   appt   confdirt   ipython_savefig_dirRD   RE   t   dirnamet   current_sourceR   t   html_static_pathRš   t   listR   t   ipython_rgxint   ipython_rgxoutt   ipython_promptint   ipython_promptout(	   RR   R6   R³   Rh   Ri   R   R   R�   R‘   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   get_config_options  s    					c         C   sº  g  t  j t j ƒ D] } | j d ƒ r | ^ q } | r® t  j j t j | d ƒ } t | ƒ j ƒ  j	 d ƒ } |  j
 j j | k r´ |  j j j j ƒ  d |  j j _ q´ n g  } |  j ƒ  \ } } } } }	 }
 | |  j _ | |  j _ |	 |  j _ |
 |  j _ | |  j _ | |  j _ |  j j d | d t ƒ|  j j ƒ  |  j
 j j | k rªt j d d d t ƒ \ } } t | d	 ƒ } | j |  j
 j j d ƒ | j ƒ  n  | | |	 |
 f S(
   Nt   seen_doci    s   
i   s   bookmark ipy_savedir %sR[   R3   t   textt   a(    RD   t   listdirRB   t   tempdirR   RE   R   t   openR{   R   R®   R¯   R¶   t   shellRJ   t   history_managert   resetRz   R½   R   R   R�   R‘   Rh   Ri   Re   R;   RZ   t   mkstempRy   t   writet   close(   RR   R#   t	   seen_docst   fnamet   docsRh   Ri   R   R   R�   R‘   t   fdt   fout(    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   setup3  s2    c         C   s'   |  j  j d d t ƒ|  j  j ƒ  d  S(   Ns   bookmark -d ipy_savedirR[   (   RÄ   Re   R;   RZ   (   RR   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   teardown_  s    c         C   s,  t  } |  j ƒ  \ } } } } |  j } d | k |  j _ d | k |  j _ d | k |  j _ d |  j k r� |  j } |  j j	 | ƒ |  _ n  d j
 |  j ƒ j d ƒ } d d g }	 g  }
 x§ | D]Ÿ } t | | | | | ƒ } t | ƒ rÁ |  j j | ƒ \ } } x; | D]3 } |	 j g  | j d ƒ D] } d	 | ^ q&ƒ q
W| d  k	 r`|
 j | ƒ q`qÁ qÁ Wx> |
 D]6 } |	 j d ƒ |	 j | j d ƒ ƒ |	 j d ƒ qkWt |	 ƒ d
 k ró| rÎd j
 |	 ƒ GHqó|  j j |	 |  j j j d ƒ ƒ n  d j
 |	 ƒ } t j | | ƒ } d | d <|  j ƒ  g  S(   NR«   R­   R¬   Rª   s   
s   

s   .. code-block:: ipythonR   s      %si   i    t   ipythont   language(   R;   RÏ   t   optionsRÄ   RP   RO   RN   t	   argumentsRž   R¥   R   R   R0   R   R•   R’   R   R   t   state_machinet   insert_inputR   t   sourceR   t   literal_blockRÐ   (   RR   t   debugR   R   R�   R‘   RÓ   Rž   t   partsR!   t   figuresR   R    t   rowst   figuret   rowR%   R¿   t   txtnode(    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   rune  sD    		1	

(   R¦   R§   Ry   t   has_contentt   required_argumentst   optional_argumentst   final_argumuent_whitespaceR   t	   unchangedt   flagt   option_specR1   RÄ   R½   RÏ   RÐ   Rà   (    (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyR©     s   

			,	c         C   sŽ   |  t  _ |  j d t ƒ |  j d d  t ƒ |  j d t j d ƒ t ƒ |  j d t j d ƒ t ƒ |  j d d t ƒ |  j d	 d
 t ƒ d  S(   NRÑ   R´   R¹   s   In \[(\d+)\]:\s?(.*)\s*Rº   s   Out\[(\d+)\]:\s?(.*)\s*R»   s   In [%d]:R¼   s   Out[%d]:(	   RÏ   R²   t   add_directiveR©   t   add_config_valueR   Ry   t   ret   compile(   R²   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyRÏ   ¤  s    			c          C   s�   d d d d d d d d g }  |  d	 }  t  ƒ  } xW |  D]O } | j d
 ƒ } t d d d  d | d | d d d d  d d  d d  d d  ƒq8 Wd  S(   Ns6  
In [9]: pwd
Out[9]: '/home/jdhunter/py4science/book'

In [10]: cd bookdata/
/home/jdhunter/py4science/book/bookdata

In [2]: from pylab import *

In [2]: ion()

In [3]: im = imread('stinkbug.png')

@savefig mystinkbug.png width=4in
In [4]: imshow(im)
Out[4]: <matplotlib.image.AxesImage object at 0x39ea850>

s´   

In [1]: x = 'hello world'

# string methods can be
# used to alter the string
@doctest
In [2]: x.upper()
Out[2]: 'HELLO WORLD'

@verbatim
In [3]: x.st<TAB>
x.startswith  x.strip
s6  

In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
   .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'

In [131]: print url.split('&')
['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']

In [60]: import urllib

sä  \

In [133]: import numpy.random

@suppress
In [134]: numpy.random.seed(2358)

@doctest
In [135]: numpy.random.rand(10,2)
Out[135]:
array([[ 0.64524308,  0.59943846],
       [ 0.47102322,  0.8715456 ],
       [ 0.29370834,  0.74776844],
       [ 0.99539577,  0.1313423 ],
       [ 0.16250302,  0.21103583],
       [ 0.81626524,  0.1312433 ],
       [ 0.67338089,  0.72302393],
       [ 0.7566368 ,  0.07033696],
       [ 0.22591016,  0.77731835],
       [ 0.0072729 ,  0.34273127]])

st   
In [106]: print x
jdh

In [109]: for i in range(10):
   .....:     print i
   .....:
   .....:
0
1
2
3
4
5
6
7
8
9
sü   

In [144]: from pylab import *

In [145]: ion()

# use a semicolon to suppress the output
@savefig test_hist.png width=4in
In [151]: hist(np.random.randn(10000), 100);


@savefig test_plot.png width=4in
In [151]: plot(np.random.randn(10000), 'o');
   sÌ   
# use a semicolon to suppress the output
In [151]: plt.clf()

@savefig plot_simple.png width=4in
In [151]: plot([1,2,3])

@savefig hist_simple.png width=4in
In [151]: hist(np.random.randn(10000), 100);

s™   
# update the current fig
In [151]: ylabel('number')

In [152]: title('normal distribution')


@savefig hist_with_text.png
In [153]: grid(True)

        i   s   
RÙ   RÔ   RÓ   Rž   R(   i    t   content_offsett
   block_textR®   RÕ   (   t   dictR   t   ipython_directiveR   (   t   examplesRÓ   t   exampleRž   (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   test²  s     	
	t   __main__t   _statics!   All OK? Check figures in _static/((   R¨   R8   RD   Rê   R\   RB   R—   t   hashlibR    t   ImportErrort
   matplotlibt   sphinxt   docutils.parsers.rstR   t   docutilsR   t   sphinx.util.compatR   t   uset   IPythonR   R   t   IPython.core.profiledirR   t   IPython.utilsR   t   rangeR   R   R   R0   t   objectR1   R©   RÏ   Rò   R¦   RE   t   isdirt   mkdir(    (    (    s`   /opt/xtal/ccp4-6.5-linux32/lib/python2.7/site-packages/matplotlib/sphinxext/ipython_directive.pyt   <module>5   sF   	^ÿ L•		Ž