#user-interface #tui #syntax-highlighting #logging #productivity #helper


Helper crate for r3bl_tui and r3bl_tuify crates. Used by workspace in https://crates.io/crates/r3bl_rs_utils

34 releases

0.9.13 Apr 16, 2024
0.9.12 Jan 7, 2024
0.9.10 Dec 23, 2023
0.9.9 Oct 22, 2023
0.7.12 Jul 7, 2022

#610 in GUI

Download history 3670/week @ 2024-03-14 3098/week @ 2024-03-21 2895/week @ 2024-03-28 3261/week @ 2024-04-04 3396/week @ 2024-04-11 3725/week @ 2024-04-18 3800/week @ 2024-04-25 5100/week @ 2024-05-02 3067/week @ 2024-05-09 3084/week @ 2024-05-16 3137/week @ 2024-05-23 3277/week @ 2024-05-30 2803/week @ 2024-06-06 3166/week @ 2024-06-13 3686/week @ 2024-06-20 3466/week @ 2024-06-27

13,541 downloads per month
Used in 10 crates (9 directly)




R3BL TUI library & suite of apps focused on developer productivity

We are working on building command line apps in Rust which have rich text user interfaces (TUI). We want to lean into the terminal as a place of productivity, and build all kinds of awesome apps for it.

  1. 🔮 Instead of just building one app, we are building a library to enable any kind of rich TUI development w/ a twist: taking concepts that work really well for the frontend mobile and web development world and re-imagining them for TUI & Rust.

    • Taking things like React, JSX, CSS, and Redux, but making everything async (they can be run in parallel & concurrent via Tokio).
    • Even the thread running the main event loop doesn't block since it is async.
    • Using proc macros to create DSLs to implement CSS & JSX.
  2. 🌎 We are building apps to enhance developer productivity & workflows.

    • The idea here is not to rebuild tmux in Rust (separate processes mux'd onto a single terminal window). Rather it is to build a set of integrated "apps" (or "tasks") that run in the same process that renders to one terminal window.
    • Inside of this terminal window, we can implement things like "app" switching, routing, tiling layout, stacking layout, etc. so that we can manage a lot of TUI apps (which are tightly integrated) that are running in the same process, in the same window. So you can imagine that all these "app"s have shared application state (that is in a Redux store). Each "app" may also have its own Redux store.
    • Here are some examples of the types of "app"s we want to build:
      1. multi user text editors w/ syntax highlighting
      2. integrations w/ github issues
      3. integrations w/ calendar, email, contacts APIs


This crate is related to the first thing that's described above. It provides lots of useful functionality to help you build TUI (text user interface) apps, along w/ general niceties & ergonomics that all Rustaceans 🦀 can enjoy 🎉:


This crate contains the core functionality for building rich text user interfaces (TUI) in Rust. The r3bl_tui crate depends on it. Here are the main features:

  1. ANSI text support
  2. Core dimensions and units that are used for positioning and sizing
  3. Grapheme cluster segment and unicode support (emoji support)
  4. Lolcat support
  5. CSS like styling support



There are quite a few declarative macros that you will find in the library. They tend to be used internally in the implementation of the library itself. Here are some that are actually externally exposed via #[macro_export].


Similar to assert_eq! but automatically prints the left and right hand side variables if the assertion fails. Useful for debugging tests, since the cargo would just print out the left and right values w/out providing information on what variables were being compared.


Wrap the given block or stmt so that it returns a Result<()>. It is just syntactic sugar that helps having to write Ok(()) repeatedly at the end of each block. Here's an example.

fn test_simple_2_col_layout() -> CommonResult<()> {
  throws! {
    match input_event {
      InputEvent::DisplayableKeypress(character) => {
      _ => todo!()

Here's another example.

fn test_simple_2_col_layout() -> CommonResult<()> {
    let mut canvas = Canvas::default();
    canvas.stylesheet = create_stylesheet()?;
        .set_pos((0, 0).into())
        .set_size((500, 500).into())
    layout_container(&mut canvas)?;


This is very similar to throws! but it also returns the result of the block.

fn test_simple_2_col_layout() -> CommonResult<RenderPipeline> {
    println!("⛵ Draw -> draw: {}\r", state);


You can use this macro to dump log messages at 3 levels to a file. By default this file is named log.txt and is dumped in the current directory. Here's how you can use it.

Please note that the macro returns a Result. A type alias is provided to save some typing called CommonResult<T> which is just a short hand for std::result::Result<T, Box<dyn Error>>. The log file itself is overwritten for each "session" that you run your program.

use r3bl_rs_utils::{init_file_logger_once, log, CommonResult};

fn run() -> CommonResult<()> {
  let msg = "foo";
  let msg_2 = "bar";

  log!(INFO, "This is a info message");
  log!(INFO, target: "foo", "This is a info message");

  log!(WARN, "This is a warning message {}", msg);
  log!(WARN, target: "foo", "This is a warning message {}", msg);

  log!(ERROR, "This is a error message {} {}", msg, msg_2);
  log!(ERROR, target: "foo", "This is a error message {} {}", msg, msg_2);

  log!(DEBUG, "This is a debug message {} {}", msg, msg_2);
  log!(DEBUG, target: "foo", "This is a debug message {} {}", msg, msg_2);

  log!(TRACE, "This is a debug message {} {}", msg, msg_2);
  log!(TRACE, target: "foo", "This is a debug message {} {}", msg, msg_2);


To change the default log file to whatever you choose, you can use the try_to_set_log_file_path() function. If the logger hasn't yet been initialized, this function will set the log file path. Otherwise it will return an error.

use r3bl_rs_utils::{try_set_log_file_path, CommonResult, CommonError};
fn run() {
  match try_set_log_file_path("new_log.txt") {
      Ok(path_set) => debug!(path_set),
      Err(error) => debug!(error),

To change the default log level or to disable the log itself, you can use the try_to_set_log_level() function.

If you want to override the default log level LOG_LEVEL, you can use this function. If the logger has already been initialized, then it will return a an error.

use r3bl_rs_utils::{try_to_set_log_level, CommonResult, CommonError};
use log::LevelFilter;

fn run() {
  match try_to_set_log_level(LevelFilter::Debug) {
      Ok(level_set) => debug!(level_set),
      Err(error) => debug!(error),

To disable logging simply set the log level to LevelFilter::Off.

use r3bl_rs_utils::{try_to_set_log_level, CommonResult, CommonError};
use log::LevelFilter;

fn run() {
  match try_to_set_log_level(LevelFilter::Off) {
      Ok(level_set) => debug!(level_set),
      Err(error) => debug!(error),

Please check out the source here.


This macro is very similar to the log! macro, except that it won't return any error if the underlying logging system fails. It will simply print a message to stderr. Here's an example.

pub fn log_state(&self, msg: &str) {
  log_no_err!(INFO, "{:?} -> {}", msg, self.to_string());
  log_no_err!(INFO, target: "foo", "{:?} -> {}", msg, self.to_string());


This is a really simple macro to make it effortless to debug into a log file. It outputs DEBUG level logs. It takes a single identifier as an argument, or any number of them. It simply dumps an arrow symbol, followed by the identifier stringify'd along with the value that it contains (using the Debug formatter). All of the output is colorized for easy readability. You can use it like this.

let my_string = "Hello World!";


This is very similar to debug_log_no_err! except that it outputs TRACE level logs.

let my_string = "Hello World!";


This is a really simple wrapper around tokio::spawn() for the given block. Its just syntactic sugar. Here's an example of using it for a non-async block.

pub fn foo() {
    { println!("Hello"); }

And, here's an example of using it for an async block.

pub fn foo() {
     let fake_data = fake_contact_data_api()
     .unwrap_or_else(|_| FakeContactData {
       name: "Foo Bar".to_string(),
       phone_h: "123-456-7890".to_string(),
       email_u: "foo".to_string(),
       email_d: "bar.com".to_string(),


Syntactic sugar to run a conditional statement. Here's an example.

const DEBUG: bool = true;
    "{} {} {}\r",
    r3bl_rs_utils::style_dimmed(&format!("{:#?}", $err))


This is a really simple macro to make it effortless to use the color console logger. It takes a single identifier as an argument, or any number of them. It simply dumps an arrow symbol, followed by the identifier (stringified) along with the value that it contains (using the Debug formatter). All of the output is colorized for easy readability. You can use it like this.

let my_string = "Hello World!";
let my_number = 42;
debug!(my_string, my_number);

You can also use it in these other forms for terminal raw mode output. This will dump the output to stderr.

if let Err(err) = $cmd {
  let msg = format!("❌ Failed to {}", stringify!($cmd));
  debug!(ERROR_RAW &msg, err);

This will dump the output to stdout.

let msg = format!("✅ Did the thing to {}", stringify!($name));
debug!(OK_RAW &msg);


This is a macro that takes inspiration from the with scoping function in Kotlin. It just makes it easier to express a block of code that needs to run after an expression is evaluated and saved to a given variable. Here's an example.

with! {
  /* $eval */ LayoutProps {
    id: id.to_string(),
    req_size: RequestedSize::new(width_pc, height_pc),
  as /* $id */ it,
  run /* $code */ {
    match self.is_layout_stack_empty() {
      true => self.add_root_layout(it),
      false => self.add_normal_layout(it),

It does the following:

  1. Evaluates the $eval expression and assigns it to $id.
  2. Runs the $code block.


This macro is just like with! but it takes a mutable reference to the $id variable. Here's a code example.

with_mut! {
  StyleFlag::BOLD_SET | StyleFlag::DIM_SET,
  as mask2,
  run {


This macro is just like with_mut! except that it returns the value of the $code block. Here's a code example.

let queue = with_mut_returns! {
    ColumnRenderComponent { lolcat },
    as it,
    return {
      it.render_component(surface.current_box()?, state, shared_store).await?


This macro can be useful when you are working w/ an expression that returns an Option and if that Option is None then you want to abort and return an error immediately. The idea is that you are using this macro in a function that returns a Result<T> basically.

Here's an example to illustrate.

pub fn from(
  width_percent: u8,
  height_percent: u8,
) -> CommonResult<RequestedSize> {
  let size_tuple = (width_percent, height_percent);
  let (width_pc, height_pc) = unwrap_option_or_run_fn_returning_err!(
    || LayoutError::new_err(LayoutErrorType::InvalidLayoutSizePercentage)
  Ok(Self::new(width_pc, height_pc))


This macro is basically a way to compute something lazily when it (the Option) is set to None. Unwrap the $option, and if None then run the $next closure which must return a value that is set to $option. Here's an example.

use r3bl_rs_utils::unwrap_option_or_compute_if_none;

fn test_unwrap_option_or_compute_if_none() {
  struct MyStruct {
    field: Option<i32>,
  let mut my_struct = MyStruct { field: None };
  assert_eq!(my_struct.field, None);
  unwrap_option_or_compute_if_none!(my_struct.field, { || 1 });
  assert_eq!(my_struct.field, Some(1));


CommonResult and CommonError

These two structs make it easier to work w/ Results. They are just syntactic sugar and helper structs. You will find them used everywhere in the r3bl_rs_utils crate.

Here's an example of using them both.

use r3bl_rs_utils::{CommonError, CommonResult};

#[derive(Default, Debug, Clone)]
pub struct Stylesheet {
  pub styles: Vec<Style>,

impl Stylesheet {
  pub fn add_style(
    &mut self,
    style: Style,
  ) -> CommonResult<()> {
    if style.id.is_empty() {
      return CommonError::new_err_with_only_msg("Style id cannot be empty");

Other crates that depend on this

This crate is a dependency of the following crates:

  1. r3bl_rs_utils_macro (procedural macros)
  2. r3bl_rs_utils crates (the "main" library)

Issues, comments, feedback, and PRs

Please report any issues to the issue tracker. And if you have any feature requests, feel free to add them there too 👍.


~149K SLoC