easy-sgr
An easy-to-use library for adding graphical ANSI codes or SGR escape sequences to your project.
Its main strengths are the multitude of methods that are provided,
and the lack of dependencies; compile times should be pretty good.
This library does not support the usage of non-SGR ANSI escape sequences
Installation
Add this to your Cargo.toml:
[]
="0.0.1"
Usage
Color and Style enums
The simplest way to color text, using these two enums allows you to
work inline of a string literal when using a macro such as
println!, writeln! or format!:
use ;
println!;
Color and Style are both enums that implement Display: when they
are printed a matching SGR code is written.
This method is the best when it comes to simplicity, but has drawbacks;
using it rewrites the Escape sequence \x1b[ and the End sequence m repeatedly.
In this example this is what would be written:
\x1b[3m\x1b[31mThis should be italic & red!\x1b[0m
This would not be much of an issue for the vast majority of use cases.
EasySGR trait
This is similar to the method above but uses the EasySGR trait.
This trait is implemented by anything that implements Into<AnsiString> including Style and Color.
Its main purpose is to provide functions for chaining SGR codes.
The example above can be achieved using it as such:
use ;
let sgr = Italic.color;
println!;
Now the output would look something like this:
\x1b[31;3mThis should be italic & red!\x1b[0m
Instead of a rewriting the entire sequence, the separator character ; is used instead.
Doing this avoids the issue of rewriting the Escape and End sequences,
though is more expensive to use as it allocates a SGRString.
SGRString struct
SGRString is the type returned by all EasySGR functions, it encapsulates all
possible SGR sequences. You can use it to reproduce the previous examples as such:
use ;
let text = "This should be italic & red!"
.to_sgr
.style
.color;
println!;
You can forgo .to_sgr() as .style(..), .color(..) and all other EasySGR functions
can be directly called on the string literal and other types that implement it.
The method above still uses the EasySGR trait, you can go without it like here:
use ;
let mut text = from;
text.italic = Place;
text.foreground = Red;
println!
SGRWriter trait
The writer can also be used directly, instead of using the above methods:
use ;
use ;
let mut writer = io;
writer.sgr.unwrap;
writer.write_inner.unwrap;
writer.sgr.unwrap;
or, when writing to a String
use ;
let stylized_string = ;
Structure
easy-sgr is split into three modules:
- discrete
- graphics
- writing
Though no modules really will be seen in usage, as all the types they contain are reexported.
TODO
- Add inline that doesn't write escape itself
- Add
get_writermethod towritingmodule - Create
writingtests - Add examples to docs
- Implement
FromStrforSGRtypes - Parser (
deSGR) - Macros (
SGRise) -
EasySGRimplementation that doesn't allocate aSGRString - (maybe) create smart clean system