Skip to main content

Console

Struct Console 

Source
pub struct Console {
    pub file: Box<dyn Write + Send>,
    pub color_system: ColorSystem,
    pub theme: Theme,
    pub options: ConsoleOptions,
    pub quiet: bool,
    pub soft_wrap: bool,
    /* private fields */
}
Expand description

The main console for rendering rich output.

Fields§

§file: Box<dyn Write + Send>

The output writer.

§color_system: ColorSystem

Detected color system.

§theme: Theme

Current theme.

§options: ConsoleOptions

Default options.

§quiet: bool

If true, suppress all output.

§soft_wrap: bool

If true, text wraps at word boundaries.

Implementations§

Source§

impl Console

Source

pub fn new() -> Self

Create a new Console writing to stdout.

Source

pub fn with_file(file: Box<dyn Write + Send>) -> Self

Create a Console that writes to a file.

Source

pub fn set_width(&mut self, width: usize)

Set the console width (overrides auto-detected terminal width).

Source

pub fn set_height(&mut self, height: usize)

Set the console height.

Source

pub fn width(&self) -> usize

Get the effective width.

Source

pub fn height(&self) -> usize

Get the effective height.

Source

pub fn render_lines( &self, renderable: &dyn Renderable, options: &ConsoleOptions, style: Option<&Style>, _pad: bool, ) -> Vec<Vec<Segment>>

Render a renderable and return the segment lines.

Source

pub fn get_style(&self, name: &str, default: &str) -> Option<Style>

Look up a style by name from the theme.

Source

pub fn render_str(&self, text: &str, style: &str) -> Text

Render a string (with optional style).

Source

pub fn print(&mut self, objects: &[&dyn Renderable], sep: &str, end: &str)

Print one or more renderable objects, separated by sep, ending with end.

Source

pub fn println(&mut self, renderable: &dyn Renderable)

Print a single renderable followed by a newline.

Source

pub fn print_str(&mut self, text: &str)

Print a plain string (supports markup by default when markup is enabled).

Source

pub fn print_json(&mut self, data: &Value)

Print formatted JSON.

Source

pub fn clear(&mut self)

Clear the screen.

Source

pub fn show_cursor(&mut self)

Show the cursor.

Source

pub fn hide_cursor(&mut self)

Hide the cursor.

Source

pub fn set_window_title(&mut self, title: &str)

Set the terminal window title.

Source

pub fn color_ansi(&self, color: &Color) -> String

Get the ANSI escape string for a given color as this console supports.

Source

pub fn render( &self, renderable: &dyn Renderable, options: &ConsoleOptions, ) -> Vec<Segment>

Render a renderable by recursively flattening nested items into segments. This is equivalent to Python Rich’s Console.render(). It handles Group composition and any renderable that yields other renderables.

Source

pub fn measure( &self, renderable: &dyn Renderable, options: &ConsoleOptions, ) -> Measurement

Measure a renderable’s width constraints. Equivalent to Python Rich’s Measurement.get(console, options, renderable).

Source

pub fn rule( &mut self, title: impl Into<String>, characters: Option<&str>, style: Option<Style>, align: Option<AlignMethod>, )

Render a rule with the given title. Equivalent to Console.rule().

Source

pub fn bell(&mut self)

Output a bell character.

Source

pub fn line(&mut self, count: usize)

Output blank lines.

Source

pub fn log(&mut self, objects: &[&dyn Renderable])

Output a log entry with timestamp, caller info.

Source

pub fn push_theme(&mut self, theme: Theme)

Push a theme onto the stack.

Source

pub fn pop_theme(&mut self)

Pop the current theme, restoring the previous one.

Source

pub fn export_html(&self, renderable: &dyn Renderable) -> String

Export the current console output as an HTML document.

Renders the given renderable and wraps it in a styled HTML page.

Source

pub fn save_html( &self, path: impl AsRef<Path>, renderable: &dyn Renderable, ) -> Result<()>

Save rendered output as an HTML file.

Source

pub fn export_svg(&self, renderable: &dyn Renderable) -> String

Export the current console output as an SVG document.

Source

pub fn save_svg( &self, path: impl AsRef<Path>, renderable: &dyn Renderable, ) -> Result<()>

Save rendered output as an SVG file.

Source

pub fn export_text(&self, renderable: &dyn Renderable) -> String

Export the current console output as plain text (strips ANSI).

Source

pub fn save_text( &self, path: impl AsRef<Path>, renderable: &dyn Renderable, ) -> Result<()>

Save rendered output as a plain text file.

Source

pub fn set_quiet(&mut self, quiet: bool)

Set the quiet flag (suppress all output when true).

Source

pub fn quiet(self, quiet: bool) -> Self

Builder-style setter for quiet.

Source

pub fn set_soft_wrap(&mut self, soft_wrap: bool)

Set the soft-wrap flag (wrap text at word boundaries when true).

Source

pub fn soft_wrap(self, soft_wrap: bool) -> Self

Builder-style setter for soft_wrap.

Source

pub fn input(&mut self, prompt: &str, password: bool) -> String

Read a line of input from the user.

Writes prompt to the console, then reads a line from stdin. When password is true, the input is masked with * characters (using raw terminal mode via crossterm).

Source

pub fn screen(&mut self) -> ScreenContext

Create a ScreenContext that enters the alternate screen buffer. The context automatically exits the alternate screen when dropped.

Source

pub fn set_alt_screen(&mut self, enable: bool)

Enter or exit the alternate screen buffer by writing the corresponding escape sequences (\x1b[?1049h / \x1b[?1049l).

Source

pub fn is_terminal(&self) -> bool

Get whether the output is a terminal.

Source

pub fn set_size(&mut self, width: usize, height: usize)

Set the terminal size (overrides auto-detected dimensions).

Source

pub fn on_broken_pipe(&self)

Handle broken pipe errors gracefully.

In Rust, write() returns ErrorKind::BrokenPipe instead of raising SIGPIPE, so broken pipes are not fatal. The Console already uses let _ = write!(...) throughout, which silently discards all write errors including EPIPE. This method is provided for API compatibility with Python Rich and as a documentation point.

Source§

impl Console

Source

pub fn begin_capture(&mut self)

Start capturing all output. All subsequent writes to this console are redirected to an internal buffer. Call end_capture to stop capturing and retrieve the captured content.

Source

pub fn end_capture(&mut self) -> Capture

End capture mode and return the Capture containing all output written while capturing was active. The console’s output is restored to its original destination.

Source

pub fn capture<F: FnOnce(&mut Self)>(&mut self, f: F) -> String

Run the given closure with output captured, returning the captured text.

This is the most ergonomic way to capture output in Rust:

let mut console = Console::new();
let output = console.capture(|c| {
    c.print_str("Hello, world!");
});
assert_eq!(output, "Hello, world!");
Source

pub fn pager(&mut self, styles: bool) -> PagerContext

Get a PagerContext. Content rendered while the context is alive is collected and displayed through the system pager ($PAGER or less) when the context is dropped.

styles controls whether ANSI styles are preserved when paging.

Source

pub fn input_renderable(&mut self, prompt: &dyn Renderable) -> String

Display a Renderable prompt and read a line of input from stdin.

The prompt is rendered through the console’s current options and theme.

Source

pub fn print_exception(&mut self, _width: Option<usize>, _extra_lines: usize)

Print the current exception as a rich traceback.

In Rust, this is a best-effort rendering; it captures the current thread’s panic info if available. width overrides the output width, and extra_lines controls how many lines of source context to show around each frame.

Source

pub fn print_json_str(&mut self, json: &str)

Pretty-print a JSON string. Parses the string and renders it with syntax highlighting.

Source

pub fn render_to_lines( &self, renderable: &dyn Renderable, options: &ConsoleOptions, ) -> Vec<Vec<Segment>>

Render a renderable to a vector of segment lines.

This is the lower-level render entry point, returning raw lines instead of an ANSI string. Compare with render which returns flat segments.

Source

pub fn render_ansi(&self, text: &str) -> String

Render a plain string to ANSI text, applying the current theme and styles. Returns the ANSI-formatted string.

Source

pub fn export_svg_opts(&self, options: &ExportSvgOptions) -> String

Export the console output as an SVG document with explicit options.

This delegates to crate::export::export_svg with the given ExportSvgOptions.

Source

pub fn size(&self) -> ConsoleDimensions

Get the terminal size as ConsoleDimensions.

Source

pub fn is_dumb_terminal(&self) -> bool

Check if the terminal is a “dumb” terminal (no color support).

Source

pub fn is_alt_screen(&self) -> bool

Check if the console is currently in the alternate screen buffer.

Source

pub fn set_cursor_visible(&mut self, visible: bool)

Show or hide the cursor based on the boolean parameter.

true shows the cursor, false hides it. Tracks the current state so it can be queried via internal fields.

Source

pub fn use_theme(&mut self, theme: Theme) -> ThemeContext

Temporarily switch to a different theme. Returns a ThemeContext that restores the original theme when dropped.

§Example
let mut console = Console::new();
let custom = Theme::new();
{
    let _ctx = console.use_theme(custom);
    // console uses custom theme here
}
// original theme restored here
Source

pub fn clear_live(&mut self)

Clear the live display region. When in alt-screen mode, this clears the entire alternate screen. Otherwise, it’s equivalent to clear.

Source

pub fn set_live(&mut self, _live: &Live)

Set the active live display. Stores a reference to the [Live] renderer for integration with the console’s rendering pipeline.

Note: Live manages its own refresh cycle; this method is primarily for API compatibility with Python Rich.

Source

pub fn update_screen( &mut self, renderable: &dyn Renderable, options: Option<&ConsoleOptions>, )

Update the full screen (enter alt-screen, render content, exit).

Clears the screen and renders the given renderable. If options is None, the console’s current options are used.

Source

pub fn update_screen_lines( &mut self, lines: &[Vec<Segment>], options: Option<&ConsoleOptions>, )

Update the screen from pre-rendered lines of segments.

Takes already-rendered lines and displays them as the full screen content, clearing existing content first.

Source

pub fn push_render_hook(&mut self, hook: RenderHook)

Add a RenderHook to the console. Hooks are applied in order and can modify the rendered lines before they are displayed.

Source

pub fn pop_render_hook(&mut self) -> Option<RenderHook>

Remove and return the most recently added RenderHook, if any.

Trait Implementations§

Source§

impl Debug for Console

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Console

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.