Code Monkey home page Code Monkey logo

rust-ansi-term's Introduction

rust-ansi-term ansi-term on crates.io Build status Build status Coverage status

This is a library for controlling colours and formatting, such as red bold text or blue underlined text, on ANSI terminals.

Installation

This crate works with Cargo. Add the following to your Cargo.toml dependencies section:

[dependencies]
ansi_term = "0.12"

Basic usage

There are three main types in this crate that you need to be concerned with: ANSIString, Style, and Colour.

A Style holds stylistic information: foreground and background colours, whether the text should be bold, or blinking, or other properties. The Colour enum represents the available colours. And an ANSIString is a string paired with a Style.

Color is also available as an alias to Colour.

To format a string, call the paint method on a Style or a Colour, passing in the string you want to format as the argument. For example, here’s how to get some red text:

use ansi_term::Colour::Red;

println!("This is in red: {}", Red.paint("a red string"));

It’s important to note that the paint method does not actually return a string with the ANSI control characters surrounding it. Instead, it returns an ANSIString value that has a Display implementation that, when formatted, returns the characters. This allows strings to be printed with a minimum of String allocations being performed behind the scenes.

If you do want to get at the escape codes, then you can convert the ANSIString to a string as you would any other Display value:

use ansi_term::Colour::Red;

let red_string = Red.paint("a red string").to_string();

Note for Windows 10 users: On Windows 10, the application must enable ANSI support first:

let enabled = ansi_term::enable_ansi_support();

Bold, underline, background, and other styles

For anything more complex than plain foreground colour changes, you need to construct Style values themselves, rather than beginning with a Colour. You can do this by chaining methods based on a new Style, created with Style::new(). Each method creates a new style that has that specific property set. For example:

use ansi_term::Style;

println!("How about some {} and {}?",
         Style::new().bold().paint("bold"),
         Style::new().underline().paint("underline"));

For brevity, these methods have also been implemented for Colour values, so you can give your styles a foreground colour without having to begin with an empty Style value:

use ansi_term::Colour::{Blue, Yellow};

println!("Demonstrating {} and {}!",
         Blue.bold().paint("blue bold"),
         Yellow.underline().paint("yellow underline"));

println!("Yellow on blue: {}", Yellow.on(Blue).paint("wow!"));

The complete list of styles you can use are: bold, dimmed, italic, underline, blink, reverse, hidden, and on for background colours.

In some cases, you may find it easier to change the foreground on an existing Style rather than starting from the appropriate Colour. You can do this using the fg method:

use ansi_term::Style;
use ansi_term::Colour::{Blue, Cyan, Yellow};

println!("Yellow on blue: {}", Style::new().on(Blue).fg(Yellow).paint("yow!"));
println!("Also yellow on blue: {}", Cyan.on(Blue).fg(Yellow).paint("zow!"));

You can turn a Colour into a Style with the normal method. This will produce the exact same ANSIString as if you just used the paint method on the Colour directly, but it’s useful in certain cases: for example, you may have a method that returns Styles, and need to represent both the “red bold” and “red, but not bold” styles with values of the same type. The Style struct also has a Default implementation if you want to have a style with nothing set.

use ansi_term::Style;
use ansi_term::Colour::Red;

Red.normal().paint("yet another red string");
Style::default().paint("a completely regular string");

Extended colours

You can access the extended range of 256 colours by using the Colour::Fixed variant, which takes an argument of the colour number to use. This can be included wherever you would use a Colour:

use ansi_term::Colour::Fixed;

Fixed(134).paint("A sort of light purple");
Fixed(221).on(Fixed(124)).paint("Mustard in the ketchup");

The first sixteen of these values are the same as the normal and bold standard colour variants. There’s nothing stopping you from using these as Fixed colours instead, but there’s nothing to be gained by doing so either.

You can also access full 24-bit colour by using the Colour::RGB variant, which takes separate u8 arguments for red, green, and blue:

use ansi_term::Colour::RGB;

RGB(70, 130, 180).paint("Steel blue");

Combining successive coloured strings

The benefit of writing ANSI escape codes to the terminal is that they stack: you do not need to end every coloured string with a reset code if the text that follows it is of a similar style. For example, if you want to have some blue text followed by some blue bold text, it’s possible to send the ANSI code for blue, followed by the ANSI code for bold, and finishing with a reset code without having to have an extra one between the two strings.

This crate can optimise the ANSI codes that get printed in situations like this, making life easier for your terminal renderer. The ANSIStrings struct takes a slice of several ANSIString values, and will iterate over each of them, printing only the codes for the styles that need to be updated as part of its formatting routine.

The following code snippet uses this to enclose a binary number displayed in red bold text inside some red, but not bold, brackets:

use ansi_term::Colour::Red;
use ansi_term::{ANSIString, ANSIStrings};

let some_value = format!("{:b}", 42);
let strings: &[ANSIString<'static>] = &[
    Red.paint("["),
    Red.bold().paint(some_value),
    Red.paint("]"),
];

println!("Value: {}", ANSIStrings(strings));

There are several things to note here. Firstly, the paint method can take either an owned String or a borrowed &str. Internally, an ANSIString holds a copy-on-write (Cow) string value to deal with both owned and borrowed strings at the same time. This is used here to display a String, the result of the format! call, using the same mechanism as some statically-available &str slices. Secondly, that the ANSIStrings value works in the same way as its singular counterpart, with a Display implementation that only performs the formatting when required.

Byte strings

This library also supports formatting [u8] byte strings; this supports applications working with text in an unknown encoding. Style and Colour support painting [u8] values, resulting in an ANSIByteString. This type does not implement Display, as it may not contain UTF-8, but it does provide a method write_to to write the result to any value that implements Write:

use ansi_term::Colour::Green;

Green.paint("user data".as_bytes()).write_to(&mut std::io::stdout()).unwrap();

Similarly, the type ANSIByteStrings supports writing a list of ANSIByteString values with minimal escape sequences:

use ansi_term::Colour::Green;
use ansi_term::ANSIByteStrings;

ANSIByteStrings(&[
    Green.paint("user data 1\n".as_bytes()),
    Green.bold().paint("user data 2\n".as_bytes()),
]).write_to(&mut std::io::stdout()).unwrap();

rust-ansi-term's People

Contributors

crumblingstatue avatar cyndis avatar da-x avatar davidjfelix avatar deadalusai avatar dflemstr avatar dzejkop avatar emlun avatar galich avatar gtabaresworkshare avatar guillaumegomez avatar havvy avatar joshtriplett avatar manuthambi avatar ogham avatar rivy avatar severen avatar visic avatar waywardmonkeys avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rust-ansi-term's Issues

Complex formatting settings are ignored

I'm trying to migrate my project from using colored to ansi_term, as one of my dependencies already uses the latter. I was expecting this to be a straightforward replacement, but faced an issue: the Display implementation in ansi_term seems to ignore the formatting settings, e.g. with the following code

const DIGITS: &'static str = "1234567890";

fn main() { 
    let s = Color::Red.paint(DIGITS);
    println!("{:.5}", s);
}

the expected behavior is: the provided format string is used; red string 12345 is printed;
the actual behavior is: the formatting settings are ignored; red string 1234567890 is printed.

Is this intentional, or a bug?

rustc: 1.38.0
ansi_term: 0.12.1

Consider 1.0 versioning

I think ansi_term seems ready to use 1.0 versioning, and that would also help people consolidate on the same version. Currently, I see multiple versions in the same dependency trees, because semver doesn't consider 0.x.0 and 0.y.0 compatible. Moving to 1.0 versioning would allow semver-compatible upgrades from 1.x.0 to 1.y.0.

ANSIStrings could handle spaces specially

I see a potential improvement to ANSIStrings, where you can drop foreground colour changes for strings that are only whitespace.

I.E.

use ansi_term::Colour::Red;
use ansi_term::{ANSIString, ANSIStrings};
let some_value = format!("{:b}", 42);
let strings: &[ANSIString<'static>] = &[
    Red.paint("["),
    Blue.paint("   "),
    Red.paint("]"),
];
println!("Value: {}", ANSIStrings(strings));

could not bother switching to blue in the middle.

TrueColor support

True color specify the color in RGB format like this:

printf "\x1b[${bg};2;${red};${green};${blue}m\n"

The 256 colour palete is configured at start, and it's a 666 cube of
colours, each of them defined as a 24bit (888 rgb) colour.

This means that current support can only display 256 different colours
in the terminal, while truecolour means that you can display 16 milion
different colours at the same time.

Truecolour escape codes doesnt uses a colour palete. It just specifies the
colour itself.

Here's a test case:

printf "\x1b[38;2;255;100;0mTRUECOLOR\x1b[0m\n"
awk 'BEGIN{
    s="/\\/\\/\\/\\/\\"; s=s s s s s s s s;
    for (colnum = 0; colnum<77; colnum++) {
        r = 255-(colnum*255/76);
        g = (colnum*510/76);
        b = (colnum*255/76);
        if (g>255) g = 510-g;
        printf "\033[48;2;%d;%d;%dm", r,g,b;
        printf "\033[38;2;%d;%d;%dm", 255-r,255-g,255-b;
        printf "%s\033[0m", substr(s,colnum+1,1);
    }
    printf "\n";
}'

Keep in mind that it is possible to use both ';' and ':' as parameters delimiter.

According to Wikipedia[1], this is only supported by xterm and konsole.

[1] https://en.wikipedia.org/wiki/ANSI_color

Currently, there is no support for the 24-bit colour descriptions in the terminfo/termcap database and utilites.
See the discussion thread here: https://lists.gnu.org/archive/html/bug-ncurses/2013-10/msg00007.html

At this point a lot of terminals have good support for 24-bit color (except rxvt-unicode and Terminology).
See more information here: https://gist.github.com/XVilka/8346728

Support global toggle via env variable

Hi @ogham !
I am the author of colored, a library highly influenced by yours, ansi_term. So, thanks for that. :)

One of the biggest feedback I got when publishing the release notes, was about an option for the user to turn on or off globally the coloring, so I think I should report to you too.

I was planning to use the RUST_NOCOLOR and RUST_FORCECOLOR env variable for that, I think it would be great if both our lib used the same variable names. What do you think ? I have no strong feeling on anything, I just want the user experience to be superb, so don't hesitate

linking to Colored tracking issue: colored-rs/colored#2

Build failure on OpenBSD with Rust nightly.

During cargo install mdbook:

   Compiling ansi_term v0.9.0
error[E0425]: cannot find value `EV_RECEIPT` in module `libc`
  --> .cargo/registry/src/github.com-1ecc6299db9ec823/mio-0.6.5/src/sys/unix/kqueue.rs:84:27
   |
84 |                     libc::EV_RECEIPT;
   |                           ^^^^^^^^^^ not found in `libc`

error[E0425]: cannot find value `EV_RECEIPT` in module `libc`
   --> .cargo/registry/src/github.com-1ecc6299db9ec823/mio-0.6.5/src/sys/unix/kqueue.rs:120:50
    |
120 |             let filter = libc::EV_DELETE | libc::EV_RECEIPT;
    |                                                  ^^^^^^^^^^ not found in `libc`

Nightly from yesterday on amd64/openbsd.

Thanks

Fails to compile on rustc 1.8.0 (db2939409 2016-04-11)

ansi-term fails to build on Debian Stretch testing with above said rustc version.

The error output is:

.cargo/registry/src/github.com-88ac128001ac3a9a/ansi_term-0.9.0/src/lib.rs:189:5: 189:23 error: user-defined types or type parameters cannot shadow the primitive types [E0317]
.cargo/registry/src/github.com-88ac128001ac3a9a/ansi_term-0.9.0/src/lib.rs:189     type str : ?Sized;
                                                                                          ^~~~~~~~~~~~~~~~~~
.cargo/registry/src/github.com-88ac128001ac3a9a/ansi_term-0.9.0/src/lib.rs:189:5: 189:23 help: run `rustc --explain E0317` to see a detailed explanation

No-op non-windows enable_ansi_support function

Hi!

This looks like an awesome crate to use for colours. One question though: could a non-windows version of enable_ansi_support be added to the crate?

Ideally I'd rather not have my CLI applications having any OS-specific code - it would be nice if I could just stick ansi_term::enable_ansi_support() at the top of my main() function, and know that it'll do whatever's needed for the current OS.

It could just be literally #[cfg(not(windows))] fn enable_ansi_support() -> Result<(), u64> { Ok(()) }. If you'd be willing to add this, I can also submit a PR.

support no_std ?

Hi can ansi-term support no_std ?
if not, can you support no_std?

Text wrap broken when using ansi_term in shell prompts

Background

I made a crate called glit, or Glitter which is a domain specific language for pretty printing git repository stats. The primary use-case is to embed information about git repository stats in a user's shell prompt; for example:

glit-demo

ansi_term has been super helpful in supporting ansi terminal formatting as part of the Glitter DSL, but I've unfortunately come across a strange issue:

When I have formatted text in the shell prompt, the text wrapping is broken. More specifically:

  • The terminal emulator wraps before the end of the line
  • The terminal emulator wraps onto the same line, overwriting the shell prompt

This issue is related to the way that BASH prompts expect all non-printing characters to be properly escaped so that it can properly count the length of a line.

Examples

Gnome shell
in gnome shell terminal emulator

hyper
demonstration in hyper.is terminal emulator

Expected Behaviour

The terminal again behaves as expected when I don't use any formatted text on the last line of the prompt; notice how below there is no formatting on the line which just contains $ ; that line was created by the interpreter by rendering the text \$ with Style::new(), or no formatting set.

  • The line wraps at the end of the line
  • The text does not wrap onto the same line as the shell prompt

demonstration of expected ansi_term behaviour

This has to do with lack of escapes for non-printing characters in bash prompts; from the documentation, control sequences must be escaped with:

\[

    Begin a sequence of non-printing characters. This could be used to embed a terminal control sequence into the prompt. 
\]

    End a sequence of non-printing characters. 

Replication

  • OS: Ubuntu 17.10 amd-64bit
  • uname -r: 4.13.0-32-generic
  • cargo -V: cargo 0.24.0 (45043115c 2017-12-05)
  • rustup -V: rustup 1.7.0 (813f7b7a8 2017-10-30)
  • rustc -V: rustc 1.23.0 (766bd11c8 2018-01-01)
  • ansi_term: 0.9^
  • bash --version: 4.4.12(1)-release

Accept any T: Display instead of just &str

It would be really nice to be able to paint anything I want. Being restricted to &str's often isn't too useful...

EDIT: I figured that this crate does not use the rust-lang/term crate... Maybe I'll write my own :P

don't rely on GetLastError() to detect errors in enable_ansi_support

let std_out_handle = GetStdHandle(STD_OUT_HANDLE);
let error_code = GetLastError();
if error_code != 0 { return Err(error_code); }
// https://docs.microsoft.com/en-us/windows/console/getconsolemode
let mut console_mode: u32 = 0;
GetConsoleMode(std_out_handle, &mut console_mode);
let error_code = GetLastError();
if error_code != 0 { return Err(error_code); }
// VT processing not already enabled?
if console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0 {
// https://docs.microsoft.com/en-us/windows/console/setconsolemode
SetConsoleMode(std_out_handle, console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
let error_code = GetLastError();
if error_code != 0 { return Err(error_code); }
}

GetStdHandle() can return valid handle and GetLastError() will return ERROR_NOT_SUPPORTED (50). Error must be checked only when GetStdHandle() returns INVALID_HANDLE_VALUE (-1). It happens when GUI app creates console via AllocConsole() and tries to call enable_ansi_support().

GetConsoleMode() and SetConsoleMode() return 0 (FALSE) when they fail, GetLastError() should be called after that.

A method to strip ANSI codes

It'd be nice if there were a way to strip the color code after the fact (basically to uncover the plain text from an ANSIString or ANSIStrings). That way, you can construct colored text, but throw the colors away at the last minute if you find the renderer doesn't support them or what have you.

fix some ESC codes

Hi,

According to various docs on the web, and to some tests I did on GNOME-terminal and XTerm, some of the codes you use are wrong. Could you fix them ?

  • 6 is another blink (useless)
  • 7 is reverse
  • 8 is hidden

I can do a PR if you prefer.

recommendation for printing single chars

Thanks for putting together such a nice crate. I wanted to ask for suggestion path for an usage issue I ran into. I ran into an issue where I wanted to paint a single char but was forced to allocate a new string to machine requirements with the Color#paint method. I was wondering if you had suggestions for an alternate approach.

allow arbitrary `Display`/`Debug` types in `paint`

Right now the paint function on Style and Color only accepts

I where
    I: Into<Cow<'a, S>>,
    <S as ToOwned>::Owned: Debug,

But in the documents it notes that the paint function doesn't do allocations and return the string with the color applied, instead it returns a Display type which wraps the original string. It seems like this restriction could be relaxed without making a breaking change.

Ideally I'd like it to return a type that impls Display if the inner type impls display, and impls Debug if the inner type impls Debug, which would let me write code like this:

                write!(
                    f,
                    "\n{}",
                    Style::new().bold().paint(format_args!(
                        "{:>8} > {}",
                        cur_line_no,
                        line.unwrap()
                    ))
                )?;

instead of what I have to write right now

                write!(
                    f,
                    "\n{:>8}{}{}",
                    bold.paint(cur_line_no.to_string()),
                    bold.paint(" > "),
                    bold.paint(line.unwrap())
                )?;

It would also make it easier to work with error reporting:

        for (n, error) in errors {
            writeln!(f)?;
            write!(Indented::numbered(f, n), "{}", Red.paint(error))?;
        }

instead of:

        let mut buf = String::new();
        for (n, error) in errors {
            writeln!(f)?;
            buf.clear();
            write!(&mut buf, "{}", error).unwrap();
            write!(Indented::numbered(f, n), "{}", Red.paint(&buf))?;
        }

NO_COLOR support

I see many projects using this library, and I don't see simple way to disable colored output for those apps (without code modification). In production environments I like to grep easily logs and colors are making it super difficult.

More info about NO_COLOR environment variable at https://no-color.org/

Maintenance status

Hi, I've found that this is the most popular crate for ANSI terminal in Rust, however the last release was two years ago...
There are also outstanding PRs, like one to update it to rust2018 edition (#63), when edition 2021 is already upcoming and other issues that don't get attention.
I see that @ogham and @joshtriplett have the ownership permissions on crates.io here. Could you please clarify the status of maintenance of this crate? Should we pass the maintainership to other members of the community or deprecate and archive this crate?

long_and_detailed test fails with latest Rust

failures:
---- debug::test::long_and_detailed stdout ----
thread 'debug::test::long_and_detailed' panicked at 'assertion failed: `(left == right)`
  left: `"Style {\n    foreground: Some(\n        Blue\n    ),\n    background: None,\n    blink: false,\n    bold: true,\n    dimmed: false,\n    hidden: false,\n    italic: false,\n    reverse: false,\n    strikethrough: false,\n    underline: false\n}"`,
 right: `"Style {\n    foreground: Some(\n        Blue,\n    ),\n    background: None,\n    blink: false,\n    bold: true,\n    dimmed: false,\n    hidden: false,\n    italic: false,\n    reverse: false,\n    strikethrough: false,\n    underline: false,\n}"`', src/debug.rs:120:9
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
failures:
    debug::test::long_and_detailed
test result: FAILED. 55 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

add strikethrough

Hi,

Could you add the strikethrough mode, which is \e[9m ?

Thanks

Add a helper to switch colors to their `intense` variant

related to this issue in color-eyre where it was reported that colors are particularly dark on Windows eyre-rs/color-eyre#12

The color-backtrace crate which color-eyre depends on fixes this issue by using intense variants of colors, according to termcolor, which are the 8-15 colors instead of the standard 0-7 colors. I think it makes sense to add a helper function on Color that will change a Color to its intense version if applicable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.