Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support ANSI-escaped color codes and hyperlinks. #171

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,4 @@ lazy_static = "1.4"
is-terminal = "0.4"
encode_unicode = "1.0"
csv = { version = "1.1", optional = true }
regex = "1"
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,14 @@ Uppercase letters stand for **bright** counterparts of the above colors:
* **B** : Bright Blue
* ... and so on ...

## ANSI hyperlinks

In most modern terminal emulators, it is possible to embed hyperlinks using ANSI escape codes. The following string field would display as a clickable link:

```rust
"\u{1b}]8;;http://example.com\u{1b}\\example.com\u{1b}]8;;\u{1b}\\"
```

## Slicing

Tables can be sliced into immutable borrowed subtables.
Expand Down
57 changes: 22 additions & 35 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::fmt;
use std::io::{Error, ErrorKind, Write};
use std::str;

use regex::Regex;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use super::format::Alignment;
Expand Down Expand Up @@ -82,45 +83,20 @@ pub fn print_align<T: Write + ?Sized>(
}

/// Return the display width of a unicode string.
/// This functions takes ANSI-escaped color codes into account.
/// This functions takes ANSI-escaped color codes and hyperlinks into account.
pub fn display_width(text: &str) -> usize {
#[derive(PartialEq, Eq, Clone, Copy)]
enum State {
/// We are not inside any terminal escape.
Normal,
/// We have just seen a \u{1b}
EscapeChar,
/// We have just seen a [
OpenBracket,
/// We just ended the escape by seeing an m
AfterEscape,
}

let width = UnicodeWidthStr::width(text);
let mut state = State::Normal;
let mut hidden = 0;

for c in text.chars() {
state = match (state, c) {
(State::Normal, '\u{1b}') => State::EscapeChar,
(State::EscapeChar, '[') => State::OpenBracket,
(State::EscapeChar, _) => State::Normal,
(State::OpenBracket, 'm') => State::AfterEscape,
_ => state,
};

// We don't count escape characters as hidden as
// UnicodeWidthStr::width already considers them.
if matches!(state, State::OpenBracket | State::AfterEscape) {
// but if we see an escape char *inside* the ANSI escape, we should ignore it.
if UnicodeWidthChar::width(c).unwrap_or(0) > 0 {
hidden += 1;
}
}

if state == State::AfterEscape {
state = State::Normal;
}
lazy_static! {
static ref COLOR_RE: Regex = Regex::new(r"\u{1b}(?P<colors>\[[^m]+?)m").unwrap();
static ref HYPERLINK_RE: Regex = Regex::new(r"\u{1b}]8;;(?P<url>[^\u{1b}]+?)\u{1b}\\(?P<text>[^\u{1b}]+?)\u{1b}]8;;\u{1b}\\").unwrap();
}
for caps in COLOR_RE.captures_iter(text) {
hidden += UnicodeWidthStr::width(&caps["colors"])
}
for caps in HYPERLINK_RE.captures_iter(text) {
hidden += 10 + UnicodeWidthStr::width(&caps["url"])
}

assert!(
Expand Down Expand Up @@ -225,6 +201,17 @@ mod tests {
assert_eq!(out.as_string(), "foo");
}

#[test]
fn ansi_escapes() {
let mut out = StringWriter::new();
print_align(&mut out, Alignment::LEFT, "\u{1b}[31;40mred\u{1b}[0m", ' ', 10, false).unwrap();
assert_eq!(display_width(out.as_string()), 10);

let mut out = StringWriter::new();
print_align(&mut out, Alignment::LEFT, "\u{1b}]8;;http://example.com\u{1b}\\example\u{1b}]8;;\u{1b}\\", ' ', 10, false).unwrap();
assert_eq!(display_width(out.as_string()), 10);
}

#[test]
fn utf8_error() {
let mut out = StringWriter::new();
Expand Down