o
    MEg"                    @   s  U d dl 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 d dl	mZ d dl
mZ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
lm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% ej&dkrd dlm'Z'm(Z(m)Z) n
d dl*m'Z'm(Z(m)Z) ddl+m,Z,m-Z- ddl.m.Z. ddl/m0Z0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ddl<m=Z> ddl?m@Z@mAZA ddlBmCZCmDZD ddlEmFZFmGZG ddlHmIZI ddlJmKZK ddlLmMZM ddlNmOZO ddlPmQZQmRZR ddlSmTZT dd lUmVZVmWZW dd!lXmYZYmZZZ dd"l[m\Z\m]Z] er0dd#l^m_Z_ dd$l`maZa dd%lbmcZc ed d&kZeee$efd'f gd'f Zge'd( Zhe'd) ZiG d*d+ d+Zjej Zkd,Zle6jme6jnd-ZoG d.d/ d/e ZpeG d0d1 d1Zqe)G d2d3 d3e(Zre)G d4d5 d5e(Zse$esereff Zt	 ee$eteOf  Zu	 e: ZvG d6d7 d7ewZxG d8d9 d9ZyG d:d; d;ZzG d<d= d=Z{G d>d? d?Z|G d@dA dAZ}G dBdC dCZ~G dDdE dEZd|dGedHedIedIef f fdJdKZdHefdLdMZe6jne6jme6je6jedNZdOdP e D ZeG dQdR dRejZG dSdT dTeZdae!dU edV< d}dWdXZdHefdYdZZe r1d d[lmZ ed\d] G d^d_ d_Zed`kre ZedadbdcdFd\ddddedfdgdhdidj edkdlee edg dFdmg dndodpdqd\drg dsdtdpdug dvdwdpdxdydz ed{ dS dS )~    N)ABCabstractmethod)abc)	dataclassfield)datetime)wraps)getpass)islice)	monotonic)TracebackType)IOTYPE_CHECKINGAnyCallableDictIterableListMapping
NamedTupleOptionalTextIOTypeUnioncast)      )LiteralProtocolruntime_checkable   )errorsthemes)_emoji_replace)FormatTimeCallable	LogRender)AlignAlignMethod)ColorSystem)Control)NullHighlighterReprHighlighterrender)Measurementmeasure_renderables)PagerSystemPager)Prettyis_expandable)Region)render_scope)Screen)Segment)Style	StyleTypeStyled)DEFAULT_TERMINAL_THEMETerminalTheme)TextTextType)Theme
ThemeStack)WindowsConsoleFeatures)LiveStatusWindowsr>   )defaultleftcenterrightfull)foldcropellipsisignorec                   @   s   e Zd ZdS )NoChangeN)__name__
__module____qualname__ rT   rT   f/var/www/eduai.edurigo.com/doc_train/edurigo_ai/Puru/venv/lib/python3.10/site-packages/rich/console.pyrP   J   s    rP   a9  <!DOCTYPE html>
<head>
<meta charset="UTF-8">
<style>
{stylesheet}
body {{
    color: {foreground};
    background-color: {background};
}}
</style>
</head>
<html>
<body>
    <code>
        <pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>
    </code>
</body>
</html>
)256color16colorc                   @   s$   e Zd ZU dZeed< 	 eed< dS )ConsoleDimensionszSize of the terminal.widthheightN)rQ   rR   rS   __doc__int__annotations__rT   rT   rT   rU   rX   i   s   
 rX   c                   @   s  e Zd ZU dZeed< 	 eed< 	 eed< 	 eed< 	 eed< 	 eed< 	 dZ	e
e ed	< 	 dZe
e ed
< 	 dZe
e ed< 	 dZe
e ed< 	 dZe
e ed< 	 dZe
e ed< 	 edefddZdddZeeeeeeeeed	deeef deeef deeef d	ee
e ef d
ee
e ef dee
e ef dee
e ef dee
e ef dee
e ef dd fddZdedd fddZdededd fddZdS )ConsoleOptionsz$Options for __rich_console__ method.sizelegacy_windows	min_width	max_widthis_terminalencodingNjustifyoverflowFno_wrap	highlightmarkuprZ   returnc                 C   s   | j d S )z+Check if renderables should use ascii only.utf)rd   
startswithselfrT   rT   rU   
ascii_only   s   zConsoleOptions.ascii_onlyc                 C   s   t t }| j |_|S )zdReturn a copy of the options.

        Returns:
            ConsoleOptions: a copy of self.
        )r^   __new____dict__copy)rn   optionsrT   rT   rU   rr      s   
zConsoleOptions.copy)	rY   ra   rb   re   rf   rg   rh   ri   rZ   rY   c       	         C   s   |   }
t|tstd| |
_|
_t|ts||
_t|ts"||
_t|ts*||
_t|ts2||
_t|ts:||
_t|tsB||
_	t|tsJ||
_
t|	ts[|	du rUdntd|	|
_|
S )zUpdate values, return a copy.r   N)rr   
isinstancerP   maxra   rb   re   rf   rg   rh   ri   rZ   )rn   rY   ra   rb   re   rf   rg   rh   ri   rZ   rs   rT   rT   rU   update   s(   








zConsoleOptions.updatec                 C   s   |   }td| |_|_|S )zUpdate just the width, return a copy.

        Args:
            width (int): New width (sets both min_width and max_width)

        Returns:
            ~ConsoleOptions: New console options instance.
        r   )rr   ru   ra   rb   )rn   rY   rs   rT   rT   rU   update_width   s   	zConsoleOptions.update_widthc                 C   s$   |   }td| |_|_||_|S )a  Update the width and height, and return a copy.

        Args:
            width (int): New width (sets both min_width and max_width).
            height (int): New height.

        Returns:
            ~ConsoleOptions: New console options instance.
        r   )rr   ru   ra   rb   rZ   )rn   rY   rZ   rs   rT   rT   rU   update_dimensions   s   
z ConsoleOptions.update_dimensions)rj   r^   )rQ   rR   rS   r[   rX   r]   boolr\   strre   r   JustifyMethodrf   OverflowMethodrg   rh   ri   rZ   propertyro   rr   	NO_CHANGEr   rP   rv   rw   rx   rT   rT   rT   rU   r^   r   sz   
 



	

#r^   c                   @   s&   e Zd ZdZdedef fddZdS )RichCastz5An object that may be 'cast' to a console renderable.rj   ConsoleRenderablec                 C      d S NrT   rm   rT   rT   rU   __rich__   s   zRichCast.__rich__N)rQ   rR   rS   r[   r   rz   r   rT   rT   rT   rU   r      s    r   c                   @   s&   e Zd ZdZ						ddd	Zd
S )r   z-An object that supports the console protocol.consoleConsolers   r^   rj   RenderResultc                 C   r   r   rT   rn   r   rs   rT   rT   rU   __rich_console__   s   z"ConsoleRenderable.__rich_console__N)r   r   rs   r^   rj   r   )rQ   rR   rS   r[   r   rT   rT   rT   rU   r      s    r   c                   @   s   e Zd ZdZdS )CaptureErrorz(An error in the Capture context manager.N)rQ   rR   rS   r[   rT   rT   rT   rU   r      s    r   c                   @   s>   e Zd ZdZddeddfddZdd	d
ddee fddZdS )NewLinez$A renderable to generate new line(s)r    countrj   Nc                 C   s
   || _ d S r   )r   rn   r   rT   rT   rU   __init__  s   
zNewLine.__init__r   r   rs   r^   c                 c   s    t d| j V  d S )N
)r7   r   r   rT   rT   rU   r     s   zNewLine.__rich_console__r    )	rQ   rR   rS   r[   r\   r   r   r7   r   rT   rT   rT   rU   r      s    r   c                   @   sH   e Zd ZdZdeee  dededdfddZd	d
dede	fddZ
dS )ScreenUpdatez)Render a list of lines at a given offset.linesxyrj   Nc                 C      || _ || _|| _d S r   )_linesr   r   )rn   r   r   r   rT   rT   rU   r        
zScreenUpdate.__init__r   r   rs   c                 c   s@    | j }tj}t| j| jD ]\}}|||V  |E d H  qd S r   )r   r)   move_to	enumerater   r   )rn   r   rs   r   r   offsetlinerT   rT   rU   r     s   zScreenUpdate.__rich_console__)rQ   rR   rS   r[   r   r7   r\   r   r^   r   r   rT   rT   rT   rU   r   
  s    "r   c                   @   s\   e Zd ZdZdddZddd	Zd
eee  dee dee	 ddfddZ
defddZdS )CapturezContext manager to capture the result of printing to the console.
    See :meth:`~rich.console.Console.capture` for how to use.

    Args:
        console (Console): A console instance to capture output.
    r   r   rj   Nc                 C   s   || _ d | _d S r   )_console_result)rn   r   rT   rT   rU   r   $  s   
zCapture.__init__c                 C      | j   | S r   )r   begin_capturerm   rT   rT   rU   	__enter__(     
zCapture.__enter__exc_typeexc_valexc_tbc                 C   s   | j  | _d S r   )r   end_capturer   rn   r   r   r   rT   rT   rU   __exit__,  s   zCapture.__exit__c                 C   s   | j du r	td| j S )zGet the result of the capture.Nz<Capture result is not available until context manager exits.)r   r   rm   rT   rT   rU   get4  s
   
zCapture.get)r   r   rj   N)rj   r   )rQ   rR   rS   r[   r   r   r   r   BaseExceptionr   r   rz   r   rT   rT   rT   rU   r     s    



r   c                	   @   s`   e Zd ZdZddddededdfd	d
ZdddZdee	e
  dee
 dee ddfddZdS )ThemeContextzbA context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage.Tr   r   themeinheritrj   Nc                 C   r   r   )r   r   r   )rn   r   r   r   rT   rT   rU   r   @  r   zThemeContext.__init__c                 C   s   | j | j | S r   )r   
push_themer   rm   rT   rT   rU   r   E  s   zThemeContext.__enter__r   r   r   c                 C   s   | j   d S r   )r   	pop_themer   rT   rT   rU   r   I  s   zThemeContext.__exit__T)rj   r   )rQ   rR   rS   r[   r@   ry   r   r   r   r   r   r   r   rT   rT   rT   rU   r   =  s    

r   c                   @   sn   e Zd ZdZ			ddddee deded	df
d
dZdddZdee	e
  dee
 dee d	dfddZdS )PagerContextzZA context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.NFr   r   pagerstyleslinksrj   c                 C   s*   || _ |d u r
t n|| _|| _|| _d S r   )r   r1   r   r   r   )rn   r   r   r   r   rT   rT   rU   r   U  s   
zPagerContext.__init__c                 C   r   r   )r   _enter_bufferrm   rT   rT   rU   r   a  r   zPagerContext.__enter__r   r   r   c                 C   s   |d u rF| j j0 | j jd d  }| j jd d = |}| js#t|}n| js+t|}| j |}W d    n1 s;w   Y  | j	
| | j   d S r   )r   _lock_bufferr   r7   strip_stylesr   strip_links_render_bufferr   show_exit_buffer)rn   r   r   r   buffersegmentscontentrT   rT   rU   r   e  s   

	zPagerContext.__exit__NFF)rj   r   )rQ   rR   rS   r[   r   r0   ry   r   r   r   r   r   r   rT   rT   rT   rU   r   R  s4    


r   c                	   @   s   e Zd ZdZ	ddddededdfd	d
Zdddedee ddfddZ	dddZ
deee  dee dee ddfddZdS )ScreenContextziA context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage. r   r   hide_cursorstylerj   Nc                 C   s"   || _ || _t|d| _d| _d S )Nr   F)r   r   r6   screen_changed)rn   r   r   r   rT   rT   rU   r   |  s   
zScreenContext.__init__r   renderablesc                G   sJ   |rt |dkrt| n|d | j_|dur|| j_| jj| jdd dS )a+  Update the screen.

        Args:
            renderable (RenderableType, optional): Optional renderable to replace current renderable,
                or None for no change. Defaults to None.
            style: (Style, optional): Replacement style, or None for no change. Defaults to None.
        r    r   Nr   )end)lenRenderGroupr   
renderabler   r   print)rn   r   r   rT   rT   rU   rv     s   
zScreenContext.updatec                 C   s*   | j d| _| jr| jr| j d | S )NTF)r   set_alt_screenr   r   show_cursorrm   rT   rT   rU   r     s   zScreenContext.__enter__r   r   r   c                 C   s0   | j r| jd | jr| jd d S d S d S )NFT)r   r   r   r   r   r   rT   rT   rU   r     s   zScreenContext.__exit__r   )rj   r   )rQ   rR   rS   r[   ry   r9   r   RenderableTyper   rv   r   r   r   r   r   rT   rT   rT   rU   r   y  s<    
	


r   c                   @   sn   e Zd ZdZdddddeddfd	d
Zeded fddZ						dddZ	ddddde
fddZdS )r   a$  Takes a group of renderables and returns a renderable object that renders the group.

    Args:
        renderables (Iterable[RenderableType]): An iterable of renderable objects.
        fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
    Tfitr   r   r   rj   Nc                G   s   || _ || _d | _d S r   )_renderablesr   _render)rn   r   r   rT   rT   rU   r     r   zRenderGroup.__init__c                 C   s   | j d u rt| j| _ | j S r   )r   listr   rm   rT   rT   rU   r     s   
zRenderGroup.renderablesr   r   rs   r^   r.   c                 C   s"   | j r
t||| jS t|j|jS r   )r   r/   r   r.   rb   r   rT   rT   rU   __rich_measure__  s   zRenderGroup.__rich_measure__c                 c   s    | j E d H  d S r   )r   r   rT   rT   rU   r     s   zRenderGroup.__rich_console__)r   r   rs   r^   rj   r.   )rQ   rR   rS   r[   ry   r   r}   r   r   r   r   r   rT   rT   rT   rU   r     s&    
r   Tr   rj   .c                    s.   dt dtt f dt dtf f fdd}|S )zA decorator that turns an iterable of renderables in to a group.

    Args:
        fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
    method.rj   c                    s(   t  dtdtdtf fdd}|S )zMConvert a method that returns an iterable of renderables in to a RenderGroup.argskwargsrj   c                     s   | i |}t |d iS )Nr   )r   )r   r   r   )r   r   rT   rU   _replace  s   z1render_group.<locals>.decorator.<locals>._replace)r   r   r   )r   r   r   )r   rU   	decorator  s   zrender_group.<locals>.decorator)r   r   r   r   )r   r   rT   r   rU   render_group  s   
r   c                  C   sV   zt  W n
 ty   Y dS w t  } | jj}dt| jv s!|dkr#dS |dkr)dS dS )z-Check if we're running in a Jupyter notebook.Fzgoogle.colabZMQInteractiveShellTTerminalInteractiveShell)get_ipython	NameError	__class__rQ   rz   )ipythonshellrT   rT   rU   _is_jupyter  s   r   )standard256	truecolorwindowsc                 C   s   i | ]\}}||qS rT   rT   ).0namesystemrT   rT   rU   
<dictcomp>      r   c                   @   s<   e Zd ZU dZeed< eedZe	e
 ed< dZeed< dS )ConsoleThreadLocalsz(Thread local values for Console context.theme_stack)default_factoryr   r   buffer_indexN)rQ   rR   rS   r[   rA   r]   r   r   r   r   r7   r   r\   rT   rT   rT   rU   r     s
   
 r   c                   @   s.   e Zd ZdZedee dee fddZdS )
RenderHookz(Provides hooks in to the render process.r   rj   c                 C   s   dS )aL  Called with a list of objects to render.

        This method can return a new list of renderables, or modify and return the same list.

        Args:
            renderables (List[ConsoleRenderable]): A number of renderable objects.

        Returns:
            List[ConsoleRenderable]: A replacement list of renderables.
        NrT   )rn   r   rT   rT   rU   process_renderables  s    zRenderHook.process_renderablesN)rQ   rR   rS   r[   r   r   r   r   rT   rT   rT   rU   r     s    r   rB   _windows_console_featuresc                  C   s"   t d urt S ddlm}  |  a t S )Nr    get_windows_console_features)r   _windowsr   r   rT   rT   rU   r     s
   r   c                   C   s   t ot j S )zDetect legacy Windows.)WINDOWSr   vtrT   rT   rT   rU   detect_legacy_windows#     r   )initF)stripc                :   @   s  e Zd ZU dZejZeeef e	d< ddddddddddddddddddddde
 dddddd	d
eed  dee dee dee dedee dedeee  dedee dee dee dee dedededededededeeef d ed! d"ee d#ed$eeg ef  d%eeg ef  deeeef  f6d&d'Zd(efd)d*Zed(ee fd+d,Zejd-ee d(dfd.d,Zed(ee fd/d0Zed(efd1d2Zejd3ed(dfd4d2Zed(e fd5d6Z!d(ee" fd7d8Z#dd9d:Z$dd;d<Z%dd?d@Z&ddAdBZ'dCe(d(dfdDdEZ)ddFdGZ*ddHdIZ+dJe,dKe,dLe,d(dfdMdNZ-ddOdPZ.d(efdQdRZ/ddSdedTed(dfdUdVZ0ddWdXZ1ddSdedTed(e2fdYdZZ3ed(ee fd[d\Z4ed(efd]d^Z5ed(efd_d`Z6ed(efdadbZ7ed(e8fdcddZ9ed(e:fdedfZ;ed(efdgdhZ<ed(efdidjZ=ddkdlZ>d(e?fdmdnZ@	ddoeeA dpedqed(eBfdrdsZCddued(dfdvdwZDddxed(dfdydzZEd{d|d}d~ddeFdedededed(dfddZGdded(efddZHdded(efddZIed(efddZJ	ddedee d(dfddZKdddeFdee8 d(eLfddZM	d deFdee8 d(eNe fddZO	d dddddeFdee8 deeP deded(eee  fddZQdddddddddedeeePf deeR deeS dee dee dee d eeT d(dfddZUdddeeePf deeePef  d(ePfddZVddddddeNe, dededeeR dee dee dee d(eeW fddZX	ddddddeYdedeeePf deZd(df
ddZ[de\d(dfddZ]dddddde,dededeeeePf  dee d(dfddÄZ^ddddddddddddddĜde,dededeeeePf  deeR deeS dee dee dee dee dee dee dedee d(dfddȄZ_dddɜdeFdee` dee8 d(dfdd̄Za	͐ddeee  deded(dfdd҄Zbdddddd՜dee dedee deded(dfddڄZcdddddddddtdۜ	de,dededeeeePf  deeR dee dee dee deded(dfdd߄ZddddZedeNe d(efddZf	dddddddeYdedededeeg d(efddZhddddedped(efddZiddddededped(dfddZjddddddeek dedee ded(ef
ddZlddemdddedeek dededed(dfddZndS (  r   a  A high level console interface.

    Args:
        color_system (str, optional): The color system supported by your terminal,
            either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect.
        force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.
        force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.
        force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None.
        soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False.
        theme (Theme, optional): An optional style theme object, or ``None`` for default theme.
        stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False.
        file (IO, optional): A file object where the console should write to. Defaults to stdout.
        quiet (bool, Optional): Boolean to suppress all output. Defaults to False.
        width (int, optional): The width of the terminal. Leave as default to auto-detect width.
        height (int, optional): The height of the terminal. Leave as default to auto-detect height.
        style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None.
        no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None.
        tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8.
        record (bool, optional): Boolean to enable recording of terminal output,
            required to call :meth:`export_html` and :meth:`export_text`. Defaults to False.
        markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.
        emoji (bool, optional): Enable emoji code. Defaults to True.
        highlight (bool, optional): Enable automatic highlighting. Defaults to True.
        log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.
        log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.
        log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%X] ".
        highlighter (HighlighterType, optional): Default highlighter.
        legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``.
        safe_box (bool, optional): Restrict box options that don't render on legacy Windows.
        get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log),
            or None for datetime.now.
        get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic.
    _environautoNFr   Tz[%X])color_systemforce_terminalforce_jupyterforce_interactive	soft_wrapr   stderrfilequietrY   rZ   r   no_colortab_sizerecordri   emojirh   log_timelog_pathlog_time_formathighlighterr`   safe_boxget_datetimeget_timer   r   )r   r   r   r   r   r  r  r  r  r   r  r  r  rY   rZ   r   r  r	  r
  ri   r  rh   r  r  r  r  HighlighterTyper`   r  r  r  c                C   s  |d ur|| _ |d u rt n|| _| jr|
pd}
|pd}|
d u r2| j d}|d ur2| r2t|}
|d u rH| j d}|d urH| rHt|}|| _|
| _|| _|| _	|| _
|| _|| _|| _|d u rkt oj| j n|| _|  || _|| _|	| _|| _|d u rd | _n|dkr|  | _nt| | _t | _t|||d| _|pt| _|| _|ptj | _!|pt"| _#|| _$|d ur|nd| j v | _%|d u r| j&o| j' n|| _(t | _)t*t+|d u rt,j-n|d| _.g | _/g | _0d | _1d	| _2d S )
N]   d   COLUMNSLINESr   )	show_time	show_pathtime_formatNO_COLOR)r   F)3r   r   
is_jupyterr   isdigitr\   r  _width_heightr	  r
  _markup_emoji
_highlightr   r`   _force_terminal_filer  r  _color_system_detect_color_systemCOLOR_SYSTEMS	threadingRLockr   r%   _log_render_null_highlighterr  r  r   nowr  r   r  r   r  rc   is_dumb_terminalis_interactive_record_buffer_lockr   rA   r"   DEFAULT_thread_locals_record_buffer_render_hooks_live_is_alt_screen)rn   r   r  r  r  r  r   r  r  r  rY   rZ   r   r  r	  r
  ri   r  rh   r  r  r  r  r`   r  r  r  r   columnsr   rT   rT   rU   r   S  s~   "





zConsole.__init__rj   c                 C   s   d| j  dt| j dS )Nz<console width= >)rY   rz   r%  rm   rT   rT   rU   __repr__  s   zConsole.__repr__c                 C   s(   | j p| jr	tjntj}t|d|}|S )z Get the file object to write to.rich_proxied_file)r$  r  sysstdoutgetattr)rn   r  rT   rT   rU   r    s   zConsole.filenew_filec                 C   s
   || _ dS )zSet a new file object.N)r$  )rn   r>  rT   rT   rU   r    s   
c                 C      | j jS zGet a thread local buffer.)r1  r   rm   rT   rT   rU   r        zConsole._bufferc                 C   r?  r@  r1  r   rm   rT   rT   rU   _buffer_index  rA  zConsole._buffer_indexvaluec                 C   s   || j _d S r   rB  )rn   rD  rT   rT   rU   rC       c                 C   r?  )z!Get the thread local theme stack.)r1  r   rm   rT   rT   rU   _theme_stack  rA  zConsole._theme_stackc                 C   s   | j rtjS | jr| jrdS tr"| jrtjS t }|jrtjS tj	S | j
dd  }|dv r4tjS | j
dd  }|d\}}}t|tj}|S )z"Detect color system from env vars.N	COLORTERMr   )r   24bitTERM-)r  r(   	TRUECOLORrc   r-  r   r`   r   r   	EIGHT_BITr   r   r   lower	partition_TERM_COLORSSTANDARD)rn   windows_console_features
color_termterm
_term_name_hyphencolorsr   rT   rT   rU   r&    s(   zConsole._detect_color_systemc                 C   s   |  j d7  _ dS )z4Enter in to a buffer context, and buffer all output.r    N)rC  rm   rT   rT   rU   r        zConsole._enter_bufferc                 C   s   |  j d8  _ |   dS )z5Leave buffer context, and render content if required.r    N)rC  _check_bufferrm   rT   rT   rU   r     s   zConsole._exit_bufferliverC   c                 C   sF   | j  | jdurtd|| _W d   dS 1 sw   Y  dS )zSet Live instance. Used by Live context manager.

        Args:
            live (Live): Live instance using this Console.

        Raises:
            errors.LiveError: If this Console has a Live context currently active.
        Nz+Only one live display may be active at once)r   r4  r!   	LiveError)rn   rY  rT   rT   rU   set_live  s
   	

"zConsole.set_livec                 C   s2   | j  d| _W d   dS 1 sw   Y  dS )zClear the Live instance.N)r   r4  rm   rT   rT   rU   
clear_live  s   "zConsole.clear_livehookc                 C   s   | j | dS )zpAdd a new render hook to the stack.

        Args:
            hook (RenderHook): Render hook instance.
        N)r3  append)rn   r]  rT   rT   rU   push_render_hook  s   zConsole.push_render_hookc                 C      | j   dS )z'Pop the last renderhook from the stack.N)r3  poprm   rT   rT   rU   pop_render_hook  r   zConsole.pop_render_hookc                 C   s   |    | S )z,Own context manager to enter buffer context.r   rm   rT   rT   rU   r   !  s   zConsole.__enter__r   	exc_value	tracebackc                 C      |    dS )zExit buffer context.N)r   )rn   r   rd  re  rT   rT   rU   r   &  rE  zConsole.__exit__c                 C   rf  )z`Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.Nrc  rm   rT   rT   rU   r   *  rE  zConsole.begin_capturec                 C   s$   |  | j}| jdd= |   |S )zhEnd capture mode and return captured string.

        Returns:
            str: Console output.
        N)r   r   r   )rn   render_resultrT   rT   rU   r   .  s   zConsole.end_capturer   r   c                C   s   | j j||d dS )a  Push a new theme on to the top of the stack, replacing the styles from the previous theme.
        Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather
        than calling this method directly.

        Args:
            theme (Theme): A theme instance.
            inherit (bool, optional): Inherit existing styles. Defaults to True.
        rh  N)rF  r   rn   r   r   rT   rT   rU   r   9  s   	zConsole.push_themec                 C   r`  )z9Remove theme from top of stack, restoring previous theme.N)rF  r   rm   rT   rT   rU   r   D  r   zConsole.pop_themec                C   s   t | ||S )a  Use a different theme for the duration of the context manager.

        Args:
            theme (Theme): Theme instance to user.
            inherit (bool, optional): Inherit existing console styles. Defaults to True.

        Returns:
            ThemeContext: [description]
        )r   ri  rT   rT   rU   	use_themeH  s   
zConsole.use_themec                 C   s   | j dur
t| j  S dS )zpGet color system string.

        Returns:
            Optional[str]: "standard", "256" or "truecolor".
        N)r%  _COLOR_SYSTEMS_NAMESrm   rT   rT   rU   r   T  s   

zConsole.color_systemc                 C   s   t | jddpd S )zGet the encoding of the console file, e.g. ``"utf-8"``.

        Returns:
            str: A standard encoding string.
        rd   utf-8)r=  r  rM  rm   rT   rT   rU   rd   a  s   zConsole.encodingc                 C   s0   | j dur| j S t| jdd}|du rdS | S )zCheck if the console is writing to a terminal.

        Returns:
            bool: True if the console writing to a device capable of
            understanding terminal codes, otherwise False.
        NisattyF)r#  r=  r  )rn   rm  rT   rT   rU   rc   j  s   
zConsole.is_terminalc                 C   s$   | j dd}| dv }| jo|S )zxDetect dumb terminal.

        Returns:
            bool: True if writing to a dumb terminal, otherwise False.

        rI  r   )dumbunknown)r   r   rM  rc   )rn   _termis_dumbrT   rT   rU   r-  w  s   
zConsole.is_dumb_terminalc                 C   s   t | j| jd| j| j| jdS )zGet default console options.r    )r_   r`   ra   rb   rd   rc   )r^   r_   r`   rY   rd   rc   rm   rT   rT   rU   rs     s   zConsole.optionsc                 C   s   | j dur| jdurt| j | jS | jrtddS d}d}tr&t \}}n2zttj	
 \}}W n% tttfyW   zttj
 \}}W n tttfyT   Y nw Y nw |p[d}|p_d}t| j du rk|| j n| j | jdu ru|S | jS )zGet the size of the console.

        Returns:
            ConsoleDimensions: A named tuple containing the dimensions.
        NP      )r  r  rX   r-  r   shutilget_terminal_sizeosr;  stdinfilenoAttributeError
ValueErrorOSErrorr<  r`   )rn   rY   rZ   rT   rT   rU   r_     s4   
zConsole.sizec                 C   s   | j \}}|S )zsGet the width of the console.

        Returns:
            int: The width (in characters) of the console.
        r_   )rn   rY   _rT   rT   rU   rY        
zConsole.widthc                 C   s   | j \}}|S )zpGet the height of the console.

        Returns:
            int: The height (in lines) of the console.
        r|  )rn   r}  rZ   rT   rT   rU   rZ     r~  zConsole.heightc                 C   s   |  t  dS )z3Play a 'bell' sound (if supported by the terminal).N)controlr)   bellrm   rT   rT   rU   r    rW  zConsole.bellc                 C   s   t | }|S )a  A context manager to *capture* the result of print() or log() in a string,
        rather than writing it to the console.

        Example:
            >>> from rich.console import Console
            >>> console = Console()
            >>> with console.capture() as capture:
            ...     console.print("[bold magenta]Hello World[/]")
            >>> print(capture.get())

        Returns:
            Capture: Context manager with disables writing to the terminal.
        )r   )rn   capturerT   rT   rU   r    s   zConsole.capturer   r   r   c                 C   s   t | |||dS )a  A context manager to display anything printed within a "pager". The pager application
        is defined by the system and will typically support at least pressing a key to scroll.

        Args:
            pager (Pager, optional): A pager object, or None to use :class:~rich.pager.SystemPager`. Defaults to None.
            styles (bool, optional): Show styles in pager. Defaults to False.
            links (bool, optional): Show links in pager. Defaults to False.

        Example:
            >>> from rich.console import Console
            >>> from rich.__main__ import make_test_card
            >>> console = Console()
            >>> with console.pager():
                    console.print(make_test_card())

        Returns:
            PagerContext: A context manager.
        )r   r   r   )r   )rn   r   r   r   rT   rT   rU   r     s   zConsole.pagerr    r   c                 C   s"   |dksJ d|  t| dS )zqWrite new line(s).

        Args:
            count (int, optional): Number of new lines. Defaults to 1.
        r   zcount must be >= 0N)r   r   r   rT   rT   rU   r     s   zConsole.linehomec                 C   s.   |r|  t t  dS |  t  dS )zClear the screen.

        Args:
            home (bool, optional): Also move the cursor to 'home' position. Defaults to True.
        N)r  r)   clearr  )rn   r  rT   rT   rU   r    s   zConsole.cleardotszstatus.spinnerg      ?g      )@)spinnerspinner_stylespeedrefresh_per_secondstatusr  r  r  r  rE   c                C   s$   ddl m} ||| ||||d}|S )a  Display a status and spinner.

        Args:
            status (RenderableType): A status renderable (str or Text typically).
            console (Console, optional): Console instance to use, or None for global console. Defaults to None.
            spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots".
            spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner".
            speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.
            refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.

        Returns:
            Status: A Status object that may be used as a context manager.
        r    rD   )r   r  r  r  r  )r  rE   )rn   r  r  r  r  r  rE   status_renderablerT   rT   rU   r    s   zConsole.statusr   c                 C   s$   | j r| js| t| dS dS )zqShow or hide the cursor.

        Args:
            show (bool, optional): Set visibility of the cursor.
        TF)rc   r`   r  r)   r   )rn   r   rT   rT   rU   r   )  s   zConsole.show_cursorenablec                 C   s.   d}| j r| js| t| d}|| _|S )a  Enables alternative screen mode.

        Note, if you enable this mode, you should ensure that is disabled before
        the application exits. See :meth:`~rich.Console.screen` for a context manager
        that handles this for you.

        Args:
            enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True.

        Returns:
            bool: True if the control codes were written.

        FT)rc   r`   r  r)   
alt_screenr5  )rn   r  changedrT   rT   rU   r   4  s   zConsole.set_alt_screenc                 C   s   | j S )zCheck if the alt screen was enabled.

        Returns:
            bool: True if the alt screen was enabled, otherwise False.
        )r5  rm   rT   rT   rU   is_alt_screenI  s   zConsole.is_alt_screenr   r   c                 C   s   t | ||pddS )au  Context manager to enable and disable 'alternative screen' mode.

        Args:
            hide_cursor (bool, optional): Also hide the cursor. Defaults to False.
            style (Style, optional): Optional style for screen. Defaults to None.

        Returns:
            ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit.
        r   )r   r   )r   )rn   r   r   rT   rT   rU   r   R  s   zConsole.screenrs   r   rs   c                C   s   t | |p| j|}|S )a  Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains
        information regarding the number of characters required to print the renderable.

        Args:
            renderable (RenderableType): Any renderable or string.
            options (Optional[ConsoleOptions], optional): Options to use when measuring, or None
                to use default options. Defaults to None.

        Returns:
            Measurement: A measurement of the renderable.
        )r.   r   rs   )rn   r   rs   measurementrT   rT   rU   measure`  s   zConsole.measurec           	      c   s    |p| j }|jdk rdS t|dr| }t|dr"|| |}nt|tr8| j||j|j	d}|| |}n	t
d|dzt|}W n tyW   t
d|d	w t}|D ]}t||rg|V  q\| ||E dH  q\dS )
ak  Render an object in to an iterable of `Segment` instances.

        This method contains the logic for rendering objects with the console protocol.
        You are unlikely to need to use it directly, unless you are extending the library.

        Args:
            renderable (RenderableType): An object supporting the console protocol, or
                an object that may be converted to a string.
            options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None.

        Returns:
            Iterable[Segment]: An iterable of segments that may be rendered.
        r    Nr   r   )rh   ri   zUnable to render zC; A str, Segment or object with __rich_console__ method is requiredzobject z is not renderable)rs   rb   hasattrr   r   rt   rz   
render_strrh   ri   r!   NotRenderableErroriter	TypeErrorr7   r-   )	rn   r   rs   _optionsrender_iterabletext_renderableiter_render_Segmentrender_outputrT   rT   rU   r-   q  s:   








zConsole.render)r   pad	new_linesr  r  c             	   C   s   | j ] |p| j}| ||}|rt||}tttj||j||dd|j	}|j	durW|j	t
| }	|	dkrW|rFtd|j |tdgntd|j |gg}
||
|	  |W  d   S 1 scw   Y  dS )aG  Render objects in to a list of lines.

        The output of render_lines is useful when further formatting of rendered console text
        is required, such as the Panel class which draws a border around any renderable object.

        Args:
            renderable (RenderableType): Any object renderable in the console.
            options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``.
            style (Style, optional): Optional style to apply to renderables. Defaults to ``None``.
            pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``.
            new_lines (bool, optional): Include "
" characters at end of lines.

        Returns:
            List[List[Segment]]: A list of lines, where a line is a list of Segment objects.
        )include_new_linesr  Nr   r7  r   )r   rs   r-   r7   apply_styler   r
   split_and_crop_linesrb   rZ   r   extend)rn   r   rs   r   r  r  render_options	_renderedr   extra_linespad_linerT   rT   rU   render_lines  s6   

$zConsole.render_linesr   )r   re   rf   r  ri   rh   r  textre   rf   r>   c                C   s   |p|du o| j }	|p|du o| j}
|p|du o| j}|
r+t|||	d}||_||_nt|	r2t|n||||d}|r@|p?| jnd}|durS|t	|}|
| |S |S )a  Convert a string to a Text instance. This is is called automatically if
        you print or log a string.

        Args:
            text (str): Text to render.
            style (Union[str, Style], optional): Style to apply to rendered text.
            justify (str, optional): Justify method: "default", "left", "center", "full", or "right". Defaults to ``None``.
            overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to ``None``.
            emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default.
            markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default.
            highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default.
            highlighter (HighlighterType, optional): Optional highlighter to apply.
        Returns:
            ConsoleRenderable: Renderable object.

        N)r   r  )re   rf   r   )r!  r   r"  render_markupre   rf   r>   r#   r  rz   copy_styles)rn   r  r   re   rf   r  ri   rh   r  emoji_enabledmarkup_enabledhighlight_enabled	rich_text_highlighterhighlight_textrT   rT   rU   r    s*    
zConsole.render_str)rG   r   rG   c             
   C   s   t |tr|S z| j|}|du rt|}|jr| W S |W S  tjyI } z|dur9| 	|W  Y d}~S t
d|d| dd}~ww )a!  Get a Style instance by it's theme name or parse a definition.

        Args:
            name (str): The name of a style or a style definition.

        Returns:
            Style: A Style object.

        Raises:
            MissingStyle: If no style could be parsed from name.

        NzFailed to get style z; )rt   r8   rF  r   parselinkrr   r!   StyleSyntaxError	get_styleMissingStyle)rn   r   rG   r   errorrT   rT   rU   r    s"   

zConsole.get_stylere   r  ri   rh   objectssepr   c                   s>  g }|j  g j }	 dv rdtddf fdd}
|
t}|s)|du r,| jr,| j}dfdd}|D ]L}t|d	rDt|}t|d
d}|rO| }t|t	r`|	| j
||||d q9t|trm|  | q9t|r}|  t||d q9|	|t	| q9|  | jdur| | jfdd|D }|S )a  Combine a number of renderables and text into one renderable.

        Args:
            objects (Iterable[Any]): Anything that Rich can render.
            sep (str): String to write between print data.
            end (str): String to write at end of print data.
            justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
            emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.
            markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.
            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.

        Returns:
            List[ConsoleRenderable]: A list of things to render.
        )rH   rI   rJ   r   rj   Nc                    s    t | tt d S r   )r&   r   r'   )r   )_appendre   rT   rU   align_appendK  s   z2Console._collect_renderables.<locals>.align_appendc                     s2   rt d}  |  d d = d S d S )N)re   r   )r>   join)sep_text)r^  r   re   r  r  rT   rU   
check_textT  s
   z0Console._collect_renderables.<locals>.check_text&jwevpw_eors4dfo6mwo345ermk7kdnfnwerwerr   )r  ri   r  )r  c                       g | ]}t | qS rT   r:   r   r   r   rT   rU   
<listcomp>w  r   z0Console._collect_renderables.<locals>.<listcomp>rj   N)r^  r   r+  r"  r  r  reprr=  rt   rz   r  r   r3   r2   r   r  )rn   r  r  r   re   r  ri   rh   r   append_textr  r  r  r   	rich_castrT   )r  r^  r   re   r  r   r  rU   _collect_renderables*  sL   



zConsole._collect_renderablesu   ─z	rule.linerI   )
charactersr   aligntitler  r  c                C   s*   ddl m} |||||d}| | dS )u  Draw a line with optional centered title.

        Args:
            title (str, optional): Text to render over the rule. Defaults to "".
            characters (str, optional): Character(s) to form the line. Defaults to "─".
            style (str, optional): Style of line. Defaults to "rule.line".
            align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center".
        r    )Rule)r  r  r   r  N)ruler  r   )rn   r  r  r   r  r  r  rT   rT   rU   r  {  s   zConsole.ruler  c                 G   s.   | j s|D ]	}| j|j q|   dS dS )zInsert non-printing control codes.

        Args:
            control_codes (str): Control codes, such as those that may move the cursor.
        N)r-  r   r^  segmentrX  )rn   r  _controlrT   rT   rU   r    s
   zConsole.controlr7  r   )r  r   r   rh   c                G   s4   | dd |D }| j|||ddddd|d	 dS )a  Output to the terminal. This is a low-level way of writing to the terminal which unlike
        :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will
        optionally apply highlighting and a basic style.

        Args:
            sep (str, optional): String to write between print data. Defaults to " ".
            end (str, optional): String to write at end of print data. Defaults to "\\n".
            style (Union[str, Style], optional): A style to apply to output. Defaults to None.
            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use
                console default. Defaults to ``None``.
        c                 s   s    | ]}t |V  qd S r   )rz   )r   _objectrT   rT   rU   	<genexpr>  s    zConsole.out.<locals>.<genexpr>FTrO   )r   rh   r  ri   rg   rf   rM   r   N)r  r   )rn   r  r   r   rh   r  
raw_outputrT   rT   rU   out  s   
zConsole.out)r  r   r   re   rf   rg   r  ri   rh   rY   rZ   rM   r  rg   rM   c             
   G   s`  |st  f}|du r| j}|r|du rd}|du rd}d}|  | j|||||||	d}| jD ]}||}q/| jj|||
durFt|
| jnt	|||d}g }|j
}| j}|du rf|D ]	}|||| q[n|D ]}|t|||| | qh|r| jj
}tj|| jddD ]}|| qn| j
| W d   dS W d   dS 1 sw   Y  dS )a  Print to the console.

        Args:
            objects (positional args): Objects to log to the terminal.
            sep (str, optional): String to write between print data. Defaults to " ".
            end (str, optional): String to write at end of print data. Defaults to "\\n".
            style (Union[str, Style], optional): A style to apply to output. Defaults to None.
            justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``.
            overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None.
            no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.
            emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.
            markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.
            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.
            width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.
            crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.
            soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or None for
                Console default. Defaults to ``None``.
        NTrO   Fr  )re   rf   rY   rZ   rg   ri   r  )r   r  r  r3  r   rs   rv   minrY   r~   r  r-   r7   r  r  r   r  )rn   r  r   r   re   rf   rg   r  ri   rh   rY   rZ   rM   r  r  r   r]  r  new_segmentsr  r-   r   buffer_extendr   rT   rT   rU   r     sl   #
		

$"zConsole.print)regionrs   r  c          
      C   sz   | j std|p| j}|du r!d }}||j|jp| j}n|\}}}}|||}| j||d}	| |	|| dS )a  Update the screen at a given offset.

        Args:
            renderable (RenderableType): A Rich renderable.
            region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None.
            x (int, optional): x offset. Defaults to 0.
            y (int, optional): y offset. Defaults to 0.

        Raises:
            errors.NoAltScreen: If the Console isn't in alt screen mode.

        0Alt screen must be enabled to call update_screenNr   r  )	r  r!   NoAltScreenrs   rx   rb   rZ   r  update_screen_lines)
rn   r   r  rs   r  r   r   rY   rZ   r   rT   rT   rU   update_screen  s   

zConsole.update_screenr   r   r   r   c                 C   s>   | j stdt|||}| |}| j| |   dS )a  Update lines of the screen at a given offset.

        Args:
            lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`).
            x (int, optional): x offset (column no). Defaults to 0.
            y (int, optional): y offset (column no). Defaults to 0.

        Raises:
            errors.NoAltScreen: If the Console isn't in alt screen mode.
        r  N)r  r!   r  r   r-   r   r  rX  )rn   r   r   r   screen_updater   rT   rT   rU   r  7  s   

zConsole.update_screen_linesr  r   rY   r  r   	word_wrapshow_localsr  r  r  c                C   s,   ddl m} ||||||d}| | dS )a   Prints a rich render of the last exception and traceback.

        Args:
            width (Optional[int], optional): Number of characters used to render code. Defaults to 88.
            extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
            theme (str, optional): Override pygments theme used in traceback
            word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
            show_locals (bool, optional): Enable display of local variables. Defaults to False.
        r    )	Tracebackr  N)re  r  r   )rn   rY   r  r   r  r  r  re  rT   rT   rU   print_exceptionK  s   zConsole.print_exception)	r  r   r   re   r  ri   rh   
log_locals_stack_offsetr  r  c       	      
      s^  |
st  f}
|  | j|
||||||d} dur" fdd|D }t |	 }|jdr0dntj|j}|j	tj
d }|j}|rYdd |jj D }|t|d	d
 | j| ||  |||dg}| jD ]}||}qjg }|j}| j}| j}|D ]	}|||| q| jj}tj|| jddD ]}|| qW d   dS 1 sw   Y  dS )a  Log rich content to the terminal.

        Args:
            objects (positional args): Objects to log to the terminal.
            sep (str, optional): String to write between print data. Defaults to " ".
            end (str, optional): String to write at end of print data. Defaults to "\\n".
            style (Union[str, Style], optional): A style to apply to output. Defaults to None.
            justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
            overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None.
            emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.
            markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.
            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.
            log_locals (bool, optional): Boolean to enable logging of locals where ``log()``
                was called. Defaults to False.
            _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.
        r  Nc                    r  rT   r:   r  r   rT   rU   r    r   zConsole.log.<locals>.<listcomp><c                 S   s    i | ]\}}| d s||qS )__)rl   )r   keyrD  rT   rT   rU   r     s    zConsole.log.<locals>.<dictcomp>z	[i]locals)r  )r  pathline_no	link_pathFr  )r   r  inspectstackfilenamerl   rv  r  abspath
rpartitionr  linenoframef_localsitemsr^  r5   r*  r  r3  r   r  r-   rs   r   r7   r  rY   )rn   r  r   r   re   r  ri   rh   r  r  r  r   callerr  r  r  
locals_mapr]  r  r  r-   r  r   r  r   rT   r   rU   logh  sd   	





"zConsole.logc                 C   sF  | j r| jdd= dS | j | jdkry| jr2ddlm} || j| | jdd  | jdd= nW| | jdd }| jdd= |rz trX| j	j
}|dD ]}|| qPn| j	
| | j	  W n, tyx } z|j d|_ d}~ww W d   dS W d   dS W d   dS W d   dS 1 sw   Y  dS )z$Check if the buffer may be rendered.Nr   r    )displayTzG
*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***)r  r   r   rC  r  jupyterr  r   r   r  write
splitlinesflushUnicodeEncodeErrorreason)rn   r  r  r  r   r  rT   rT   rU   rX    sB   


"zConsole._check_bufferr   c                 C   s   g }|j }| j}| j}| jr'| j | j| W d   n1 s"w   Y  | j }| jr5|r5t	
|}|D ]\}}}	|rI||j|||d q7|rM|	sQ|| q7d|}
|
S )z)Render buffered output, and clear buffer.N)r   r`   r   )r^  r%  r`   r
  r/  r2  r  rc   r  r7   remove_colorr-   r  )rn   r   outputr^  r   r`   not_terminalr  r   r  renderedrT   rT   rU   r     s2   


zConsole._render_buffer)ri   r  passwordstreampromptr  r  c          	      C   s   d}|r%|   }| j|||dd W d   n1 sw   Y  | }| jr0| j| d}|r:t||d}|S |rH| j| | }|S t|}|S )an  Displays a prompt and waits for input from the user. The prompt may contain color / style.

        Args:
            prompt (Union[str, Text]): Text to render in the prompt.
            markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.
            emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.
            password: (bool, optional): Hide typed text. Defaults to False.
            stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.

        Returns:
            str: Text read from stdin.
        r   )ri   r  r   N)r  )	r  r   r   r`   r  r  r	   readlineinput)	rn   r  ri   r  r  r  
prompt_strr  resultrT   rT   rU   r    s$   
zConsole.inputr  r   r  c                C   s   | j sJ d| j2 |rddd | jD }nddd | jD }|r4| jdd= W d   |S W d   |S 1 s?w   Y  |S )a  Generate text from console contents (requires record=True argument in constructor).

        Args:
            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
            styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.
                Defaults to ``False``.

        Returns:
            str: String containing console contents.

        ITo export console contents set record=True in the constructor or instancer   c                 s   s(    | ]\}}}|r| |n|V  qd S r   r,   )r   r  r   r}  rT   rT   rU   r  /  s
    
z&Console.export_text.<locals>.<genexpr>c                 s   s    | ]	}|j s|jV  qd S r   )r  r  )r   r  rT   rT   rU   r  4  s    
N)r
  r/  r  r2  )rn   r  r   r  rT   rT   rU   export_text  s*   




zConsole.export_textr  c                C   sL   | j ||d}t|ddd}|| W d   dS 1 sw   Y  dS )a  Generate text from console and save to a given location (requires record=True argument in constructor).

        Args:
            path (str): Path to write text files.
            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
            styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.
                Defaults to ``False``.

        r	  wtrl  rd   N)r  openr  )rn   r  r  r   r  
write_filerT   rT   rU   	save_text=  s   
"zConsole.save_textr   r  code_formatinline_stylesr  r  c             	   C   s  | j sJ dg }|j}|pt}d}dtdtfdd}	|du r!tn|}
| j |rbtt| j	D ].\}}}|	|}|r\|
|}|jrOd|j d	| d
}|rZd| d	| dn|}|| q2ndi }tt| j	D ]8\}}}|	|}|r|
|}||t|d }|jrd| d|j d	| d
}n	d| d	| d}|| qmg }|j}| D ]\}}|r|d| d| d qd|}|
jd|||jj|jjd}|r| j	dd= W d   |S W d   |S 1 sw   Y  |S )a  Generate HTML from console contents (requires record=True argument in constructor).

        Args:
            theme (TerminalTheme, optional): TerminalTheme object containing console colors.
            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
            code_format (str, optional): Format string to render HTML, should contain {foreground}
                {background} and {code}.
            inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
                larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
                Defaults to False.

        Returns:
            str: String containing console contents as HTML.
        r
  r   r  rj   c                 S   s   |  dd dd ddS )zEscape html.&z&amp;r  z&lt;r8  z&gt;)replace)r  rT   rT   rU   escapei  s   z#Console.export_html.<locals>.escapeNz	<a href="z">z</a>z<span style="z</span>r    z<a class="rz" href="z<span class="rz.rz {}r   )code
stylesheet
foreground
background)r
  r^  r<   rz   CONSOLE_HTML_FORMATr/  r7   filter_controlsimplifyr2  get_html_styler  
setdefaultr   r  r  formatforeground_colorhexbackground_color)rn   r   r  r  r  	fragmentsr^  _themer  r  render_code_formatr  r   r}  r  r   style_numberstylesheet_rulesstylesheet_append
style_rulerendered_coderT   rT   rU   export_htmlK  sr   







)
))zConsole.export_htmlc                C   sP   | j ||||d}t|ddd}|| W d   dS 1 s!w   Y  dS )a  Generate HTML from console contents and write to a file (requires record=True argument in constructor).

        Args:
            path (str): Path to write html file.
            theme (TerminalTheme, optional): TerminalTheme object containing console colors.
            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
            code_format (str, optional): Format string to render HTML, should contain {foreground}
                {background} and {code}.
            inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
                larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
                Defaults to False.

        r  r  rl  r  N)r-  r  r  )rn   r  r   r  r  r  htmlr  rT   rT   rU   	save_html  s   "zConsole.save_htmlr  )rY  rC   rj   N)rj   r   r   r   r   )TNr   r   )r   r   )orQ   rR   rS   r[   rv  environr   r   rz   r]   r+   r   r   ry   r@   r   r\   r9   r   r$   r   r   floatr   r9  r}   r  setterr   r7   r   rC  rA   rF  r(   r&  r   r   r[  r\  r   r_  rb  r   r   r   r   r   r   r   r   rj  r   rd   rc   r-  r^   rs   rX   r_   rY   rZ   r  r   r  r0   r   r   r   r  r   r  r   r   r  r   r.   r  r   r-   r8   r  r{   r|   r  r  r  r   r  r?   r'   r  r)   r  r  r   r4   r  r  r  r  rX  r   r   r  r  r  r=   r-  r  r/  rT   rT   rT   rU   r   .  s  
 "	



k




	


"	
	


"	


5

9
	

5

$	

S


#	

^
#


 	


U
(" 
Sr   __main__zJSONRPC [i]request[/i]   g?z2.0subtract*      )minuend
subtrahendr   )jsonrpcr   paramsidzHello, World!z{'a': 1}z&Which one is correct team name in NBA?)zNew York BullszLos Angeles KingszGolden State WarriorsHuston Rocketr=  )questionrs   answer)answeredq1z	5 + 7 = ?)
            rD  z
12 - 8 = ?)r       r      rG  )r@  rA  q2)sportmaths)r   emptyquizfoor   )rj   rB   )r  rv  platformrt  r;  r(  r   r   r   collectionsdataclassesr   r   r   	functoolsr   r	   	itertoolsr
   timer   typesr   typingr   r   r   r   r   r   r   r   r   r   r   r   r   r   version_infor   r   r   typing_extensionsr   r!   r"   r#   r*  r$   r%   r  r&   r'   colorr(   r  r)   r  r*   r+   ri   r-   r  r  r.   r/   r   r0   r1   prettyr2   r3   r  r4   scoper5   r   r6   r  r7   r   r8   r9   styledr;   terminal_themer<   r=   r  r>   r?   r   r@   rA   r   rB   rY  rC   r  rE   r   r   rz   r  r{   r|   rP   r~   r  rL  rP  rO  rX   r^   r   r   r   r   r+  	Exceptionr   r   r   r   r   r   r   r   ry   r   r   rK  r'  r  rk  localr   r   r   r]   r   r   coloramar   r   rQ   r   r  r  r   rT   rT   rT   rU   <module>   s  
 @
	k	!'/$!


           
"