Fast, minimal, feature-rich, extended formatting syntax for Rust!

Related tags

Command-line fmtools
Overview

Formatting Tools

MIT License crates.io docs.rs Build status

Fast, minimal, feature-rich, extended formatting syntax for Rust!

Features include:

  • Arbitrary expressions inside the formatting braces
  • Generates optimized Rust code at compiletime
  • Supports rust-analyzer auto complete, refactoring and more!
  • Supports Rust's standard formatting specifiers
  • Single package, no proc-macro, no_std compatible, no extra dependencies
  • Control flow allows conditional and repeated formatting
  • Capture variables by value or by reference
  • Escape hatch to inject custom formatting code

In your Cargo.toml, add:

[dependencies]
fmtools = "0.1"

Examples

Basic usage

fn basic_usage() -> String {
	let name = "World";

	fmtools::format!("Hello "{name}"!")
}

assert_eq!(basic_usage(), "Hello World!");

The value arguments can be arbitrary expressions. They are inlined in the formatting braces and are outside the string literals.

Formatting specifiers

fn formatting_specifiers() -> String {
	let value = 42;

	fmtools::format!("hex("{value}") = "{value:#x})
}

assert_eq!(formatting_specifiers(), "hex(42) = 0x2a");

The rules for the specifiers are exactly the same as the standard library of Rust.

Let bindings

fn let_bindings() -> String {
	let base = 52;

	fmtools::format! {
		let value = base - 10;
		"value = "{value}
	}
}

assert_eq!(let_bindings(), "value = 42");

Introduce new variable bindings to hold onto temporary values used in the formatting.

Control flow

fn control_flow1() -> String {
	let power = 0.5;

	fmtools::format! {
		"At "
		if power >= 1.0 { "full" } else { {power * 100.0:.0}"%" }
		" power"
	}
}

assert_eq!(control_flow1(), "At 50% power");
fn control_flow2() -> String {
	let value = Some(42);

	fmtools::format! {
		"The answer is "
		match value {
			Some(answer) => "Some("{answer}")",
			None => "None",
		}
	}
}

assert_eq!(control_flow2(), "The answer is Some(42)");
fn control_flow3() -> String {
	let values = [1, 2, 3, 4, 5];

	fmtools::format! {
		for &val in &values {
			let result = val * 5;
			"* "{val}" x 5 = "{result}"\n"
		}
	}
}

assert_eq!(control_flow3(), "\
	* 1 x 5 = 5\n\
	* 2 x 5 = 10\n\
	* 3 x 5 = 15\n\
	* 4 x 5 = 20\n\
	* 5 x 5 = 25\n");

Control flow really shows the added value of the extended formatting syntax.

Capture by value

fn capture_by_value() -> String {
	fn inner() -> impl std::fmt::Display {
		let a = 42;
		fmtools::fmt!(move "a = "{a})
	}
	fmtools::format!("{"{inner()}"}")
}

assert_eq!(capture_by_value(), "{a = 42}");

The displayable object can own the captured variables with move and can be returned from functions.

Custom formatting

fn custom_formatting() -> String {
	fmtools::format! {
		"Now entering ["
		|f| f.write_str("custom formatting")?;
		"]"
	}
}

assert_eq!(custom_formatting(), "Now entering [custom formatting]");

Closure syntax provides an escape hatch to inject custom code if needed. The argument's type is &mut Formatter.

License

Licensed under MIT License, see license.txt.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, shall be licensed as above, without any additional terms or conditions.

You might also like...
⚡️Highly efficient data and string formatting library for Rust.

⚡️Highly efficient data and string formatting library for Rust. 🔎 Overview Pad and format string slices and generic vectors efficiently with minimal

Social media style compact number formatting for rust.

prettty-num Format integers into a compact social media style format, similar to using Intl.NumberFormat("en", { notation: "compact" }); as a number f

 create and test the style and formatting of text in your terminal applications
create and test the style and formatting of text in your terminal applications

description: create and test the style and formatting of text in your terminal applications docs: https://docs.rs/termstyle termstyle is a library tha

Monorepo for dprint—a pluggable and configurable code formatting platform

dprint Monorepo for dprint—a pluggable and configurable code formatting platform. This project is under active early development. I recommend you chec

🍅 A command-line tool to get and set values in toml files while preserving comments and formatting

tomato Get, set, and delete values in TOML files while preserving comments and formatting. That's it. That's the feature set. I wrote tomato to satisf

Sleek is a CLI tool for formatting SQL. It helps you maintain a consistent style across your SQL code, enhancing readability and productivity.

Sleek: SQL Formatter ✨ Sleek is a CLI tool for formatting SQL. It helps you maintain a consistent style across your SQL code, enhancing readability an

nvim-oxi provides safe and idiomatic Rust bindings to the rich API exposed by the Neovim text editor.

🔗 nvim-oxi nvim-oxi provides safe and idiomatic Rust bindings to the rich API exposed by the Neovim text editor. The project is mostly intended for p

Estratto is a powerful and user-friendly Rust library designed for extracting rich audio features from digital audio signals.
Estratto is a powerful and user-friendly Rust library designed for extracting rich audio features from digital audio signals.

estratto 〜 An Audio Feature Extraction Library estratto is a powerful and user-friendly Rust library designed for extracting rich audio features from

🚀 Discord Rich Presence plugin for Neovim written in Rust
🚀 Discord Rich Presence plugin for Neovim written in Rust

🧩 Cord 🚀 Cord is a Discord Rich Presence plugin designed for Neovim, written in Rust. 💎 Features Lightweight and dependency-free Cross-platform sup

Comments
  • variable width, precision, etc

    variable width, precision, etc

    I couldn't find an example, and I couldn't make it work: is there a way to have, say, a width be defined by a variable, as described at https://doc.rust-lang.org/nightly/alloc/fmt/index.html#width? The macros here don't really take any arguments (that I can tell?), and it seems that neither {variable:<width$} nor {variable:<w$,w=width} doesn't work, so I'm not sure if this can be done. But it sure would be nice. 😃

    opened by dhduvall 2
Owner
Casper
Casper
🖥 A feature rich terminal UI file transfer and explorer with support for SCP/SFTP/FTP/S3

?? A feature rich terminal UI file transfer and explorer with support for SCP/SFTP/FTP/S3

Christian Visintin 574 Jan 5, 2023
A lightweight but incredibly powerful and feature-rich BitTorrent tracker. Supports UDP + HTTP(S) and a private tracker mode.

Torrust Tracker Project Description Torrust Tracker is a lightweight but incredibly powerful and feature-rich BitTorrent tracker made using Rust. Feat

Torrust 162 Dec 31, 2022
Terminal based, feature rich, interactive SQL tool

datafusion-tui (dft) DataFusion-tui provides a feature rich terminal application, built with tui-rs, for using DataFusion (and eventually Ballista). I

null 49 Dec 24, 2022
A superset of PHP with extended syntax and runtime capabilities.

PXP PXP is a superset of the PHP programming language that provides an extended set of syntax rules and language features to improve developer experie

PXP 188 Jan 29, 2023
Count your code by tokens, types of syntax tree nodes, and patterns in the syntax tree. A tokei/scc/cloc alternative.

tcount (pronounced "tee-count") Count your code by tokens, types of syntax tree nodes, and patterns in the syntax tree. Quick Start Simply run tcount

Adam P. Regasz-Rethy 48 Dec 7, 2022
Compiler for an "extended" version of the Mindustry logic language

Minblur Compiler Minblur is a compiler for a superset of "logic" programming language in the game Mindustry. It helps reduce code-duplication, making

Binder News 15 May 2, 2022
rpsc is a *nix command line tool to quickly search for file systems items matching varied criterions like permissions, extended attributes and much more.

rpsc rpsc is a *nix command line tool to quickly search for file systems items matching varied criterions like permissions, extended attributes and mu

null 3 Dec 15, 2022
Cross-platform Rust library for coloring and formatting terminal output

Coloring terminal output Documentation term-painter is a cross-platform (i.e. also non-ANSI terminals) Rust library for coloring and formatting termin

Lukas Kalbertodt 75 Jul 28, 2022
Fmt-rfcs - RFCs for Rust formatting guidelines and changes to Rustfmt

Rust code formatting RFCs This repository exists to decide on a code style for Rust code, to be enforced by the Rustfmt tool. Accepted RFCs live in th

null 397 Jan 9, 2023
Vari (Väri) is a Rust library for formatting strings with colors and cosmetic stuff to the terminal.

Vari Vari (Väri) is a Rust library for formatting strings with colors and cosmetic stuff to the terminal. Like Rich library for Python. Väri means "co

azur 13 Nov 2, 2022