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

Capturing escape sequence sizing with categorized slices #9

Open
ncatelli opened this issue Jun 21, 2023 · 3 comments
Open

Capturing escape sequence sizing with categorized slices #9

ncatelli opened this issue Jun 21, 2023 · 3 comments

Comments

@ncatelli
Copy link

What would be the best way to derive the escape code by size of a give CategorizedSlice? Having this information would be extremely useful for tasks like text wrapping.

@kurtlawrence
Copy link
Collaborator

Hi @ncatelli.

CategorisedSlice has a .text field which is a reference to the underlying string (without the escape codes). You could call .chars() on it to get a character 'width'.

Is that sufficient for your use case?

@ncatelli
Copy link
Author

Hi Kurt,

Unfortunately no, specifically I was looking for the best way to either:

  • Tie the original text, including the escape codes back to the categorized slice.
  • Include the byte size of the escape codes for a given categorized slice.

That could be used, in conjunction with the .text field to gain the real width of a CategorizedSlice over its input text.

@kurtlawrence
Copy link
Collaborator

I think you could use the fact that the CategorisedSlice has start and end fields. Each slice can be considered to contain a leading 'style' which is the escape code.

For example, take the following:

let x = format!("{}, {}!", "Hello".blue().on_green(), "world".red().on_yellow());
println!("{x:?}");

let [hello, comma, world, bang]: [v3::CategorisedSlice; 4] = 
v3::categorise_text(&x).try_into().unwrap();

let hello_rng = 0..hello.end;
let comma_rng = hello.end..comma.end;
let world_rng = comma.end..world.end;
let bang_rng = world.end..bang.end;

dbg!(&x[hello_rng]);
dbg!(&x[comma_rng]);
dbg!(&x[world_rng]);
dbg!(&x[bang_rng]);

It will print out:

"\u{1b}[42;34mHello\u{1b}[0m, \u{1b}[43;31mworld\u{1b}[0m!"
[src/tests.rs:531] &x[hello_rng] = "\u{1b}[42;34mHello"
[src/tests.rs:532] &x[comma_rng] = "\u{1b}[0m, "
[src/tests.rs:533] &x[world_rng] = "\u{1b}[43;31mworld"
[src/tests.rs:534] &x[bang_rng] = "\u{1b}[0m!"

Which captures the original escape code sequences.

If you need a 'trailing' escape code sequence (say \u{1b}[42;34mHello\u{1b}[0m), you could use 0..comma.start.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants