Crate ansi_to_html

source ·
Expand description

Convert a string that can contain ANSI escape codes to HTML.

This crate currently supports SGR parameters (text style and colors). The supported styles are:

  • bold
  • italic
  • underlined
  • crossed out
  • faint
  • foreground and background colors: 3-bit, 4-bit, 8-bit, truecolor (24-bit)

Not supported SGR parameters (note that most of these are niche features and rarely supported by terminals):

  • slow/rapid blink
  • reverse video
  • conceal
  • alternative fonts
  • fraktur
  • doubly underlined
  • proportional spacing
  • framed
  • encircled
  • overlined
  • underline color (not in standard)
  • ideogram attributes
  • superscript, subscript (not in standard)
  • bright foreground/background color (not in standard)

All unsupported ANSI escape codes are stripped from the output.

It should be easy to add support for more styles, if there’s a straightforward HTML representation. If you need a different style (e.g. doubly underlined), file an issue.

Example

let bold = "\x1b[1m";
let red = "\x1b[31m";
let input = format!("<h1> {bold}Hello {red}world! </h1>");
let converted = ansi_to_html::convert(&input).unwrap();
assert_eq!(
    converted,
    "&lt;h1&gt; <b>Hello <span style='color:var(--red,#a00)'>world! &lt;/h1&gt;</span></b>"
);

Features

Enable the lazy-init feature to initialize a few things lazily, which is faster if you’re converting many strings.

Structs

Enums

  • Errors that can occur when converting an ANSI string to HTML

Functions

  • Converts a string containing ANSI escape codes to HTML.
  • Converts a string containing ANSI escape codes to HTML with customized behavior.