#![no_std]
#![doc(html_root_url = "https://docs.rs/slice-ansi/0.1.0")]
extern crate alloc;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use unicode_width::UnicodeWidthChar;
const RESET: &str = "\u{1b}[0m";
const OSC8_CLOSE: &str = "\u{1b}]8;;\u{1b}\\";
#[must_use]
pub fn width(text: &str) -> usize {
let chars: Vec<char> = text.chars().collect();
let mut total = 0;
let mut i = 0;
while i < chars.len() {
let (scanned, next) = scan(&chars, i);
if let Scanned::Visible(c) = scanned {
total += char_width(c);
}
i = next;
}
total
}
#[must_use]
pub fn slice(text: &str, start: usize, end: usize) -> String {
if start >= end {
return String::new();
}
let toks = tokenize(text);
let mut col = 0;
let mut sgr: Vec<String> = Vec::new();
let mut link: Option<String> = None;
let mut lo: Option<usize> = None;
let mut hi = 0;
let mut sgr_at_lo: Vec<String> = Vec::new();
let mut link_at_lo: Option<String> = None;
for (idx, t) in toks.iter().enumerate() {
match t {
Tok::Esc(s) => {
update_sgr(&mut sgr, s);
update_link(&mut link, s);
}
Tok::Ch(_, w) => {
let (cs, ce) = (col, col + w);
if cs >= end {
break;
}
if cs >= start && ce <= end {
if lo.is_none() {
lo = Some(idx);
sgr_at_lo.clone_from(&sgr);
link_at_lo.clone_from(&link);
}
hi = idx + 1;
}
col = ce;
}
}
}
let Some(lo) = lo else {
return String::new();
};
let mut out = String::new();
if let Some(l) = &link_at_lo {
out.push_str(l);
}
for code in &sgr_at_lo {
out.push_str(code);
}
let mut open_sgr = sgr_at_lo;
let mut open_link = link_at_lo;
for t in &toks[lo..hi] {
match t {
Tok::Esc(s) => {
out.push_str(s);
update_sgr(&mut open_sgr, s);
update_link(&mut open_link, s);
}
Tok::Ch(s, _) => out.push_str(s),
}
}
if !open_sgr.is_empty() {
out.push_str(RESET);
}
if open_link.is_some() {
out.push_str(OSC8_CLOSE);
}
out
}
#[must_use]
pub fn slice_from(text: &str, start: usize) -> String {
slice(text, start, width(text))
}
fn update_sgr(active: &mut Vec<String>, seq: &str) {
let Some(params) = sgr_params(seq) else {
return;
};
let mut last_reset = None;
let mut count = 0;
for (i, p) in params.split(';').enumerate() {
if is_reset_param(p) {
last_reset = Some(i);
}
count = i + 1;
}
match last_reset {
Some(idx) => {
active.clear();
if idx + 1 < count {
active.push(seq.to_string());
}
}
None => active.push(seq.to_string()),
}
}
fn is_reset_param(p: &str) -> bool {
p.is_empty() || p.bytes().all(|b| b == b'0')
}
fn sgr_params(seq: &str) -> Option<&str> {
let body = match seq.strip_prefix('\u{1b}') {
Some(rest) => rest.strip_prefix('[')?,
None => seq.strip_prefix('\u{9b}')?,
};
body.strip_suffix('m')
}
fn update_link(link: &mut Option<String>, seq: &str) {
match osc8_kind(seq) {
Some(true) => *link = Some(seq.to_string()),
Some(false) => *link = None,
None => {}
}
}
fn osc8_kind(seq: &str) -> Option<bool> {
let body = match seq.strip_prefix('\u{1b}') {
Some(rest) => rest.strip_prefix(']')?,
None => seq.strip_prefix('\u{9d}')?,
};
let body = body.strip_prefix("8;")?;
let body = body
.strip_suffix('\u{07}')
.or_else(|| body.strip_suffix("\u{1b}\\"))
.or_else(|| body.strip_suffix('\u{9c}'))?;
let uri = body.split_once(';')?.1;
Some(!uri.is_empty())
}
enum Tok {
Esc(String),
Ch(String, usize),
}
fn tokenize(text: &str) -> Vec<Tok> {
let chars: Vec<char> = text.chars().collect();
let mut toks = Vec::new();
let mut i = 0;
while i < chars.len() {
let (scanned, next) = scan(&chars, i);
match scanned {
Scanned::Escape(seq) => {
toks.push(Tok::Esc(seq));
i = next;
}
Scanned::Control => i = next,
Scanned::Visible(c) => {
let w = char_width(c);
let mut glyph = String::new();
glyph.push(c);
i = next;
while i < chars.len() {
let (sc, nx) = scan(&chars, i);
match sc {
Scanned::Visible(c2) if char_width(c2) == 0 => {
glyph.push(c2);
i = nx;
}
_ => break,
}
}
toks.push(Tok::Ch(glyph, w));
}
}
}
toks
}
fn char_width(c: char) -> usize {
UnicodeWidthChar::width(c).unwrap_or(0)
}
enum Scanned {
Escape(String),
Visible(char),
Control,
}
fn scan(chars: &[char], i: usize) -> (Scanned, usize) {
let c = chars[i];
if c == '\u{1b}' {
return scan_escape(chars, i);
}
match c {
'\u{9b}' => return scan_csi(chars, i + 1, i),
'\u{90}' | '\u{9d}' | '\u{98}' | '\u{9e}' | '\u{9f}' => {
return scan_string_sequence(chars, i + 1, i);
}
_ => {}
}
if c.is_control() {
return (Scanned::Control, i + 1);
}
(Scanned::Visible(c), i + 1)
}
fn scan_escape(chars: &[char], i: usize) -> (Scanned, usize) {
match chars.get(i + 1).copied() {
Some('[') => scan_csi(chars, i + 2, i),
Some(']' | 'P' | 'X' | '^' | '_') => scan_string_sequence(chars, i + 2, i),
Some(c) if ('\u{20}'..='\u{2f}').contains(&c) => {
let mut j = i + 2;
while j < chars.len() && ('\u{20}'..='\u{2f}').contains(&chars[j]) {
j += 1;
}
if j < chars.len() && ('\u{30}'..='\u{7e}').contains(&chars[j]) {
j += 1;
}
(Scanned::Escape(collect(chars, i, j)), j)
}
Some(c) if ('\u{30}'..='\u{7e}').contains(&c) => {
(Scanned::Escape(collect(chars, i, i + 2)), i + 2)
}
_ => (Scanned::Escape(collect(chars, i, i + 1)), i + 1),
}
}
fn scan_csi(chars: &[char], body: usize, start: usize) -> (Scanned, usize) {
let mut j = body;
while j < chars.len() && ('\u{30}'..='\u{3f}').contains(&chars[j]) {
j += 1;
}
while j < chars.len() && ('\u{20}'..='\u{2f}').contains(&chars[j]) {
j += 1;
}
if j < chars.len() && ('\u{40}'..='\u{7e}').contains(&chars[j]) {
j += 1;
}
(Scanned::Escape(collect(chars, start, j)), j)
}
fn scan_string_sequence(chars: &[char], body: usize, start: usize) -> (Scanned, usize) {
let mut j = body;
while j < chars.len() {
let c = chars[j];
if c == '\u{07}' || c == '\u{9c}' {
j += 1;
break;
}
if c == '\u{1b}' && chars.get(j + 1) == Some(&'\\') {
j += 2;
break;
}
j += 1;
}
(Scanned::Escape(collect(chars, start, j)), j)
}
fn collect(chars: &[char], start: usize, end: usize) -> String {
chars[start..end].iter().collect()
}