a
    <bqY                     @   sv   d Z ddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ dd	 Zd
d Zdd ZdZdddZdS )z7Tools for setting up printing in interactive sessions.     )version_tuple)BytesIO)latex)preview)debug)	Printablec                    s*   ddl }ddl  fdd}||_dS )z.Setup printing in Python interactive session. r   Nc                    s,   | dur(d _ t| fi  |  _ dS )zPython's pretty-printer display hook.

           This function was adapted from:

            http://www.python.org/dev/peps/pep-0217/

        N)_print)argbuiltinssettingsstringify_func j/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/sympy/interactive/printing.py_displayhook   s    z+_init_python_printing.<locals>._displayhook)sysr   displayhook)r   r   r   r   r   r   r   _init_python_printing   s    r   c                    s  zddl m
 W n ty"   Y n0 du r`| j }|dkrDdn|dkrRdndtd	 d
|rnd}nd}|dkr|d  }||f d}d}td }d||||f }| d }dd|gtd td td |	pt	 fdd}fddfdd
fdd d!fd"d#	fd$d%}	fd&d'}fd(d)}	fd*d+}fd,d-}ddl
 t jtd.krtttttttg}| jjd/ }|tg D ]}||| q| jjd0 }|d1v r<td2 |D ]}||| q |t_n4td3 |D ]}||jv rH|j| qHtjt_| jjd4 }|d5v rtd6 |D ]}||| q|t_nf|d7krtd8 |D ]}||| q|t_n4td9 |D ]}||jv r|j| qtjt_| jjd: }|d;v rRtd< |D ]}||| q6|t_n4td= |D ]}||jv r^|j| q^tjt_n| d>| dS )?z/Setup printing in IPython interactive session. r   )latex_to_pngNZlightbgZBlacklinuxWhiteZGrayz*init_printing: Automatic foreground color:zW\documentclass[varwidth,%s]{standalone}
\usepackage{amsmath,amsfonts}%s\begin{document}z\usepackage{euler} svgz
\special{color %s}Ztightz0cm,0cm   z-T %s -D %d -bg %s -fg %s -O %sg @z
--no-fontsz
--scale={}zinit_printing: DVIOPTIONS:zinit_printing: DVIOPTIONS_SVG:zinit_printing: PREAMBLE:c                    s0   | r| |  n|  jj|  dS )z*caller for pretty, for use in IPython 0.11N)textlibpretty)r
   pcycle)IPython
_can_printr   r   r   _print_plainV   s    z,_init_ipython_printing.<locals>._print_plainc              
      s^   t  }zt| dd| d W n6 tyT } ztddt|  W Y d }~n
d }~0 0 | S )Npngr   outputZviewerZoutputbufferpreamble
dvioptionszpng printing:"_preview_wrapper exception raised:)r   r   	Exceptionr   reprgetvalueoZ
exprbuffere)r'   r&   r   r   _preview_wrapper]   s    
z0_init_ipython_printing.<locals>._preview_wrapperc              
      sd   t  }zt| dd| d W n6 tyT } ztddt|  W Y d }~n
d }~0 0 | dS )Nr   r   r$   zsvg printing:r(   zutf-8)r   r   r)   r   r*   r+   decoder,   )dvioptions_svgr&   r   r   _svg_wrapperj   s    
z,_init_ipython_printing.<locals>._svg_wrapperc              
      sn   z4z|  dW W S  t y0   |  Y W S 0 W n4 tyh } ztdt| W Y d }~d S d }~0 0 d S )N)colorscalezmatplotlib exception caught:)	TypeError
ValueErrorr   r*   )r-   r.   )	forecolorr   r4   r   r   _matplotlib_wrapperw   s    z3_init_ipython_printing.<locals>._matplotlib_wrapper)Z_latexZ	_sympystrZ_prettyZ
_sympyreprc                    s   zt tttf}t |rft jdd |D vsHt jdd |D vrNW dS tfdd D W S t t	rt fdd D W S t t
rW dS t trW dS t fddD rW dS t ttfrވrW dS W dS  t y   Y dS 0 d	S )
zReturn True if type o can be printed with one of the SymPy printers.

        If o is a container type, this is True if and only if every element of
        o can be printed in this way.
        c                 s   s   | ]}|j V  qd S N)__str__.0ir   r   r   	<genexpr>       z=_init_ipython_printing.<locals>._can_print.<locals>.<genexpr>c                 s   s   | ]}|j V  qd S r9   )__repr__r;   r   r   r   r>      r?   Fc                 3   s   | ]} |V  qd S r9   r   r;   )r!   r   r   r>      r?   c                 3   s"   | ]} |o | V  qd S r9   r   r;   )r!   r-   r   r   r>      r?   Tc                 3   s   | ]}t  |V  qd S r9   )hasattr)r<   hookr-   r   r   r>      r?   N)listtupleset	frozenset
isinstancetyper:   r@   alldictboolr   anyfloatintRuntimeError)r-   Zbuiltin_types)r!   print_builtinprinting_hooksrC   r   r!      s*    



z*_init_ipython_printing.<locals>._can_printc              
      s    | r| fdi}dkr,d| }z
|W S  t y } z@tdt|d dkrr| fddi}|W  Y d}~S d}~0 0 dS )z
        A function that returns a png rendered by an external latex
        distribution, falling back to matplotlib rendering
        modeplain$\displaystyle %s$preview failed with:z# Falling back to matplotlib backendinlineNrP   r   r*   r-   sr.   )r!   r8   r/   r   
latex_moder   r   r   _print_latex_png   s    

z0_init_ipython_printing.<locals>._print_latex_pngc              
      sp    | rl| fdi}dkr,d| }z
|W S  t yj } ztdt|d W Y d}~n
d}~0 0 dS )zz
        A function that returns a svg rendered by an external latex
        distribution, no fallback available.
        rS   rT   rU   rV   z No fallback available.NrX   rY   )r!   r2   r   r[   r   r   r   _print_latex_svg   s    

z0_init_ipython_printing.<locals>._print_latex_svgc                    s(    | r$| fddi}|S dS )zD
        A function that returns a png rendered by mathtext
        rS   rW   Nr   r-   rZ   )r!   r8   r   r   r   r   _print_latex_matplotlib   s    z7_init_ipython_printing.<locals>._print_latex_matplotlibc                    s4    | r0| fdi}dkr,d| S |S dS )zW
        A function to generate the latex representation of SymPy expressions.
        rS   rT   rU   Nr   r^   )r!   r   r[   r   r   r   _print_latex_text   s
    z1_init_ipython_printing.<locals>._print_latex_textc                    s8   | j jr( |}d|v rt  t| ntt| dS )zIPython's pretty-printer display hook, for use in IPython 0.10

           This function was adapted from:

            ipython/IPython/hooks.py:155

        
N)rcpprintr	   r*   )selfr
   out)r   r   r   _result_display   s    
z/_init_ipython_printing.<locals>._result_displayz0.11z
text/plainzimage/svg+xml)r   z"init_printing: using svg formatterz*init_printing: not using any svg formatterz	image/png)Tr#   z"init_printing: using png formatterZ
matplotlibz)init_printing: using matplotlib formatterz*init_printing: not using any png formatterz
text/latex)TZmathjaxz&init_printing: using mathjax formatterz-init_printing: not using text/latex formatterZresult_display)ZIPython.lib.latextoolsr   ImportErrorcolorslowerr   roundsplitformatdefault_latexr    r   __version__rN   rE   rD   rF   rG   rK   rO   Zdisplay_formatter
formattersr   Zfor_typeZ
_repr_svg_Ztype_printerspopZ_repr_disabledZ
_repr_png_Z_repr_latex_Zset_hook)ipr   	use_latexeulerr7   	backcolorfontsizer[   rQ   latex_printerr4   r   r3   ZaddpackagesZ	imagesizeoffset
resolutionZdviZ	svg_scaler"   r\   r]   r_   r`   rf   Zprintable_typesZplaintext_formatterclsZsvg_formatterZpng_formatterZlatex_formatterr   )r    r!   r8   r/   r2   r'   r1   r7   r   r[   r   r&   rQ   rR   r4   r   r   r   _init_ipython_printing!   s    





&





rz   c                 C   sn   ddl m} d|vrdS zddlm} W n: tyb   zddlm} W n ty\   Y Y dS 0 Y n0 t| |S )z%Is a shell instance an IPython shell?r   )modulesr    F)InteractiveShell)r   r{   ZIPython.core.interactiveshellr|   rg   ZIPython.iplibrH   )shellr{   r|   r   r   r   _is_ipython:  s    r~   FTNTransparent10ptrT         ?c                    s  ddl }ddlm} | r4|dur&|}qNddlm} n|durB|}nddlm} d}|du rz
t }W n tyv   Y n
0 |du}|r|st|}|rB| rBzDddl	}t
|jt
dkrddlm} nddlm} dd	lm} W n ty   Y nP0 t|||fsBd
d|jvrBdu r,td d|du rBtd d}tsb|sb|jd n.| | r fdd}n fdd}|r|dd}|rtd t|||||	|
|||||fi | nt|fi | dS )a*  
    Initializes pretty-printer depending on the environment.

    Parameters
    ==========

    pretty_print : bool, default=True
        If ``True``, use :func:`~.pretty_print` to stringify or the provided pretty
        printer; if ``False``, use :func:`~.sstrrepr` to stringify or the provided string
        printer.
    order : string or None, default='lex'
        There are a few different settings for this parameter:
        ``'lex'`` (default), which is lexographic order;
        ``'grlex'``, which is graded lexographic order;
        ``'grevlex'``, which is reversed graded lexographic order;
        ``'old'``, which is used for compatibility reasons and for long expressions;
        ``None``, which sets it to lex.
    use_unicode : bool or None, default=None
        If ``True``, use unicode characters;
        if ``False``, do not use unicode characters;
        if ``None``, make a guess based on the environment.
    use_latex : string, bool, or None, default=None
        If ``True``, use default LaTeX rendering in GUI interfaces (png and
        mathjax);
        if ``False``, do not use LaTeX rendering;
        if ``None``, make a guess based on the environment;
        if ``'png'``, enable LaTeX rendering with an external LaTeX compiler,
        falling back to matplotlib if external compilation fails;
        if ``'matplotlib'``, enable LaTeX rendering with matplotlib;
        if ``'mathjax'``, enable LaTeX text generation, for example MathJax
        rendering in IPython notebook or text rendering in LaTeX documents;
        if ``'svg'``, enable LaTeX rendering with an external latex compiler,
        no fallback
    wrap_line : bool
        If True, lines will wrap at the end; if False, they will not wrap
        but continue as one line. This is only relevant if ``pretty_print`` is
        True.
    num_columns : int or None, default=None
        If ``int``, number of columns before wrapping is set to num_columns; if
        ``None``, number of columns before wrapping is set to terminal width.
        This is only relevant if ``pretty_print`` is ``True``.
    no_global : bool, default=False
        If ``True``, the settings become system wide;
        if ``False``, use just for this console/session.
    ip : An interactive console
        This can either be an instance of IPython,
        or a class that derives from code.InteractiveConsole.
    euler : bool, optional, default=False
        Loads the euler package in the LaTeX preamble for handwritten style
        fonts (http://www.ctan.org/pkg/euler).
    forecolor : string or None, optional, default=None
        DVI setting for foreground color. ``None`` means that either ``'Black'``,
        ``'White'``, or ``'Gray'`` will be selected based on a guess of the IPython
        terminal color setting. See notes.
    backcolor : string, optional, default='Transparent'
        DVI setting for background color. See notes.
    fontsize : string, optional, default='10pt'
        A font size to pass to the LaTeX documentclass function in the
        preamble. Note that the options are limited by the documentclass.
        Consider using scale instead.
    latex_mode : string, optional, default='plain'
        The mode used in the LaTeX printer. Can be one of:
        ``{'inline'|'plain'|'equation'|'equation*'}``.
    print_builtin : boolean, optional, default=True
        If ``True`` then floats and integers will be printed. If ``False`` the
        printer will only print SymPy types.
    str_printer : function, optional, default=None
        A custom string printer function. This should mimic
        :func:`~.sstrrepr()`.
    pretty_printer : function, optional, default=None
        A custom pretty printer. This should mimic :func:`~.pretty()`.
    latex_printer : function, optional, default=None
        A custom LaTeX printer. This should mimic :func:`~.latex()`.
    scale : float, optional, default=1.0
        Scale the LaTeX output when using the ``'png'`` or ``'svg'`` backends.
        Useful for high dpi screens.
    settings :
        Any additional settings for the ``latex`` and ``pretty`` commands can
        be used to fine-tune the output.

    Examples
    ========

    >>> from sympy.interactive import init_printing
    >>> from sympy import Symbol, sqrt
    >>> from sympy.abc import x, y
    >>> sqrt(5)
    sqrt(5)
    >>> init_printing(pretty_print=True) # doctest: +SKIP
    >>> sqrt(5) # doctest: +SKIP
      ___
    \/ 5
    >>> theta = Symbol('theta') # doctest: +SKIP
    >>> init_printing(use_unicode=True) # doctest: +SKIP
    >>> theta # doctest: +SKIP
    \u03b8
    >>> init_printing(use_unicode=False) # doctest: +SKIP
    >>> theta # doctest: +SKIP
    theta
    >>> init_printing(order='lex') # doctest: +SKIP
    >>> str(y + x + y**2 + x**2) # doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_printing(order='grlex') # doctest: +SKIP
    >>> str(y + x + y**2 + x**2) # doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_printing(order='grevlex') # doctest: +SKIP
    >>> str(y * x**2 + x * y**2) # doctest: +SKIP
    x**2*y + x*y**2
    >>> init_printing(order='old') # doctest: +SKIP
    >>> str(x**2 + y**2 + x + y) # doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_printing(num_columns=10) # doctest: +SKIP
    >>> x**2 + x + y**2 + y # doctest: +SKIP
    x + y +
    x**2 + y**2

    Notes
    =====

    The foreground and background colors can be selected when using ``'png'`` or
    ``'svg'`` LaTeX rendering. Note that before the ``init_printing`` command is
    executed, the LaTeX rendering is handled by the IPython console and not SymPy.

    The colors can be selected among the 68 standard colors known to ``dvips``,
    for a list see [1]_. In addition, the background color can be
    set to  ``'Transparent'`` (which is the default value).

    When using the ``'Auto'`` foreground color, the guess is based on the
    ``colors`` variable in the IPython console, see [2]_. Hence, if
    that variable is set correctly in your IPython console, there is a high
    chance that the output will be readable, although manual settings may be
    needed.


    References
    ==========

    .. [1] https://en.wikibooks.org/wiki/LaTeX/Colors#The_68_standard_colors_known_to_dvips

    .. [2] https://ipython.readthedocs.io/en/stable/config/details.html#terminal-colors

    See Also
    ========

    sympy.printing.latex
    sympy.printing.pretty

    r   N)Printer)r   )sstrreprFz1.0)TerminalInteractiveShell)InteractiveConsolezipython-consoler   z*init_printing: Setting use_unicode to TrueTz(init_printing: Setting use_latex to Trueorderuse_unicode	wrap_linenum_columnsc                    s    | fd|S )Nr   r   exprr   _stringify_funcr   r   r   r   r   r   <lambda>$  s    zinit_printing.<locals>.<lambda>c                    s    | fdi|S )Nr   r   r   )r   r   r   r   r   ,  s   rS   zMinit_printing: Mode is not able to be set due to internalsof IPython printing)r   Zsympy.printing.printerr   Zsympy.printingr   r   Zget_ipython	NameErrorr~   r    r   rn   Z!IPython.terminal.interactiveshellr   Z*IPython.frontend.terminal.interactiveshellcoder   rg   rH   joinargvr   	NO_GLOBALZset_global_settingsrp   rz   r   )Zpretty_printr   r   rr   r   r   Z	no_globalrq   rs   r7   rt   ru   r[   rQ   Zstr_printerZpretty_printerrv   r4   r   r   r   r   Z
in_ipythonr    r   r   Zmode_in_settingsr   r   r   init_printingO  sr     



r   )TNNNNNFNFNr   r   rT   TNNNr   )__doc__Zsympy.external.importtoolsr   ior   Zsympy.printing.latexr   rm   Zsympy.printing.previewr   Zsympy.utilities.miscr   Zsympy.printing.defaultsr   r   rz   r~   r   r   r   r   r   r   <module>   s(            