Skip to main content

Console

Struct Console 

Source
pub struct Console<W: Write = Stdout> { /* private fields */ }
Expand description

The main console for rendering output.

Console is generic over the writer type, allowing it to write to any type that implements Write. The default is Stdout, but you can use Vec<u8> for testing or any other writer.

§Example

use rich_rs::Console;

let mut console = Console::new();
console.print_text("Hello, World!").unwrap();

§Testing with capture

use rich_rs::Console;

let mut console = Console::capture();
console.print_text("Hello").unwrap();
assert!(console.get_captured().contains("Hello"));

Implementations§

Source§

impl Console<Stdout>

Source

pub fn new() -> Self

Create a new console writing to stdout.

Source

pub fn new_with_record() -> Self

Create a new console with recording enabled.

When recording is enabled, all segments written via print() are captured in an internal buffer that can be exported as SVG/HTML.

§Example
use rich_rs::Console;

let mut console = Console::new_with_record();
console.print_text("Hello, World!").unwrap();
let svg = console.export_svg("Example", None, true, None, 0.61, None);
Source

pub fn with_theme(self, name: &str) -> Self

Set the console theme by name.

This sets the base theme for all renderables. Renderables like Pretty and Syntax will automatically use this theme unless they have an explicit theme set.

Available themes: “default”, “dracula”, “gruvbox-dark”, “nord”

§Example
use rich_rs::Console;

let console = Console::new().with_theme("dracula");
Source

pub fn with_options(options: ConsoleOptions) -> Self

Create a console with specific options.

Console state fields (theme_stack, markup_enabled, etc.) are initialized from the provided options, ensuring that nested renderables see the correct state when a temp Console is created from options.

Source§

impl Console<Vec<u8>>

Source

pub fn capture() -> Self

Create a console that captures output to a buffer.

Use this for testing to capture console output.

§Example
use rich_rs::Console;

let mut console = Console::capture();
console.print_text("Hello").unwrap();
let output = console.get_captured();
assert!(output.contains("Hello"));
Source

pub fn capture_with_options(options: ConsoleOptions) -> Self

Create a capture console with specific options.

Source

pub fn get_captured(&self) -> String

Get captured output as a string.

Source

pub fn get_captured_bytes(&self) -> &[u8]

Get captured output as bytes.

Source

pub fn clear_captured(&mut self)

Clear the capture buffer.

Source§

impl<W: Write> Console<W>

Source

pub fn with_writer(writer: W, options: ConsoleOptions) -> Self

Create a console with a custom writer.

Console state fields are initialized from the provided options, ensuring that nested renderables see the correct state.

Source

pub fn options(&self) -> &ConsoleOptions

Get the console options.

Source

pub fn options_mut(&mut self) -> &mut ConsoleOptions

Get mutable access to console options.

§Warning

Modifying state fields (markup_enabled, emoji_enabled, highlight_enabled, tab_size, color_system, theme_stack) via options_mut() will NOT update the corresponding Console fields. This can cause inconsistent behavior.

Use the specific setters (set_markup_enabled(), set_tab_size(), etc.) to modify these fields, which keep both in sync. Or call sync_from_options() after modifying options directly.

This method is safe for modifying non-state fields like max_width, justify, etc.

Source

pub fn sync_from_options(&mut self)

Sync Console fields from options.

Call this after modifying state fields via options_mut() to ensure Console fields stay in sync with options.

Source

pub fn options_with_state(&self) -> ConsoleOptions

Get a copy of options with current console state.

Since Console setters now keep self.options in sync, this just clones the options. It ensures caller-provided options will have correct state if they were derived from console.options().

§Note

If a caller creates ConsoleOptions from scratch (not derived from console.options()), they should ensure state fields (theme_stack, markup_enabled, etc.) are set appropriately. The console state is passed through ConsoleOptions, not through the Console reference.

Source

pub fn width(&self) -> usize

Get the terminal width.

Source

pub fn height(&self) -> usize

Get the terminal height.

Source

pub fn size(&self) -> (usize, usize)

Get the terminal size as (width, height).

Source

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

Set the terminal size.

Source

pub fn is_terminal(&self) -> bool

Check if the console is writing to a terminal.

Source

pub fn is_dumb_terminal(&self) -> bool

Check if the terminal is considered “dumb” (no cursor control).

Source

pub fn set_force_terminal(&mut self, force: Option<bool>)

Force terminal mode on or off.

Source

pub fn color_system(&self) -> Option<ColorSystem>

Get the color system.

Source

pub fn set_color_system(&mut self, system: Option<ColorSystem>)

Set the color system.

Source

pub fn is_markup_enabled(&self) -> bool

Check if markup is enabled by default.

Source

pub fn set_markup_enabled(&mut self, enabled: bool)

Enable or disable markup parsing by default.

Source

pub fn is_emoji_enabled(&self) -> bool

Check if emoji replacement is enabled by default.

Source

pub fn set_emoji_enabled(&mut self, enabled: bool)

Enable or disable emoji replacement by default.

Source

pub fn is_highlight_enabled(&self) -> bool

Check if highlighting is enabled by default.

Source

pub fn set_highlight_enabled(&mut self, enabled: bool)

Enable or disable highlighting by default.

Source

pub fn tab_size(&self) -> usize

Get the tab size.

Source

pub fn encoding(&self) -> &str

Get the configured output encoding.

Source

pub fn set_encoding(&mut self, encoding: impl Into<String>)

Set the output encoding.

Source

pub fn set_tab_size(&mut self, size: usize)

Set the tab size.

Source

pub fn is_quiet(&self) -> bool

Check if quiet mode is enabled.

Source

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

Enable or disable quiet mode (suppress all output).

Source

pub fn theme_name(&self) -> &str

Get the current theme name.

Returns the name of the base theme (e.g., “default”, “dracula”).

Source

pub fn set_theme(&mut self, name: &str)

Set the theme by name.

This replaces the base theme. Any pushed themes remain on the stack.

§Example
use rich_rs::Console;

let mut console = Console::new();
console.set_theme("dracula");
assert_eq!(console.theme_name(), "dracula");
Source

pub fn theme_stack(&self) -> &ThemeStack

Get a reference to the theme stack.

Source

pub fn theme_stack_mut(&mut self) -> &mut ThemeStack

Get a mutable reference to the theme stack.

§Warning

Modifying the theme stack directly will NOT update self.options.theme_stack. This can cause nested renderables (which read from options) to see stale theme data.

Prefer using push_theme() and pop_theme() which keep both stacks in sync. If you need direct access, call sync_theme_to_options() after modifications.

Source

pub fn sync_theme_to_options(&mut self)

Sync the options theme stack from the Console theme stack.

Call this after modifying the theme stack via theme_stack_mut() to ensure nested renderables see the updated theme.

Source

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

Push a new theme onto the stack.

If inherit is true, the new theme inherits styles from the current theme.

Source

pub fn pop_theme(&mut self) -> Result<(), ThemeError>

Pop the top theme from the stack.

Returns an error if trying to pop the base theme.

Source

pub fn render_lines<R: Renderable + ?Sized>( &self, renderable: &R, options: Option<&ConsoleOptions>, style: Option<Style>, pad: bool, new_lines: bool, ) -> Vec<Vec<Segment>>

Render to a grid of lines (for layout).

§Arguments
  • renderable - The object to render.
  • options - Optional custom options, or None to use console defaults. If provided, ensure these options include the console state fields (theme_stack, markup_enabled, etc.) by deriving from console.options().
  • style - Optional style to apply to all segments.
  • pad - Whether to pad lines to the full width.
  • new_lines - Whether to include newline segments at the end of lines.
Source

pub fn render_str( &self, text: &str, markup: Option<bool>, emoji: Option<bool>, highlight: Option<bool>, highlighter: Option<&dyn Highlighter>, ) -> Text

Render a string to Text with optional markup/emoji/highlight.

This method converts a string to a Text object, applying:

  • Markup parsing (if enabled)
  • Emoji replacement (if enabled)
  • Syntax highlighting (if highlighter provided)
§Arguments
  • text - The text to render.
  • markup - Whether to parse markup, or None to use console default.
  • emoji - Whether to replace emoji codes, or None to use console default.
  • highlight - Whether to apply highlighting, or None to use console default.
  • highlighter - Optional highlighter to apply.
Source

pub fn write_raw(&mut self, data: &[u8]) -> Result<()>

Write raw bytes to the output.

Source

pub fn write_str(&mut self, s: &str) -> Result<()>

Write a string directly to the output.

Source

pub fn print_text(&mut self, text: &str) -> Result<()>

Print plain text with a newline.

Source

pub fn print_styled(&mut self, text: &str, style: Style) -> Result<()>

Print styled text with a newline.

Source

pub fn print_traceback(&mut self, traceback: &Traceback) -> Result<()>

Print a traceback.

This renders the given Traceback to the console with appropriate styling. It’s the Rust equivalent of Python Rich’s console.print_exception().

§Example
use rich_rs::{Console, traceback::{Traceback, Trace, Stack, Frame}};

let frame = Frame::new("main.rs", 42, "main");
let stack = Stack::new("Error", "Something went wrong").with_frame(frame);
let trace = Trace::new(vec![stack]);
let tb = Traceback::new(trace);

let mut console = Console::new();
console.print_traceback(&tb).unwrap();
Source

pub fn print_segment(&mut self, segment: &Segment) -> Result<()>

Print a segment.

Source

pub fn print_segments(&mut self, segments: &Segments) -> Result<()>

Print multiple segments.

Uses streaming output that avoids resetting styles between segments, which prevents visual artifacts like black hairlines between colored lines.

Source

pub fn print<R: Renderable + ?Sized>( &mut self, renderable: &R, style: Option<Style>, justify: Option<JustifyMethod>, overflow: Option<OverflowMethod>, no_wrap: bool, end: &str, ) -> Result<()>

Print a renderable object.

This is the main method for printing content to the console. It renders the object to segments and writes them to the output.

§Arguments
  • renderable - The object to render and print.
  • style - Optional style to apply to all output.
  • justify - Optional justify override.
  • overflow - Optional overflow override.
  • no_wrap - Whether to disable word wrapping.
  • end - String to print at the end (default “\n”).
Source

pub fn log<R: Renderable + ?Sized>( &mut self, renderable: &R, file: Option<&str>, line: Option<u32>, ) -> Result<()>

Log a renderable with timestamp prefix.

Similar to print(), but adds a timestamp prefix in [HH:MM:SS] format. Optionally displays the source file and line number.

§Arguments
  • renderable - The object to render and log.
  • file - Optional source file name (use file!() macro at call site).
  • line - Optional line number (use line!() macro at call site).
§Example
use rich_rs::{Console, Text};

let mut console = Console::new();
// Using the log! macro (recommended)
rich_rs::log!(console, &Text::plain("Server starting..."));

// Or directly with file/line
console.log(&Text::plain("Message"), Some(file!()), Some(line!())).unwrap();
Source

pub fn rule(&mut self, title: Option<&str>) -> Result<()>

Render a line (horizontal rule).

Source

pub fn line(&mut self, count: usize) -> Result<()>

Print new line(s).

Source

pub fn clear(&mut self) -> Result<()>

Clear the screen.

Source

pub fn clear_line(&mut self) -> Result<()>

Clear the current line.

Source

pub fn move_cursor(&mut self, x: u16, y: u16) -> Result<()>

Move the cursor to a specific position.

Source

pub fn show_cursor(&mut self, show: bool) -> Result<bool>

Show or hide the cursor.

Source

pub fn enter_alt_screen(&mut self) -> Result<bool>

Enter alternate screen mode.

The alternate screen is a separate screen buffer that can be used for full-screen applications. Call leave_alt_screen when done.

Source

pub fn leave_alt_screen(&mut self) -> Result<bool>

Leave alternate screen mode.

Source

pub fn is_alt_screen(&self) -> bool

Check if alternate screen mode is active.

Source

pub fn set_alt_screen(&mut self, enable: bool) -> Result<bool>

Enable or disable alternate screen mode (Rich parity).

When enabling, Rich emits ENABLE_ALT_SCREEN followed by HOME. When disabling, Rich emits DISABLE_ALT_SCREEN.

Source

pub fn screen( &mut self, hide_cursor: bool, style: Option<Style>, ) -> Result<ScreenContext<'_, W>>

Enter alternate screen mode with a context guard.

This returns a crate::ScreenContext that automatically leaves alternate screen mode when dropped, providing RAII semantics for full-screen applications.

§Arguments
  • hide_cursor - Whether to hide the cursor while in alternate screen mode.
  • style - Optional background style for the screen.
§Example
use rich_rs::{Console, Text};

let mut console = Console::new();
let mut screen = console.screen(true, None)?;
screen.update(Text::plain("Hello!"))?;
// Screen is automatically exited when `screen` is dropped
Source

pub fn set_window_title(&mut self, title: &str) -> Result<bool>

Set the window title.

Source

pub fn bell(&mut self) -> Result<()>

Ring the terminal bell.

Source

pub fn live_start( &mut self, renderable: Box<dyn Renderable + Send + Sync>, vertical_overflow: VerticalOverflowMethod, ) -> (usize, bool)

Source

pub fn live_update( &mut self, id: usize, renderable: Box<dyn Renderable + Send + Sync>, )

Source

pub fn live_set_vertical_overflow( &mut self, id: usize, vertical_overflow: VerticalOverflowMethod, )

Source

pub fn live_stop( &mut self, id: usize, ) -> Option<Box<dyn Renderable + Send + Sync>>

Source

pub fn live_clear(&mut self)

Source

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

Read a line of input from the user.

This method displays a prompt and reads a line of input from stdin. If password is true, input is masked (not echoed to the terminal).

§Arguments
  • prompt - The text to display as a prompt.
  • password - If true, input will be masked for password entry.
§Returns

The user’s input as a string (without trailing newline).

§Errors

Returns an error if reading from stdin fails or if the input stream reaches EOF unexpectedly.

§Example
use rich_rs::{Console, Text};

let mut console = Console::new();
let prompt = Text::plain("Enter your name: ");
let name = console.input(&prompt, false)?;
println!("Hello, {}!", name);
Source

pub fn measure<R: Renderable + ?Sized>( &self, renderable: &R, options: Option<&ConsoleOptions>, ) -> Measurement

Measure a renderable object.

Returns the minimum and maximum width required to render the object.

§Arguments
  • renderable - The object to measure.
  • options - Optional custom options, or None to use console defaults. If provided, ensure these options include the console state fields by deriving from console.options().
Source

pub fn out( &mut self, text: &str, style: Option<Style>, _highlight: Option<bool>, ) -> Result<()>

Low-level output that bypasses the full rendering pipeline.

Unlike print(), this won’t pretty print, wrap text, or apply markup, but will optionally apply a basic style and highlighting.

Source

pub fn export_text(&self, clear: bool, styles: bool) -> String

Export recorded output as plain text.

Requires record=true to be set. If styles is false, ANSI codes are stripped from the output (only plain text is returned).

Source

pub fn save_text(&self, path: &str, clear: bool, styles: bool) -> Result<()>

Save export_text output to a file.

Source

pub fn push_render_hook( &mut self, hook: Box<dyn Fn(&Segments) -> Segments + Send + Sync>, )

Push a render hook that intercepts/transforms rendered segments before output.

Source

pub fn pop_render_hook(&mut self)

Remove the last render hook.

Source

pub fn status( &self, status: &str, spinner: Option<&str>, spinner_style: Option<Style>, speed: Option<f64>, refresh_per_second: Option<f64>, ) -> Status

Create and return a Status spinner.

This is a convenience method that creates a Status with the console’s default settings.

Source

pub fn print_json( &mut self, json: &str, indent: usize, highlight: bool, sort_keys: bool, ) -> Result<()>

Pretty-print JSON.

Parse, format, highlight, and print JSON content.

Source§

impl Console<Stdout>

Source

pub fn render<R: Renderable + ?Sized>(&self, renderable: &R) -> Segments

Render a Renderable to Segments.

Source

pub fn render_with_options<R: Renderable + ?Sized>( &self, renderable: &R, options: &ConsoleOptions, ) -> Segments

Render a Renderable with custom options.

Source

pub fn update_screen_lines( &mut self, lines: &[Vec<Segment>], x: u16, y: u16, ) -> Result<()>

Update rendered lines at an offset on the alternate screen.

This is the Rust equivalent of Rich’s Console.update_screen_lines.

Source§

impl Console<Stdout>

Source

pub fn pager(&self, options: Option<PagerOptions>) -> PagerContext

Create a pager context that captures output and sends it to a pager.

Similar to Python Rich’s with console.pager(): context manager.

§Arguments
  • options - Optional pager options. Use PagerOptions::new().with_styles(true) to preserve ANSI escape sequences in the pager.
§Example
use rich_rs::{Console, PagerOptions};

let console = Console::new();
{
    let mut pager = console.pager(Some(PagerOptions::new().with_styles(true)));
    pager.print_text("Long content that should be paged...").unwrap();
    // Content is sent to pager when `pager` is dropped
}
Source

pub fn is_recording(&self) -> bool

Check if recording is enabled.

Source

pub fn set_record(&mut self, record: bool)

Enable or disable recording.

When recording is enabled, all segments written via print() are captured in an internal buffer that can be exported as SVG/HTML.

Source

pub fn clear_record_buffer(&mut self)

Clear the record buffer.

Source

pub fn get_record_buffer(&self) -> Vec<Segment>

Get the current record buffer contents.

Returns a clone of the recorded segments.

Source

pub fn export_svg( &mut self, title: &str, theme: Option<&TerminalTheme>, clear: bool, code_format: Option<&str>, font_aspect_ratio: f64, unique_id: Option<&str>, ) -> String

Export console contents as SVG.

Generates an SVG image from the recorded console output. Requires record=true to have been set (via new_with_record() or set_record(true)).

§Arguments
  • title - The title shown in the terminal window chrome.
  • theme - Optional terminal theme for colors. Defaults to SVG_EXPORT_THEME.
  • clear - Whether to clear the record buffer after exporting.
  • code_format - Optional custom SVG template. Defaults to CONSOLE_SVG_FORMAT.
  • font_aspect_ratio - Width/height ratio of the font. Defaults to 0.61 (Fira Code).
  • unique_id - Optional unique ID for CSS classes. Auto-generated if not provided.
§Example
use rich_rs::Console;

let mut console = Console::new_with_record();
console.print_text("Hello, World!").unwrap();
let svg = console.export_svg("Example", None, true, None, 0.61, None);
assert!(svg.contains("Hello"));
Source

pub fn export_html( &mut self, theme: Option<&TerminalTheme>, clear: bool, code_format: Option<&str>, ) -> String

Export console contents as HTML.

Generates an HTML document from the recorded console output. Requires record=true to have been set (via new_with_record() or set_record(true)).

This is modeled after Python Rich’s Console.export_html(). Hyperlinks are emitted as <a href="..."> when StyleMeta.link is present on segments.

§Arguments
  • theme - Optional terminal theme for colors. Defaults to DEFAULT_TERMINAL_THEME.
  • clear - Whether to clear the record buffer after exporting.
  • code_format - Optional custom HTML template. Defaults to CONSOLE_HTML_FORMAT.
§Example
use rich_rs::Console;

let mut console = Console::new_with_record();
console.print_text("Hello, World!").unwrap();
let html = console.export_html(None, true, None);
assert!(html.contains("<!DOCTYPE html>"));
assert!(html.contains("Hello, World!"));
Source

pub fn save_html( &mut self, path: &str, theme: Option<&TerminalTheme>, clear: bool, code_format: Option<&str>, ) -> Result<()>

Save console contents to an HTML file.

This is a convenience method that calls export_html() and writes the result to a file.

Source

pub fn save_svg( &mut self, path: &str, title: &str, theme: Option<&TerminalTheme>, clear: bool, font_aspect_ratio: f64, unique_id: Option<&str>, ) -> Result<()>

Save console contents to an SVG file.

This is a convenience method that calls export_svg() and writes the result to a file.

§Arguments
  • path - The file path to write to.
  • title - The title shown in the terminal window chrome.
  • theme - Optional terminal theme for colors.
  • clear - Whether to clear the record buffer after exporting.
  • font_aspect_ratio - Width/height ratio of the font. Defaults to 0.61.
  • unique_id - Optional unique ID for CSS classes.
§Example
use rich_rs::Console;

let mut console = Console::new_with_record();
console.print_text("Hello, World!").unwrap();
console.save_svg("output.svg", "Example", None, true, 0.61, None).unwrap();

Trait Implementations§

Source§

impl Default for Console<Stdout>

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl<W> Freeze for Console<W>
where W: Freeze,

§

impl<W = Stdout> !RefUnwindSafe for Console<W>

§

impl<W> Send for Console<W>
where W: Send,

§

impl<W> Sync for Console<W>
where W: Sync,

§

impl<W> Unpin for Console<W>
where W: Unpin,

§

impl<W = Stdout> !UnwindSafe for Console<W>

Blanket Implementations§

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> 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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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.