o 7]hT= @sDUddlZddlZddlZddlZddlZddlmZmZddlm Z m Z ddl m Z ddl m Z ddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZmZmZdd lmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*ej+dkrddlm,Z,m-Z-m.Z.n ddl/m,Z,m-Z-m.Z.ddl0m1Z1m2Z2ddl3m3Z3ddl4m5Z5m6Z6ddl7m8Z8m9Z9ddl:m;Z;ddlm?Z?ddl@mAZAmBZBddlCmDZEddlFmGZGmHZHddlImJZJmKZKddlLmMZMmNZNddlOmPZPddlQmRZRddlSmTZTdd lUmVZVdd!lWmXZXdd"lYmZZZm[Z[dd#l\m]Z]dd$l^m_Z_m`Z`dd%lambZbmcZcdd&ldmeZemfZferJdd'lgmhZhdd(limjZjdd)lkmlZlemd*kZnee)eod+fgd+fZpe,d,Zqe,d-ZrGd.d/d/ZsesZtd0Zue;jve;jwd1ZxGd2d3d3e$Zye Gd4d5d5Zze.Gd6d7d7e-Z{e.Gd8d9d9e-Z|e)e|e{eofZ}e!e)e}eXfZ~eAZGd:d;d;eZGdd?d?ZGd@dAdAZGdBdCdCZGdDdEdEZGdFdGdGZGdHdIdIZddKedLedMedMefffdNdOZdLefdPdQZe;jwe;jve;je;jndRZdSdTeDZe GdUdVdVejZGdWdXdXeZdae%dYedZ<dd[d\ZdLefd]d^ZerIdd_lmZed`daGdbdcdcZeddkreZededfdgdJd`ddhdidjdkdldmdnedodpeeedgdJdqgdrdsdtdud`dvgdwdxdtdygdzd{dtd|d}d~eddSdS)N)ABCabstractmethod) dataclassfield)datetime)wraps)getpass)escape)isclass)islice)RLock) monotonic) FrameType ModuleType TracebackType)IO TYPE_CHECKINGAnyCallableDictIterableListMapping NamedTupleOptionalTextIOTupleTypeUnioncast))LiteralProtocolruntime_checkable)errorsthemes)_emoji_replace)FormatTimeCallable LogRender)Align AlignMethod) ColorSystem)Control) EmojiVariant)NullHighlighterReprHighlighterrender) Measurementmeasure_renderables)Pager SystemPager)Pretty is_expandable) rich_cast)Region) render_scope)Screen)Segment)Style StyleTypeStyled)DEFAULT_TERMINAL_THEME TerminalTheme)TextTextType)Theme ThemeStack)WindowsConsoleFeatures)LiveStatusWindowsrE)defaultleftcenterrightfull)foldcropellipsisignorec@s eZdZdS)NoChangeN)__name__ __module__ __qualname__r[r[:/usr/lib/python3/dist-packages/pip/_vendor/rich/console.pyrWOsrWa9
{code}
)256color16colorc@s$eZdZUdZeed< eed<dS)ConsoleDimensionszSize of the terminal.widthheightN)rXrYrZ__doc__int__annotations__r[r[r[r\r_ns r_c@seZdZUdZeed< eed< eed< eed< eed< eed< eed< d Z e e ed < d Z e e ed < d Ze eed < d Ze eed< d Ze eed< d Ze eed<edefddZd ddZeeeeeeeeed deeefdeeefdeeefd ee e efd ee e efd ee eefdee eefdee eefdee eefddfddZdeddfddZdeddfddZdededdfddZd S)!ConsoleOptionsz$Options for __rich_console__ method.sizelegacy_windows min_width max_width is_terminalencoding max_heightNjustifyoverflowFno_wrap highlightmarkuprareturncCs|jd S)z+Check if renderables should use ascii only.utf)rk startswithselfr[r[r\ ascii_onlyszConsoleOptions.ascii_onlycCstt}|j|_|S)zdReturn a copy of the options. Returns: ConsoleOptions: a copy of self. )re__new____dict__copy)rvoptionsr[r[r\rzs  zConsoleOptions.copy) r`rhrirmrnrorprqrar`c Cs|} t|tstd|| _| _t|ts|| _t|ts"|| _t|ts*|| _t|ts2|| _t|ts:|| _t|tsB|| _ t|tsJ|| _ t| tsb| durV| | _ | dur\dntd| | _ | S)zUpdate values, return a copy.rN) rz isinstancerWmaxrhrirmrnrorprqrlra) rvr`rhrirmrnrorprqrar{r[r[r\updates,         zConsoleOptions.updatecCs|}td||_|_|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)rzr}rhri)rvr`r{r[r[r\ update_widths zConsoleOptions.update_widthcCs|}||_|_|S)zUpdate the height, and return a copy. Args: height (int): New height Returns: ~ConsoleOptions: New Console options instance. )rzrlra)rvrar{r[r[r\ update_heights zConsoleOptions.update_heightcCs*|}td||_|_||_|_|S)aUpdate 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)rzr}rhrirarl)rvr`rar{r[r[r\update_dimensionss  z ConsoleOptions.update_dimensions)rrre)rXrYrZrbr_rdboolrcstrrmr JustifyMethodrnOverflowMethodrorprqrapropertyrwrz NO_CHANGErrWr~rrrr[r[r[r\rews~          %  rec@s&eZdZdZdedeffddZdS)RichCastz5An object that may be 'cast' to a console renderable.rrConsoleRenderablecCdSNr[rur[r[r\__rich__szRichCast.__rich__N)rXrYrZrbrrrr[r[r[r\rsrc@s&eZdZdZ      d dd Zd S) rz-An object that supports the console protocol.consoleConsoler{rerr RenderResultcCrrr[rvrr{r[r[r\__rich_console__sz"ConsoleRenderable.__rich_console__N)rrr{rerrr)rXrYrZrbrr[r[r[r\rsrc@seZdZdZdS) CaptureErrorz(An error in the Capture context manager.N)rXrYrZrbr[r[r[r\rsrc@s>eZdZdZddeddfddZdd d d deefd d ZdS)NewLinez$A renderable to generate new line(s)r%countrrNcCs ||_dSr)rrvrr[r[r\__init__s zNewLine.__init__rrr{reccstd|jVdS)N )r>rrr[r[r\rszNewLine.__rich_console__r%) rXrYrZrbrcrrr>rr[r[r[r\rsrc@sHeZdZdZdeeedededdfddZd d d ede fd d Z dS) ScreenUpdatez)Render a list of lines at a given offset.linesxyrrNcC||_||_||_dSr)_linesrr)rvrrrr[r[r\r# zScreenUpdate.__init__rrr{ccs@|j}tj}t|j|jD]\}}|||V|EdHqdSr)rr.move_to enumeraterr)rvrr{rroffsetliner[r[r\r(s  zScreenUpdate.__rich_console__) rXrYrZrbrr>rcrrerrr[r[r[r\r s"rc@s\eZdZdZdddZddd Zd eeed eed ee ddfd dZ de fddZ dS)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. rrrrNcCs||_d|_dSr)_console_result)rvrr[r[r\r:s zCapture.__init__cC|j|Sr)r begin_capturerur[r[r\ __enter__> zCapture.__enter__exc_typeexc_valexc_tbcCs|j|_dSr)r end_capturerrvrrrr[r[r\__exit__BszCapture.__exit__cCs|jdur td|jS)zGet the result of the capture.Nz strip_stylesr strip_links_render_bufferrshow _exit_buffer)rvrrrbuffersegmentscontentr[r[r\r{s    zPagerContext.__exit__NFF)rrr) rXrYrZrbrr6rrrrrrrr[r[r[r\rhs4  rc @seZdZdZ ddddededdfd d Zdd d edeeddfd dZ dddZ dee e dee dee ddfddZdS) ScreenContextziA context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage.rr hide_cursorstylerrNcCs"||_||_t|d|_d|_dS)NrF)rrr=screen_changed)rvrrrr[r[r\rs  zScreenContext.__init__r renderablescGsJ|rt|dkr t|n|d|j_|dur||j_|jj|jdddS)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%rNr)end)lenGroupr renderablerrprint)rvrrr[r[r\r~s  zScreenContext.updatecCs*|jd|_|jr|jr|jd|S)NTF)rset_alt_screenrr show_cursorrur[r[r\rs  zScreenContext.__enter__rrrcCs0|jr|jd|jr|jddSdSdS)NFT)rrrrrrr[r[r\rs  zScreenContext.__exit__r)rrr)rXrYrZrbrr@rRenderableTyperr~rrrrrr[r[r[r\rs<    rc@sneZdZdZdddddeddfd d Zededfd d Z     dddZ d dddde fddZ dS)ra$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. TfitrrrrrNcGs||_||_d|_dSr) _renderablesr_render)rvrrr[r[r\rrzGroup.__init__cCs|jdur t|j|_|jSr)rlistrrur[r[r\rs  zGroup.renderablesrrr{rer4cCs"|jr t|||jSt|j|jSr)rr5rr4rirr[r[r\__rich_measure__szGroup.__rich_measure__ccs|jEdHdSr)rrr[r[r\rszGroup.__rich_console__)rrr{rerrr4) rXrYrZrbrrrrrrrrr[r[r[r\rs& rTrrr.cs.dtdttfdtdtfffdd }|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.rrcs(tdtdtdtffdd }|S)zGConvert a method that returns an iterable of renderables in to a Group.argskwargsrrcs|i|}t|diS)Nr)r)rrr)rrr[r\_replacesz*group..decorator.._replace)rrr)rrr)rr\ decoratorszgroup..decorator)rrrr)rrr[rr\groups   rcCsVztWn tyYdSwt}|jj}dt|jvs!|dkr#dS|dkr)dSdS)z-Check if we're running in a Jupyter notebook.Fz google.colabZMQInteractiveShellTTerminalInteractiveShell) get_ipython NameError __class__rXr)ipythonshellr[r[r\ _is_jupyters r)standard256 truecolorwindowscCsi|]\}}||qSr[r[).0namesystemr[r[r\ rc@s<eZdZUdZeed<eedZe e ed<dZ e ed<dS)ConsoleThreadLocalsz(Thread local values for Console context. theme_stack)default_factoryrr buffer_indexN) rXrYrZrbrHrdrrrrr>rrcr[r[r[r\rs rc@s.eZdZdZedeedeefddZdS) RenderHookz(Provides hooks in to the render process.rrrcCsdS)aLCalled 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. Nr[)rvrr[r[r\process_renderablesszRenderHook.process_renderablesN)rXrYrZrbrrrrr[r[r[r\rsrrI_windows_console_featurescCs"tdurtSddlm}|atS)Nr%get_windows_console_features)r_windowsrrr[r[r\r/s  rcCstotj S)zDetect legacy Windows.)WINDOWSrvtr[r[r[r\detect_legacy_windows9r)initF)stripc<@s eZdZUdZejZeeefe d<dddddddddddddddddddddde dddddd d e e d d e e d e e de e de de ede de eede de ede ede ede e dede de de de ede de de d eeefd!e d"d#e e d$e d%e egefd&e egefde eeeff8d'd(Zd)efd*d+Zed)eefd,d-Zejd.eed)dfd/d-Zed)eefd0d1Zed)efd2d3Z e jd4ed)dfd5d3Z ed)e!fd6d7Z"d)e e#fd8d9Z$dd:d;Z%dde>jded)dfdldkZ>ed)efdmdnZ?e?jded)dfdodnZ?ddpdqZ@d)eAfdrdsZB ddte eCdue dve d)eDfdwdxZEddzed)dfd{d|ZFdd}e d)dfd~dZGddddddeHdedededed)df ddZIdde d)e fddZJdde d)e fddZKed)e fddZL dde de ed)dfddZMdddeHde e9d)eNfddZO ddeHde e9d)ePefddZQ ddddddeHde e9de eRde de d)eeef ddZSdddddddddedeeeRfde eTde eUde e de e de e d!e eVd)dfddZWdddeeeRfde eeRefd)eRfddZXddddddePe-dedede eTde e de e de e d)eeYfddZZ dddddde[dedeeeRfde\d)df ddZ]de^d)dfddÄZ_dddddƜde-dedede eeeRfde e d)df ddȄZ`dddddddddddddddɜde-dedede eeeRfde eTde eUde e de e de e de e de ede ede de e de d)df dd΄Za dddddddddddМ de ede-dedeefde de de de de de ee-ge-fde d)dfddڄZbdddۜdeHde ecde e9d)dfddބZd ߐddeeededed)dfddZeddddddddde edede ede de dePeeeffded)dfddZgeheijjfdedege ekfd)e=eeelee-fffddZmdddddddddyd de-dedede eeeRfde eTde e de e de e de ded)dfddZndddZodePed)efddZp ddddddde[de de de de eqd)ef ddZrdddde due d)efddZsddddede due d)dfd d Ztddddd de eude d e ed e d)ef ddZvddewdd dede eude d ed e d)df ddZxdS(ra] 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. emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None. 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. _environautoNFr!Tz[%X]) color_systemforce_terminal force_jupyterforce_interactive soft_wraprstderrfilequietr`rarno_colortab_sizerecordrqemoji emoji_variantrplog_timelog_pathlog_time_format highlighterrgsafe_box get_datetimeget_timerr )rrrrrr r r r rrrrr`rarrrrrqrrrprrrrHighlighterTypergrrrcCs|dur||_|durtn||_|jr| pd} | pd} ||_| |_| |_||_||_||_||_ ||_ ||_ |durBt oA|j n||_ | dur^|jd}|dur^|r^t||j } | durt|jd}|durt|rtt|} ||_| |_| |_|||_||_| |_||_|durd|_n|dkr||_nt||_t|_t|||d|_|pt|_||_|pt j!|_"|pt#|_$| |_%| dur| nd|jv|_&|dur|j'o|j( n||_)t|_*t+t,|durt-j.n|d|_/g|_0g|_1d|_2d |_3dS) N]dCOLUMNSLINESr) show_time show_path time_formatNO_COLOR)rF)4rr is_jupyterr _width_heightrr_markup_emoji_emoji_variant _highlightrrgrisdigitrc_force_terminal_filerr _color_system_detect_color_system COLOR_SYSTEMS threadingr rr* _log_render_null_highlighterrrrnowrr rrrrjis_dumb_terminalis_interactive_record_buffer_lockrrHr'DEFAULT_thread_locals_record_buffer _render_hooks_live_is_alt_screen)rvr r r r r rrrrr`rarrrrrqrrrprrrrrgrrrrcolumnsrr[r[r\rjs#            zConsole.__init__rrcCsd|jdt|jdS)Nz)r`rr0rur[r[r\__repr__szConsole.__repr__cCs(|jp |jr tjntj}t|d|}|S)z Get the file object to write to.rich_proxied_file)r/rsysstdoutgetattr)rvrr[r[r\rs z Console.filenew_filecC ||_dS)zSet a new file object.N)r/)rvrHr[r[r\rs cC|jjSzGet a thread local buffer.)r;rrur[r[r\rzConsole._buffercCrJrKr;rrur[r[r\ _buffer_indexrLzConsole._buffer_indexvaluecCs ||j_dSrrM)rvrOr[r[r\rN cCrJ)z!Get the thread local theme stack.)r;rrur[r[r\ _theme_stackrLzConsole._theme_stackcCs|jrtjS|jr |jrdStr"|jrtjSt}|jrtjStj S|j dd }|dvr4tjS|j dd }|d\}}}t |tj}|S)z"Detect color system from env vars.N COLORTERMr)r24bitTERM-)r&r- TRUECOLORrjr7rrgrr EIGHT_BITrrrlower rpartition _TERM_COLORSSTANDARD)rvwindows_console_features color_termterm _term_name_hyphencolorsr r[r[r\r1s( zConsole._detect_color_systemcCs|jd7_dS)z4Enter in to a buffer context, and buffer all output.r%N)rNrur[r[r\rzConsole._enter_buffercCs|jd8_|dS)z5Leave buffer context, and render content if required.r%N)rN _check_bufferrur[r[r\rs zConsole._exit_bufferliverJcCsF|j|jdurtd||_WddS1swYdS)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)rr>r& LiveError)rvrdr[r[r\set_lives   "zConsole.set_livecCs2|j d|_WddS1swYdS)zClear the Live instance.N)rr>rur[r[r\ clear_live+s"zConsole.clear_livehookcCs8|j|j|WddS1swYdS)zpAdd a new render hook to the stack. Args: hook (RenderHook): Render hook instance. N)rr=append)rvrhr[r[r\push_render_hook0s"zConsole.push_render_hookcCs6|j|jWddS1swYdS)z'Pop the last renderhook from the stack.N)rr=poprur[r[r\pop_render_hook9s "zConsole.pop_render_hookcCs ||S)z,Own context manager to enter buffer context.rrur[r[r\r>szConsole.__enter__r exc_value tracebackcC |dS)zExit buffer context.N)r)rvrrnror[r[r\rCrPzConsole.__exit__cCrp)z`Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.Nrmrur[r[r\rGrPzConsole.begin_capturecCs$||j}|jdd=||S)zhEnd capture mode and return captured string. Returns: str: Console output. N)rrr)rv render_resultr[r[r\rKs  zConsole.end_capturerrcCs|jj||ddS)aPush 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. rrN)rQrrvrrr[r[r\rVs zConsole.push_themecCs|jdS)z9Remove theme from top of stack, restoring previous theme.N)rQrrur[r[r\rarzConsole.pop_themecCs t|||S)aUse 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] )rrsr[r[r\ use_themees zConsole.use_themecCs|jdur t|jSdS)zpGet color system string. Returns: Optional[str]: "standard", "256" or "truecolor". N)r0_COLOR_SYSTEMS_NAMESrur[r[r\r qs  zConsole.color_systemcCst|jddpdS)zGet the encoding of the console file, e.g. ``"utf-8"``. Returns: str: A standard encoding string. rkutf-8)rGrrXrur[r[r\rk~szConsole.encodingcCsJ|jdur|jSt|jdd}z |durdWS|WSty$YdSw)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. NisattyF)r.rGr ValueError)rvrwr[r[r\rjs  zConsole.is_terminalcCs$|jdd}|dv}|jo|S)zxDetect dumb terminal. Returns: bool: True if writing to a dumb terminal, otherwise False. rTr)dumbunknown)rrrXrj)rv_termis_dumbr[r[r\r7s  zConsole.is_dumb_terminalc Cs$t|jj|j|jd|j|j|jdS)zGet default console options.r%)rlrfrgrhrirkrj)rerfrargr`rkrjrur[r[r\r{szConsole.optionsc CsV|jdur|jdurt|j|j|jS|jrtddSd}d}tr4zt\}}Wn;ty3Yn3wz tt j \}}Wn%t t tfyez tt j \}}Wn t t tfybYnwYnw|jd}|durx|rxt|}|jd}|dur|rt|}|pd}|pd}t|jdur||jn|j|jdur|S|jS)zGet the size of the console. Returns: ConsoleDimensions: A named tuple containing the dimensions. NPr r!)r'r(r_rgr7rosget_terminal_sizeOSErrorrE __stdin__filenoAttributeErrorrx __stdout__rrr-rc)rvr`rar@rr[r[r\rfsH     z Console.sizenew_sizecCs|\}}||_||_dS)zvSet a new size for the terminal. Args: new_size (Tuple[int, int]): New width and height. N)r'r()rvrr`rar[r[r\rfs cCrJ)zsGet the width of the console. Returns: int: The width (in characters) of the console. )rfr`rur[r[r\r`z Console.widthcCrI)zFSet width. Args: width (int): New width. N)r')rvr`r[r[r\r` cCrJ)zpGet the height of the console. Returns: int: The height (in lines) of the console. )rfrarur[r[r\rarzConsole.heightcCrI)zISet height. Args: height (int): new height. N)r()rvrar[r[r\rarcCs|tdS)z3Play a 'bell' sound (if supported by the terminal).N)controlr.bellrur[r[r\rrbz Console.bellcCs t|}|S)aA 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)rvcapturer[r[r\rszConsole.capturerrrcCst||||dS)aA 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. )rrr)r)rvrrrr[r[r\r%sz Console.pagerr%rcCs"|dksJd|t|dS)zqWrite new line(s). Args: count (int, optional): Number of new lines. Defaults to 1. rzcount must be >= 0N)rrrr[r[r\r<sz Console.linehomecCs.|r|ttdS|tdS)zClear the screen. Args: home (bool, optional): Also move the cursor to 'home' position. Defaults to True. N)rr.clearr)rvrr[r[r\rFsz Console.cleardotszstatus.spinnerg?g)@)spinner spinner_stylespeedrefresh_per_secondstatusrrrrrLcCs$ddlm}|||||||d}|S)atDisplay a status and spinner. Args: status (RenderableType): A status renderable (str or Text typically). 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%rK)rrrrr)rrL)rvrrrrrrLstatus_renderabler[r[r\rQs zConsole.statusrcCs$|jr|js|t|dSdS)zqShow or hide the cursor. Args: show (bool, optional): Set visibility of the cursor. TF)rjrgrr.r)rvrr[r[r\rrs zConsole.show_cursorenablecCs.d}|jr|js|t|d}||_|S)aEnables 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)rjrgrr. alt_screenr?)rvrchangedr[r[r\r}s  zConsole.set_alt_screencCs|jS)zCheck if the alt screen was enabled. Returns: bool: True if the alt screen was enabled, otherwise False. )r?rur[r[r\ is_alt_screenszConsole.is_alt_screenrrcCst|||pddS)auContext 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)rr)r)rvrrr[r[r\rs zConsole.screenr{rr{cCst||p|j|}|S)aMeasure 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. )r4rr{)rvrr{ measurementr[r[r\measureszConsole.measurec cs|p|j}|jdkr dSt|}t|dr!t|s!|||}nt|tr7|j||j |j d}|||}n t d|dzt |}WntyVt d|dwt}|D]}t||rf|Vq[|||EdHq[dS) akRender 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)rprqzUnable to render zC; A str, Segment or object with __rich_console__ method is requiredzobject z is not renderable)r{rir:hasattrr rr|r render_strrprqr&NotRenderableErroriter TypeErrorr>r3) rvrr{_optionsrender_iterabletext_renderable iter_render_Segment render_outputr[r[r\r3s8         zConsole.render)rpad new_linesrrc Cs|j]|p|j}|||}|rt||}tttj||j||dd|j }|j durW|j t |} | dkrW|rFtd|j|tdgntd|j|gg} | | | |WdS1scwYdS)aGRender 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_linesrNrrAr) rr{r3r> apply_stylerr split_and_crop_linesrirarextend) rvrr{rrrrender_options _renderedr extra_linespad_liner[r[r\ render_liness6    $zConsole.render_linesr)rrmrnrrqrprtextrmrnrEcCs|p|duo|j} |p|duo|j} |p|duo|j} | r-t||| |jd} || _|| _nt| r7t||jdn||||d} | rE|pD|j nd} | durX| t | }| | |S| S)aConvert 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)rrr)default_variant)rmrnr) r*r)r, render_markupr+rmrnrEr(rr copy_styles)rvrrrmrnrrqrpr emoji_enabledmarkup_enabledhighlight_enabled rich_text _highlighterhighlight_textr[r[r\r!s8   zConsole.render_str)rNrrNc Cst|tr|Sz|j|}|durt|}|jr|WS|WStjyI}z|dur9| |WYd}~St d|d|dd}~ww)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. NzFailed to get style z; ) r|r?rQrparselinkrzr&StyleSyntaxError get_style MissingStyle)rvrrNrerrorr[r[r\r\s"   zConsole.get_stylermrrqrpobjectsseprcs2g}|jgj} dvrdtddffdd } | t} |s)|dur,|jr,|j} d fdd } |D]F} t| } t| trP| |j| ||| d q9t| t rZ| | q9t| t rg| | q9t | rw| t | | d q9| | t| q9| |j dur||j fd d |D}|S)aCombine 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. )rOrPrQrrrNcst|ttdSr)r+rr,)r)_appendrmr[r\ align_appendsz2Console._collect_renderables..align_appendcs2rtd}|dd=dSdS)N)rmr)rEjoin)sep_text)rirrmrrr[r\ check_texts z0Console._collect_renderables..check_text)rrqr)rcg|]}t|qSr[rArrrr[r\ rz0Console._collect_renderables..rrN)rirr5r,rr:r|rrrErr9r8rr)rvrrrrmrrqrpr append_textrrrrr[)rrirrmrrrr\_collect_renderableszsD       zConsole._collect_renderablesu─z rule.linerP) charactersraligntitlerrcCs*ddlm}|||||d}||dS)uDraw 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)rrrrN)rulerr)rvrrrrrrr[r[r\rs z Console.rulercGsJ|js#||jdd|DWddS1swYdSdS)zInsert non-printing control codes. Args: control_codes (str): Control codes, such as those that may move the cursor. cs|]}|jVqdSr)segment)r_controlr[r[r\ z"Console.control..N)r7rr)rvrr[r[r\rs "zConsole.controlrAr)rrrrpc Gs4|dd|D}|j|||ddddd|d dS)aOutput 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``. css|]}t|VqdSr)r)r_objectr[r[r\rszConsole.out..FTrV)rrprrqrornrTrN)rr)rvrrrrpr raw_outputr[r[r\outs z Console.out)rrrrmrnrorrqrpr`rarTr new_line_startrorTrc Gs|stf}| dur |j} | r|durd}|durd}d} |jdd}||j||||||| d}|D]}||}q5|jj||| durLt| |jnt | ||| d}g}|j }|j }|durm|D] }||||qbn|D]}|t |||||qo|rtddd |Dd kr|d t | r|jj }t j||jdd D]}||qn|j |WddSWddS1swYdS) 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``. new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``. NTrVFr)rmrnr`rarorqrprcsrr)rrrr[r[r\rZrz Console.print..r%rr)rr r=rrr{r~minr`rrr3r>rrrr splitlinesinsertrrr)rvrrrrmrnrorrqrpr`rarTr rr render_hooksrrhr new_segmentsrr3r buffer_extendrr[r[r\rsz%   +"z Console.print) dataindentrp skip_keys ensure_asciicheck_circular allow_nanrN sort_keysjsonrrrrrrrc Csxddlm} |dur| j|||||||| | d } nt|ts&td|d| |||||||| | d } |j| dddS) aPretty prints JSON. Output will be valid JSON. Args: json (Optional[str]): A string containing JSON. data (Any): If json is not supplied, then encode this data. indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2. highlight (bool, optional): Enable highlighting of output: Defaults to True. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. check_circular (bool, optional): Check for circular references. Defaults to True. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. default (Callable, optional): A callable that converts values that can not be encoded in to something that can be JSON encoded. Defaults to None. sort_keys (bool, optional): Sort dictionary keys. Defaults to False. r)JSONN)rrprrrrrNrz/json must be str. Did you mean print_json(data=z) ?T)r )pip._vendor.rich.jsonr from_datar|rrr) rvrrrrprrrrrNrrjson_renderabler[r[r\ print_jsongs:    zConsole.print_json)regionr{rc Csz|jstd|p |j}|dur!d}}||j|jp|j}n |\}}}}|||}|j||d} || ||dS)aUpdate 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_screenNrr) rr& NoAltScreenr{rrirarupdate_screen_lines) rvrrr{rrrr`rarr[r[r\ update_screens    zConsole.update_screenrrrrcCs>|jstdt|||}||}|j||dS)aUpdate 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. rN)rr&rrr3rrrc)rvrrr screen_updaterr[r[r\rs      zConsole.update_screen_linesrr r[r`rr word_wrap show_localssuppress max_framesrrrrrc Cs0ddlm}||||||||d} || dS)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. suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. r%) TracebackrN)rorr) rvr`rrrrrrrror[r[r\print_exceptions  zConsole.print_exceptionr currentframecCsp|d7}|}|dur)|r|r|j}|d8}|r|s|dus J|jj|j|jfSt|}|j|j|j jfS)aEGet caller frame information. Args: offset (int): the caller offset within the current frame stack. currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to retrieve the current frame. Defaults to ``inspect.currentframe``. Returns: Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and the dictionary of local variables associated with the caller frame. Raises: RuntimeError: If the stack offset is invalid. r%N) f_backf_code co_filenamef_linenof_localsinspectstackfilenamelinenoframe)rrr  frame_infor[r[r\_caller_frame_infos  zConsole._caller_frame_info) rrrrmrrqrp log_locals _stack_offsetrrc  s^| stf} |jdd} ||j| ||||||d} dur)fdd| D} || \} }}| dr8dntj| }| tj d}|rZdd| D}| t |d d |j || ||||d g} | D]}|| } qjg}|j}|j}|j}| D] }||||q|jj}tj||jd d D]}||qWddS1swYdS)aLog 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. Nrcrr[rArrr[r\rMrzConsole.log...z [i]locals)r)rpathline_no link_pathFr)rr=rr rtrrabspathrYritemsrir<r4rrrr3r{rr>rr`)rvrrrrmrrqrprrrrrr rlocalsrr locals_maprhrrr3rrrrr[rr\log s^   "z Console.logc CsF|jr |jdd=dS|j|jdkry|jr2ddlm}||j||jdd|jdd=nW||jdd}|jdd=|rz trX|j j }| dD]}||qPn|j ||j Wn,t yx}z|jd|_d}~wwWddSWddSWddSWddS1swYdS)z$Check if the buffer may be rendered.Nrr%)displayTzG *** You may need to add PYTHONIOENCODING=utf-8 to your environment ***)rrrrNr&jupyterrrrrwriterflushUnicodeEncodeErrorreason)rvrrrrrr[r[r\rcrsB       "zConsole._check_bufferrc Csg}|j}|j}|j}|jr'|j|j|Wdn1s"wY|j }|jr5|r5t |}|D]\}}} |rI||j |||dq7|rM| sQ||q7d |} | S)z)Render buffered output, and clear buffer.N)r rgr) rir0rgrr9r<rrjrr> remove_colorr3r) rvroutputrir rg not_terminalrrrrenderedr[r[r\rs2   zConsole._render_buffer)rqrpasswordstreampromptr&r'c Csd}|r%|}|j|||ddWdn1swY|}|jr0|j|d}|r:t||d}|S|rH|j||}|St|}|S)a5Displays a prompt and waits for input from the user. The prompt may contain color / style. It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded. 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)rqrrN)r') rrrrgrrrreadlineinput) rvr(rqrr&r' prompt_strrresultr[r[r\r*s$    z Console.inputrrrcCs|jsJd|j2|rddd|jD}n ddd|jD}|r4|jdd=Wd|SWd|S1s?wY|S)aGenerate 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 instancercss(|]\}}}|r||n|VqdSrr2)rrr_r[r[r\rs  z&Console.export_text..css|] }|js|jVqdSr)rrrr[r[r\rs N)rr9rr<)rvrrrr[r[r\ export_texts*     zConsole.export_textrcCsL|j||d}t|ddd}||WddS1swYdS)aGenerate 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-wtrvrkN)r0openr)rvrrrr write_filer[r[r\ save_texts  "zConsole.save_textrr code_format inline_stylesr7r8c Cs|jsJdg}|j}|pt}d}|durtn|} |j|rYtt|jD].\} } } t | } | rS| |} | j rFd| j d| d} | rQd| d| dn| } || q)ndi}tt|jD]8\} } } t | } | r| |} | | t |d }| j rd |d | j d| d} n d |d| d} || qdg}|j}|D]\}}|r|d |d|dqd|}| jd|||jj|jjd}|r|jdd=Wd|SWd|S1swY|S)aGenerate 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.rNz zz filter_controlsimplifyr<r get_html_styler setdefaultrrrformatforeground_colorhexbackground_color)rvrrr7r8 fragmentsri_themer;render_code_formatrrr/rr style_numberstylesheet_rulesstylesheet_append style_rule rendered_coder[r[r\ export_htmlsp         ) ))zConsole.export_htmlcCsP|j||||d}t|ddd}||WddS1s!wYdS)aGenerate 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. r6r1rvr2N)rOr3r)rvrrrr7r8htmlr4r[r[r\ save_htmlMs "zConsole.save_htmlr)rdrJrrN)rrrrrr)TNrr)rr)yrXrYrZrbrenvironrrrrdr1rr"rrGrrcr@r/rr)rrfloatrrCrrsetterrr>rrNrHrQr-r1rrrfrgrrjrlrrrrrrrrrtr rkrjr7rer{r_rfrr`rarrrr6rrrrrrrrrrr4rrr3r?rrrrrrrrrFr,rr.rrrrr;rrrr staticmethodrrrrr rrcrrr*r0r5rDrOr>rQr[r[r[r\rDs #       p           -     !     5  9    <  $  M    #      e      A #    # %    R&*, O r__main__zJSONRPC [i]request[/i]g?z2.0subtract*)minuend subtrahendr )jsonrpcrparamsidz Hello, World!z{'a': 1}z&Which one is correct team name in NBA?)zNew York BullszLos Angeles KingszGolden State Warriors Huston Rocketr`)questionr{answer)answeredq1z 5 + 7 = ?) rgz 12 - 8 = ?)r%rr ri)rcrdq2)sportmaths)remptyquizfoor)rrrI)rrplatformrEr3abcrr dataclassesrrr functoolsrrrPr r itertoolsr r timer typesrrrtypingrrrrrrrrrrrrrrr version_infor"r#r$pip._vendor.typing_extensionsrr&r'r(r4r)r*rr+r,colorr-rr.rr/rr0r1rqr3rrr4r5rr6r7prettyr8r9protocolr:rr;scoper<rr=rr>rr?r@styledrBterminal_themerCrDrrErFrrGrHrrIrdrJrrLrrrrrrrWrr>rWr[rZr_rerrrrr5 ExceptionrrrrrrrrrrrrVr2rrulocalrrrrdrrpip._vendor.coloramarrrXrrreprrr[r[r[r\s         D                 {  !'/$!     5"