### Install ansi2html
Source: https://ansi2html.readthedocs.io/
Install the ansi2html package using pip.
```bash
$ pip3 install ansi2html
```
--------------------------------
### Shell Usage Examples
Source: https://ansi2html.readthedocs.io/
Examples of piping command output through ansi2html to generate HTML files. Useful for logs, directory listings, or task outputs.
```bash
$ ls --color=always | ansi2html > directories.html
```
```bash
$ sudo tail /var/log/messages | ccze -A | ansi2html > logs.html
```
```bash
$ task rc._forcecolor:yes limit:0 burndown | ansi2html > burndown.html
```
--------------------------------
### Display Full Options
Source: https://ansi2html.readthedocs.io/
Run ansi2html with the --help flag to see all available command-line options and configurations.
```bash
$ ansi2html --help
```
--------------------------------
### prepare
Source: https://ansi2html.readthedocs.io/api
Loads ANSI content into the object and prepares it for conversion. It processes the ANSI string, applies regex for styling, and optionally ensures a trailing newline.
```APIDOC
## prepare
### Description
Loads the contents of 'ansi' into this object.
### Method
`prepare(ansi: str = "", ensure_trailing_newline: bool = False) -> Attributes`
### Parameters
- **ansi** (str) - Optional - The ANSI sequence string to process.
- **ensure_trailing_newline** (bool) - Optional - If True, ensures that a newline character is present at the end of the processed body.
### Returns
- **Attributes** - A dictionary containing processed attributes like `dark_bg`, `line_wrap`, `font_size`, `body`, and `styles`.
```
--------------------------------
### Initialize Ansi2HTMLConverter
Source: https://ansi2html.readthedocs.io/api
Instantiate the converter with various options to control output formatting, such as enabling/disabling line wrapping, font size, and linkification.
```python
conv = Ansi2HTMLConverter()
ansi = " ".join(sys.stdin.readlines())
html = conv.convert(ansi)
```
```python
conv = Ansi2HTMLConverter(
latex=False,
inline=False,
dark_bg=True,
line_wrap=True,
font_size="normal",
linkify=False,
escaped=True,
markup_lines=False,
output_encoding="utf-8",
scheme="ansi2html",
title="",
)
```
--------------------------------
### Ansi2HTMLConverter Constructor
Source: https://ansi2html.readthedocs.io/api
Initializes the Ansi2HTMLConverter with various configuration options.
```APIDOC
## Ansi2HTMLConverter()
### Description
Initializes the Ansi2HTMLConverter with various configuration options to control the conversion process.
### Parameters
- **latex** (bool) - Optional - If True, output will be LaTeX compatible.
- **inline** (bool) - Optional - If True, styles will be inlined.
- **dark_bg** (bool) - Optional - If True, assumes a dark background for styling.
- **line_wrap** (bool) - Optional - If True, enables line wrapping.
- **font_size** (str) - Optional - Sets the font size for the output.
- **linkify** (bool) - Optional - If True, URLs in the text will be converted to hyperlinks.
- **escaped** (bool) - Optional - If True, input is assumed to be escaped.
- **markup_lines** (bool) - Optional - If True, each line will be wrapped in a span with an ID.
- **output_encoding** (str) - Optional - Specifies the output encoding.
- **scheme** (str) - Optional - The color scheme to use for conversion.
- **title** (str) - Optional - The title for the generated HTML document.
```
--------------------------------
### prepare
Source: https://ansi2html.readthedocs.io/api
Prepares the ANSI string by applying regular expressions to extract styles and body content. This method is typically called internally by `convert` but can be used directly.
```APIDOC
## prepare(ansi='', ensure_trailing_newline=False)
### Description
Prepares the ANSI string by applying regular expressions to extract styles and body content. This method is typically called internally by `convert` but can be used directly.
### Parameters
- **ansi** (str) - Optional - The ANSI string to prepare. Defaults to an empty string.
- **ensure_trailing_newline** (bool) - Optional - Ensures that `\n` character is present at the end of the output. Defaults to False.
### Returns
- **Attributes** - A dictionary containing the prepared attributes, including 'body' and 'styles'.
```
--------------------------------
### Prepare ANSI string for conversion
Source: https://ansi2html.readthedocs.io/api
Loads ANSI string content, applies regex for body and styles, and optionally ensures a trailing newline. The result is stored in internal attributes for subsequent conversion.
```python
def prepare(
self,
ansi: str = "", ensure_trailing_newline: bool = False
) -> Attributes:
"""Load the contents of 'ansi' into this object"""
body, styles = self.apply_regex(ansi)
if ensure_trailing_newline and _needs_extra_newline(body):
body += "\n"
self._attrs = {
"dark_bg": self.dark_bg,
"line_wrap": self.line_wrap,
"font_size": self.font_size,
"body": body,
"styles": styles,
}
return self._attrs
```
--------------------------------
### produce_headers
Source: https://ansi2html.readthedocs.io/api
Generates the HTML style headers for the ansi2html output.
```APIDOC
## produce_headers()
### Description
Generates the HTML style headers, including CSS, for the ansi2html output. This method is part of the main class and is used internally to format the output.
### Method
`produce_headers`
### Parameters
This method does not accept any parameters.
### Returns
- `str`: A string containing the HTML style headers.
```
--------------------------------
### Prepare ANSI Input
Source: https://ansi2html.readthedocs.io/api
Loads ANSI input and processes it to extract the HTML body and styles. Optionally ensures a trailing newline character in the output body.
```python
def prepare(
self, ansi: str = "", ensure_trailing_newline: bool = False
) -> Attributes:
"""Load the contents of 'ansi' into this object"""
body, styles = self.apply_regex(ansi)
if ensure_trailing_newline and _needs_extra_newline(body):
body += "\n"
self._attrs = {
"dark_bg": self.dark_bg,
"line_wrap": self.line_wrap,
"font_size": self.font_size,
"body": body,
"styles": styles,
}
return self._attrs
```
--------------------------------
### Ansi2HTMLConverter.handle_osc_links
Source: https://ansi2html.readthedocs.io/api
Handles the conversion of OSC (Operating System Command) link sequences into HTML or LaTeX hyperlinks.
```APIDOC
## Ansi2HTMLConverter.handle_osc_links(part: OSC_Link)
### Description
Processes an OSC_Link object, converting it into an HTML anchor tag or a LaTeX \href command based on the converter's configuration.
### Parameters
- **part** (OSC_Link) - Required - The OSC_Link object containing URL and text.
### Response
#### Success Response (str)
- Returns the formatted hyperlink string.
```
--------------------------------
### Ansi2HTMLConverter.do_linkify
Source: https://ansi2html.readthedocs.io/api
Applies URL detection and conversion to a given line of text.
```APIDOC
## Ansi2HTMLConverter.do_linkify(line: str)
### Description
Detects URLs within the provided line of text and converts them into hyperlinks. If LaTeX output is enabled, it uses the \url command; otherwise, it generates HTML anchor tags.
### Parameters
- **line** (str) - Required - The line of text to process.
### Response
#### Success Response (str)
- Returns the line with URLs converted to hyperlinks.
```
--------------------------------
### Produce HTML Style Headers
Source: https://ansi2html.readthedocs.io/api
Generates the HTML style tag for the output. This method is part of a class and likely used internally for styling the converted HTML.
```python
def produce_headers(self) -> str:
return '
' % {
"style": "\n".join(
map(str, get_styles(self.dark_bg, self.line_wrap, self.scheme))
)
}
```
--------------------------------
### Check and Process Links
Source: https://ansi2html.readthedocs.io/api
Iterates through parsed parts, applying linkification to URLs and handling OSC links. This generator yields processed parts ready for final HTML assembly.
```python
if self.linkify:
yield self.do_linkify(part)
else:
yield part
```
--------------------------------
### Handle OSC Links
Source: https://ansi2html.readthedocs.io/api
Processes Operating System Command (OSC) link codes, converting them to HTML anchor tags or LaTeX \href commands. This is used when OSC links are present in the input and `linkify` is enabled.
```python
return "%s" % (part.url, part.text)
```
--------------------------------
### Python API Usage
Source: https://ansi2html.readthedocs.io/
Use the Ansi2HTMLConverter class to convert ANSI colored text to HTML within a Python script. Ensure sys is imported if reading from stdin.
```python
from ansi2html import Ansi2HTMLConverter
conv = Ansi2HTMLConverter()
ansi = "".join(sys.stdin.readlines())
html = conv.convert(ansi)
```
--------------------------------
### Convert ANSI to HTML or LaTeX
Source: https://ansi2html.readthedocs.io/api
Converts an ANSI string to either HTML or LaTeX format. It prepares the content, retrieves necessary styles, and formats the output using predefined templates. Options for full document inclusion and trailing newline are available.
```python
def convert(
self,
ansi: str,
full: bool = True,
ensure_trailing_newline: bool = False
) -> str:
r"""
:param ansi: ANSI sequence to convert.
:param full: Whether to include the full HTML document or only the body.
:param ensure_trailing_newline: Ensures that ``\n`` character is present at the end of the output.
"""
attrs = self.prepare(ansi, ensure_trailing_newline=ensure_trailing_newline)
if not full:
return attrs["body"]
if self.latex:
_template = _latex_template
else:
_template = _html_template
all_styles = get_styles(self.dark_bg, self.line_wrap, self.scheme)
backgrounds = all_styles[:5]
used_styles = filter(
lambda e: e.klass.lstrip(".") in attrs["styles"],
all_styles,
)
return _template % {
"style": "\n".join(list(map(str, backgrounds + list(used_styles)))),
"title": self.title,
"font_size": self.font_size,
"content": attrs["body"],
"output_encoding": self.output_encoding,
"hyperref": "\\usepackage{hyperref}" if self.hyperref else "",
}
```
--------------------------------
### Linkify URLs in Text
Source: https://ansi2html.readthedocs.io/api
Applies URL detection and conversion to HTML anchor tags or LaTeX \url commands. This method is used internally when the `linkify` option is enabled.
```python
return self.url_matcher.sub(r"\1", line)
```
--------------------------------
### convert
Source: https://ansi2html.readthedocs.io/api
Converts an ANSI escape sequence string into either a full HTML/LaTeX document or just the body content. It utilizes the prepare method to process the input.
```APIDOC
## convert
### Description
Converts an ANSI sequence to HTML or LaTeX.
### Method
`convert(ansi: str, full: bool = True, ensure_trailing_newline: bool = False) -> str`
### Parameters
- **ansi** (str) - The ANSI sequence to convert.
- **full** (bool) - Optional - If True, returns a full HTML document; otherwise, returns only the body content. Defaults to True.
- **ensure_trailing_newline** (bool) - Optional - Ensures that a newline character is present at the end of the output. Defaults to False.
### Returns
- **str** - The converted string, either as a full document or just the body content.
```
--------------------------------
### Combine Processed Parts
Source: https://ansi2html.readthedocs.io/api
Joins the processed parts into a single HTML string. If `markup_lines` is enabled and not in LaTeX mode, it wraps each line with a span for line identification.
```python
combined = "".join(parts)
```
```python
combined = "\n".join([
"%s" % (i, line)
```
--------------------------------
### convert
Source: https://ansi2html.readthedocs.io/api
Converts an ANSI string into an HTML string. It can generate a full HTML document or just the body content, and optionally ensure a trailing newline.
```APIDOC
## convert(ansi, full=True, ensure_trailing_newline=False)
### Description
Converts an ANSI string into an HTML string. It can generate a full HTML document or just the body content, and optionally ensure a trailing newline.
### Parameters
- **ansi** (str) - Required - ANSI sequence to convert.
- **full** (bool) - Optional - Whether to include the full HTML document or only the body. Defaults to True.
- **ensure_trailing_newline** (bool) - Optional - Ensures that `\n` character is present at the end of the output. Defaults to False.
### Returns
- **str** - The converted HTML string.
```
--------------------------------
### Convert ANSI to HTML
Source: https://ansi2html.readthedocs.io/api
Converts ANSI escape sequences to HTML. Use `full=True` for a complete HTML document or `full=False` for just the body. The `ensure_trailing_newline` parameter adds a newline if needed.
```python
def convert(
self, ansi: str, full: bool = True, ensure_trailing_newline: bool = False
) -> str:
r"""
:param ansi: ANSI sequence to convert.
:param full: Whether to include the full HTML document or only the body.
:param ensure_trailing_newline: Ensures that ``\n`` character is present at the end of the output.
"""
attrs = self.prepare(ansi, ensure_trailing_newline=ensure_trailing_newline)
if not full:
return attrs["body"]
if self.latex:
_template = _latex_template
else:
_template = _html_template
all_styles = get_styles(self.dark_bg, self.line_wrap, self.scheme)
backgrounds = all_styles[:5]
used_styles = filter(
lambda e: e.klass.lstrip(".") in attrs["styles"],
all_styles,
)
return _template % {
"style": "\n".join(list(map(str, backgrounds + list(used_styles)))),
"title": self.title,
"font_size": self.font_size,
"content": attrs["body"],
"output_encoding": self.output_encoding,
"hyperref": "\\usepackage{hyperref}" if self.hyperref else "",
}
```
--------------------------------
### Ansi2HTMLConverter.convert
Source: https://ansi2html.readthedocs.io/api
Converts a string containing ANSI color codes into an HTML string.
```APIDOC
## Ansi2HTMLConverter.convert(ansi: str)
### Description
Converts a string containing ANSI color codes into an HTML string, applying the configured styling and options.
### Parameters
- **ansi** (str) - Required - The input string containing ANSI color codes.
### Response
#### Success Response (str)
- Returns the converted HTML string.
```
--------------------------------
### Apply Regex for ANSI Conversion
Source: https://ansi2html.readthedocs.io/api
Applies regular expressions to process ANSI escape codes, including VT100 box drawing characters and OSC links. It yields processed strings, OSC link objects, or cursor movement commands.
```python
def _apply_regex(
self,
ansi: str,
styles_used: Set[str],
) -> Iterator[Union[str, OSC_Link, CursorMoveUp]]:
if self.escaped:
if (
self.latex
): # Known Perl function which does this: https://tex.stackexchange.com/questions/34580/escape-character-in-latex/119383#119383
specials = OrderedDict([])
else:
specials = OrderedDict(
[
("&", "&"),
("<", "<"),
(">", ">"),
]
)
for pattern, special in specials.items():
ansi = ansi.replace(pattern, special)
def _vt100_box_drawing() -> Iterator[str]:
last_end = 0 # the index of the last end of a code we've seen
box_drawing_mode = False
for match in self.vt100_box_codes_prog.finditer(ansi):
trailer = ansi[last_end : match.start()]
if box_drawing_mode:
for char in trailer:
yield map_vt100_box_code(char)
else:
yield trailer
last_end = match.end()
box_drawing_mode = match.groups()[0] == "0"
yield ansi[last_end:]
ansi = "".join(_vt100_box_drawing())
def _osc_link(ansi: str) -> Iterator[Union[str, OSC_Link]]:
last_end = 0
for match in self.osc_link_re.finditer(ansi):
trailer = ansi[last_end : match.start()]
yield trailer
url = match.groups()[0]
text = match.groups()[1]
yield OSC_Link(url, text)
last_end = match.end()
yield ansi[last_end:]
state = _State()
for part in _osc_link(ansi):
if isinstance(part, OSC_Link):
yield part
else:
yield from self._handle_ansi_code(part, styles_used, state)
if state.inside_span:
if self.latex:
yield "}"
else:
yield ""
```
--------------------------------
### Collapse cursor movements by deleting preceding tokens
Source: https://ansi2html.readthedocs.io/api
This method processes a stream of tokens, removing preceding tokens when a CursorMoveUp command is encountered. It handles OSC_Link and string tokens, ensuring that only valid tokens remain in the final list.
```python
def _collapse_cursor(
self,
parts: Iterator[Union[str, OSC_Link, CursorMoveUp]]
) -> List[Union[str, OSC_Link]]:
"""Act on any CursorMoveUp commands by deleting preceding tokens"""
final_parts: List[Union[str, OSC_Link]] = []
for part in parts:
# Throw out empty string tokens ("')
if not part:
continue
# Go back, deleting every token in the last 'line'
if isinstance(part, CursorMoveUp):
if final_parts:
final_parts.pop()
while final_parts and (
isinstance(final_parts[-1], OSC_Link)
or (
isinstance(final_parts[-1], str) and "\n" not in final_parts[-1]
)
):
final_parts.pop()
continue
# Otherwise, just pass this token forward
final_parts.append(part)
return final_parts
```
--------------------------------
### Convert ANSI to HTML
Source: https://ansi2html.readthedocs.io/api
Converts a string containing ANSI color codes into an HTML string. This method processes the input and applies the configured styling and options.
```python
html = conv.convert(ansi)
```
--------------------------------
### Apply Regex for ANSI Codes
Source: https://ansi2html.readthedocs.io/api
Internal method to apply regular expressions to parse ANSI escape codes within the input string. It identifies styles and parts of the text, returning them along with a set of used styles.
```python
all_parts = self._apply_regex(ansi, styles_used)
```
--------------------------------
### Handle ANSI Codes and Styles
Source: https://ansi2html.readthedocs.io/api
Processes ANSI escape codes within a string, applying styles and handling special commands like cursor movement. It manages state for nested spans and resets styles when a full reset code is encountered.
```python
def _handle_ansi_code(
self,
ansi: str,
styles_used: Set[str],
state: _State,
) -> Iterator[Union[str, CursorMoveUp]]:
last_end = 0 # the index of the last end of a code we've seen
for match in self.ansi_codes_prog.finditer(ansi):
yield ansi[last_end : match.start()]
last_end = match.end()
params: Union[str, List[int]]
params, command = match.groups()
if command not in "mMA":
continue
# Special cursor-moving code. The only supported one.
if command == "A":
yield CursorMoveUp()
continue
while True:
param_len = len(params)
params = params.replace("::", ":")
params = params.replace(";;", ";")
if len(params) == param_len:
break
try:
params = [int(x) for x in re.split("[;:]", params)]
except ValueError:
params = [ANSI_FULL_RESET]
# Find latest reset marker
last_null_index = None
skip_after_index = -1
for i, v in enumerate(params):
if i <= skip_after_index:
continue
if v == ANSI_FULL_RESET:
last_null_index = i
elif v in (ANSI_FOREGROUND, ANSI_BACKGROUND):
try:
x_bit_color_id = params[i + 1]
except IndexError:
x_bit_color_id = -1
is_256_color = x_bit_color_id == ANSI_256_COLOR_ID
shift = 2 if is_256_color else 4
skip_after_index = i + shift
# Process reset marker, drop everything before
if last_null_index is not None:
params = params[last_null_index + 1 :]
if state.inside_span:
state.inside_span = False
if self.latex:
yield "}"
else:
yield ""
state.reset()
if not params:
continue
# Turn codes into CSS classes
skip_after_index = -1
for i, v in enumerate(params):
if i <= skip_after_index:
continue
is_x_bit_color = v in (ANSI_FOREGROUND, ANSI_BACKGROUND)
try:
x_bit_color_id = params[i + 1]
except IndexError:
x_bit_color_id = -1
```
--------------------------------
### Collapse Cursor Movement Codes
Source: https://ansi2html.readthedocs.io/api
Removes ANSI escape codes related to cursor movement from the parsed parts. This ensures that only visible text and formatting are retained in the final output.
```python
no_cursor_parts = self._collapse_cursor(all_parts)
```
--------------------------------
### Process ANSI escape codes and manage styles
Source: https://ansi2html.readthedocs.io/api
This code processes ANSI escape codes, determining color modes and adjusting text states. It handles both 256-color and truecolor modes, and manages the rendering of spans for inline or block elements, including LaTeX output.
```python
is_256_color = x_bit_color_id == ANSI_256_COLOR_ID
is_truecolor = x_bit_color_id == ANSI_TRUECOLOR_ID
if is_x_bit_color and is_256_color:
try:
parameter: Optional[str] = str(params[i + 2])
except IndexError:
continue
skip_after_index = i + 2
elif is_x_bit_color and is_truecolor:
try:
state.adjust_truecolor(
v, params[i + 2], params[i + 3], params[i + 4]
)
except IndexError:
continue
skip_after_index = i + 4
continue
else:
parameter = None
state.adjust(v, parameter=parameter)
if state.inside_span:
if self.latex:
yield "}"
else:
yield ""
state.inside_span = False
css_classes = state.to_css_classes()
if not css_classes:
continue
styles_used.update(css_classes)
if self.inline:
self.styles.update(pop_truecolor_styles())
if self.latex:
style = [
self.styles[klass].kwl[0][1]
for klass in css_classes
if self.styles[klass].kwl[0][0] == "color"
]
yield "\\textcolor[HTML]{%s}{" % style[0]
else:
style = [
self.styles[klass].kw
for klass in css_classes
if klass in self.styles
]
yield '' % "; ".join(style)
else:
if self.latex:
yield "\\textcolor{%s}{" % " ".join(css_classes)
else:
yield '' % " ".join(css_classes)
state.inside_span = True
yield ansi[last_end:]
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.