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>
impl Console<Stdout>
Sourcepub fn new_with_record() -> Self
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);Sourcepub fn with_theme(self, name: &str) -> Self
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");Sourcepub fn with_options(options: ConsoleOptions) -> Self
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>>
impl Console<Vec<u8>>
Sourcepub fn capture() -> Self
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"));Sourcepub fn capture_with_options(options: ConsoleOptions) -> Self
pub fn capture_with_options(options: ConsoleOptions) -> Self
Create a capture console with specific options.
Sourcepub fn get_captured(&self) -> String
pub fn get_captured(&self) -> String
Get captured output as a string.
Sourcepub fn get_captured_bytes(&self) -> &[u8] ⓘ
pub fn get_captured_bytes(&self) -> &[u8] ⓘ
Get captured output as bytes.
Sourcepub fn clear_captured(&mut self)
pub fn clear_captured(&mut self)
Clear the capture buffer.
Source§impl<W: Write> Console<W>
impl<W: Write> Console<W>
Sourcepub fn with_writer(writer: W, options: ConsoleOptions) -> Self
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.
Sourcepub fn options(&self) -> &ConsoleOptions
pub fn options(&self) -> &ConsoleOptions
Get the console options.
Sourcepub fn options_mut(&mut self) -> &mut ConsoleOptions
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.
Sourcepub fn sync_from_options(&mut self)
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.
Sourcepub fn options_with_state(&self) -> ConsoleOptions
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.
Sourcepub fn is_terminal(&self) -> bool
pub fn is_terminal(&self) -> bool
Check if the console is writing to a terminal.
Sourcepub fn is_dumb_terminal(&self) -> bool
pub fn is_dumb_terminal(&self) -> bool
Check if the terminal is considered “dumb” (no cursor control).
Sourcepub fn set_force_terminal(&mut self, force: Option<bool>)
pub fn set_force_terminal(&mut self, force: Option<bool>)
Force terminal mode on or off.
Sourcepub fn color_system(&self) -> Option<ColorSystem>
pub fn color_system(&self) -> Option<ColorSystem>
Get the color system.
Sourcepub fn set_color_system(&mut self, system: Option<ColorSystem>)
pub fn set_color_system(&mut self, system: Option<ColorSystem>)
Set the color system.
Sourcepub fn is_markup_enabled(&self) -> bool
pub fn is_markup_enabled(&self) -> bool
Check if markup is enabled by default.
Sourcepub fn set_markup_enabled(&mut self, enabled: bool)
pub fn set_markup_enabled(&mut self, enabled: bool)
Enable or disable markup parsing by default.
Sourcepub fn is_emoji_enabled(&self) -> bool
pub fn is_emoji_enabled(&self) -> bool
Check if emoji replacement is enabled by default.
Sourcepub fn set_emoji_enabled(&mut self, enabled: bool)
pub fn set_emoji_enabled(&mut self, enabled: bool)
Enable or disable emoji replacement by default.
Sourcepub fn is_highlight_enabled(&self) -> bool
pub fn is_highlight_enabled(&self) -> bool
Check if highlighting is enabled by default.
Sourcepub fn set_highlight_enabled(&mut self, enabled: bool)
pub fn set_highlight_enabled(&mut self, enabled: bool)
Enable or disable highlighting by default.
Sourcepub fn set_encoding(&mut self, encoding: impl Into<String>)
pub fn set_encoding(&mut self, encoding: impl Into<String>)
Set the output encoding.
Sourcepub fn set_tab_size(&mut self, size: usize)
pub fn set_tab_size(&mut self, size: usize)
Set the tab size.
Sourcepub fn theme_name(&self) -> &str
pub fn theme_name(&self) -> &str
Get the current theme name.
Returns the name of the base theme (e.g., “default”, “dracula”).
Sourcepub fn set_theme(&mut self, name: &str)
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");Sourcepub fn theme_stack(&self) -> &ThemeStack
pub fn theme_stack(&self) -> &ThemeStack
Get a reference to the theme stack.
Sourcepub fn theme_stack_mut(&mut self) -> &mut ThemeStack
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.
Sourcepub fn sync_theme_to_options(&mut self)
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.
Sourcepub fn push_theme(&mut self, theme: Theme)
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.
Sourcepub fn pop_theme(&mut self) -> Result<(), ThemeError>
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.
Sourcepub fn render_lines<R: Renderable + ?Sized>(
&self,
renderable: &R,
options: Option<&ConsoleOptions>,
style: Option<Style>,
pad: bool,
new_lines: bool,
) -> Vec<Vec<Segment>>
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 fromconsole.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.
Sourcepub fn render_str(
&self,
text: &str,
markup: Option<bool>,
emoji: Option<bool>,
highlight: Option<bool>,
highlighter: Option<&dyn Highlighter>,
) -> Text
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.
Sourcepub fn print_text(&mut self, text: &str) -> Result<()>
pub fn print_text(&mut self, text: &str) -> Result<()>
Print plain text with a newline.
Sourcepub fn print_styled(&mut self, text: &str, style: Style) -> Result<()>
pub fn print_styled(&mut self, text: &str, style: Style) -> Result<()>
Print styled text with a newline.
Sourcepub fn print_traceback(&mut self, traceback: &Traceback) -> Result<()>
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();Sourcepub fn print_segment(&mut self, segment: &Segment) -> Result<()>
pub fn print_segment(&mut self, segment: &Segment) -> Result<()>
Print a segment.
Sourcepub fn print_segments(&mut self, segments: &Segments) -> Result<()>
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.
Sourcepub fn print<R: Renderable + ?Sized>(
&mut self,
renderable: &R,
style: Option<Style>,
justify: Option<JustifyMethod>,
overflow: Option<OverflowMethod>,
no_wrap: bool,
end: &str,
) -> Result<()>
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”).
Sourcepub fn log<R: Renderable + ?Sized>(
&mut self,
renderable: &R,
file: Option<&str>,
line: Option<u32>,
) -> Result<()>
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 (usefile!()macro at call site).line- Optional line number (useline!()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();Sourcepub fn clear_line(&mut self) -> Result<()>
pub fn clear_line(&mut self) -> Result<()>
Clear the current line.
Sourcepub fn move_cursor(&mut self, x: u16, y: u16) -> Result<()>
pub fn move_cursor(&mut self, x: u16, y: u16) -> Result<()>
Move the cursor to a specific position.
Sourcepub fn show_cursor(&mut self, show: bool) -> Result<bool>
pub fn show_cursor(&mut self, show: bool) -> Result<bool>
Show or hide the cursor.
Sourcepub fn enter_alt_screen(&mut self) -> Result<bool>
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.
Sourcepub fn leave_alt_screen(&mut self) -> Result<bool>
pub fn leave_alt_screen(&mut self) -> Result<bool>
Leave alternate screen mode.
Sourcepub fn is_alt_screen(&self) -> bool
pub fn is_alt_screen(&self) -> bool
Check if alternate screen mode is active.
Sourcepub fn set_alt_screen(&mut self, enable: bool) -> Result<bool>
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.
Sourcepub fn screen(
&mut self,
hide_cursor: bool,
style: Option<Style>,
) -> Result<ScreenContext<'_, W>>
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 droppedSourcepub fn set_window_title(&mut self, title: &str) -> Result<bool>
pub fn set_window_title(&mut self, title: &str) -> Result<bool>
Set the window title.
pub fn live_start( &mut self, renderable: Box<dyn Renderable + Send + Sync>, vertical_overflow: VerticalOverflowMethod, ) -> (usize, bool)
pub fn live_update( &mut self, id: usize, renderable: Box<dyn Renderable + Send + Sync>, )
pub fn live_set_vertical_overflow( &mut self, id: usize, vertical_overflow: VerticalOverflowMethod, )
pub fn live_stop( &mut self, id: usize, ) -> Option<Box<dyn Renderable + Send + Sync>>
pub fn live_clear(&mut self)
Sourcepub fn input(&mut self, prompt: &Text, password: bool) -> Result<String>
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);Sourcepub fn measure<R: Renderable + ?Sized>(
&self,
renderable: &R,
options: Option<&ConsoleOptions>,
) -> Measurement
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 fromconsole.options().
Sourcepub fn out(
&mut self,
text: &str,
style: Option<Style>,
_highlight: Option<bool>,
) -> Result<()>
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.
Sourcepub fn export_text(&self, clear: bool, styles: bool) -> String
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).
Sourcepub fn save_text(&self, path: &str, clear: bool, styles: bool) -> Result<()>
pub fn save_text(&self, path: &str, clear: bool, styles: bool) -> Result<()>
Save export_text output to a file.
Sourcepub fn push_render_hook(
&mut self,
hook: Box<dyn Fn(&Segments) -> Segments + Send + Sync>,
)
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.
Sourcepub fn pop_render_hook(&mut self)
pub fn pop_render_hook(&mut self)
Remove the last render hook.
Source§impl Console<Stdout>
impl Console<Stdout>
Sourcepub fn render<R: Renderable + ?Sized>(&self, renderable: &R) -> Segments
pub fn render<R: Renderable + ?Sized>(&self, renderable: &R) -> Segments
Render a Renderable to Segments.
Sourcepub fn render_with_options<R: Renderable + ?Sized>(
&self,
renderable: &R,
options: &ConsoleOptions,
) -> Segments
pub fn render_with_options<R: Renderable + ?Sized>( &self, renderable: &R, options: &ConsoleOptions, ) -> Segments
Render a Renderable with custom options.
Source§impl Console<Stdout>
impl Console<Stdout>
Sourcepub fn pager(&self, options: Option<PagerOptions>) -> PagerContext
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. UsePagerOptions::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
}Sourcepub fn is_recording(&self) -> bool
pub fn is_recording(&self) -> bool
Check if recording is enabled.
Sourcepub fn set_record(&mut self, record: bool)
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.
Sourcepub fn clear_record_buffer(&mut self)
pub fn clear_record_buffer(&mut self)
Clear the record buffer.
Sourcepub fn get_record_buffer(&self) -> Vec<Segment>
pub fn get_record_buffer(&self) -> Vec<Segment>
Get the current record buffer contents.
Returns a clone of the recorded segments.
Sourcepub 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
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 toSVG_EXPORT_THEME.clear- Whether to clear the record buffer after exporting.code_format- Optional custom SVG template. Defaults toCONSOLE_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"));Sourcepub fn export_html(
&mut self,
theme: Option<&TerminalTheme>,
clear: bool,
code_format: Option<&str>,
) -> String
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 toDEFAULT_TERMINAL_THEME.clear- Whether to clear the record buffer after exporting.code_format- Optional custom HTML template. Defaults toCONSOLE_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!"));Sourcepub fn save_html(
&mut self,
path: &str,
theme: Option<&TerminalTheme>,
clear: bool,
code_format: Option<&str>,
) -> Result<()>
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.
Sourcepub fn save_svg(
&mut self,
path: &str,
title: &str,
theme: Option<&TerminalTheme>,
clear: bool,
font_aspect_ratio: f64,
unique_id: Option<&str>,
) -> Result<()>
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();