Convert text with ANSI color codes to HTML or to LaTeX.

Overview
Build Status - main branch

ansi2html

Author: Ralph Bean <[email protected]>
Contributor: Robin Schneider <[email protected]>

Convert text with ANSI color codes to HTML or to LaTeX.

Inspired by and developed off of the work of pixelbeat and blackjack.

Read the docs for more informations.

Example - Python API

>> html = conv.convert(ansi)">
>>> from ansi2html import Ansi2HTMLConverter
>>> conv = Ansi2HTMLConverter()
>>> ansi = "".join(sys.stdin.readlines())
>>> html = conv.convert(ansi)

Example - Shell Usage

$ ls --color=always | ansi2html > directories.html
$ sudo tail /var/log/messages | ccze -A | ansi2html > logs.html
$ task rc._forcecolor:yes limit:0 burndown | ansi2html > burndown.html

See the list of full options with:

$ ansi2html --help

Get this project:

$ pip3 install ansi2html

Source: https://github.com/pycontribs/ansi2html/

pypi: https://pypi.org/project/ansi2html/

License

ansi2html is licensed LGPLv3+.

Comments
  • Fixes to respect bright colors in palette

    Fixes to respect bright colors in palette

    Fixes #133

    It seems there are two errors in the existing logic in style.py:

    1. When a palette defines the upper 8 colors (the "bright" colors), the existing code overwrites them anyway using the results of intensify.
    2. When a palette does not define the upper 8 colors, the existing code does not define replacements for them in the 256-color palette rule families.

    In other words, the code was overwriting some of the explicitly defined colors, but also failing to provide automatically brightened colors when it could have :-)

    Note that with this fix in place, the existing test suite doesn't "pass" because the output colors will be different. For some users, this may be an unexpected change in behavior. In that case, maybe the old behavior should be preserved as a default while the new behavior is toggled optionally.

    The code could be optimized to not make so many redundant calls to intensify, but I haven't bothered to make that change here.

    bug 
    opened by echuber2 41
  • gpl license prevents direct usage in non-gpl python tools

    gpl license prevents direct usage in non-gpl python tools

    hi,

    pytest-dev/pytest-html#96 has just brought this to my attention, as things are pytest-html would have to drop usage and/or implement an sub-process communication to keep using ansi2html while also keeping its own license terms

    i would like to solve this by just version-bumping the ansi2html dependency but i can understand if you want to keep the gpl

    opened by RonnyPfannschmidt 40
  • missing header.mak when easy_installed on Python 2.6

    missing header.mak when easy_installed on Python 2.6

    It seems header.mak is not being included when ansi2html is installed via easy_install on Python 2.6, which results in:

      File "/Library/Python/2.6/site-packages/tw2.core-2.0b4-py2.6.egg/tw2/core/dottedtemplatelookup.py", line 103, in __load
        self.template_cache[template_name] = Template(open(filename).read(),
    IOError: [Errno 2] No such file or directory: u'/Users/ana/.python-eggs/ansi2html-0.6.0-py2.6.egg-tmp/ansi2html/templates/header.mak'
    

    When I look in the directory it's trying to search:

    $ tree /Users/ana/.python-eggs/ansi2html-0.6.0-py2.6.egg-tmp/ansi2html/
    /Users/ana/.python-eggs/ansi2html-0.6.0-py2.6.egg-tmp/ansi2html/
    └── templates
        └── full.mak
    

    Installing via pip or from source seems to fix this, and the setup.py and MANIFEST.in files look fine to me, so this is probably more of an easy_install issue, but maybe releasing an egg for 2.6 instead of source would be a simple workaround? Or maybe explicitly listing the template files instead of a wildcard?

    Note this was reported to me here: http://discuss.dexy.it/index.php?p=/discussion/13/ioerror-errno-2-no-such-file-or-directory-...-header.mak

    And I have just come across this issue myself on a new machine (OSX 10.6.7) running Python 2.6.1

    opened by ananelson 13
  • Add type hinting

    Add type hinting

    Adds some basic type hinting.

    mypy ansi2html/style.py is happy and mypy ansi2html/converter.py spits out a few errors I don't know how to fix.

    ansi2html/converter.py:38: error: Cannot find implementation or library stub for module named "ordereddict"
    ansi2html/converter.py:38: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
    ansi2html/converter.py:38: error: Name "OrderedDict" already defined (possibly by an import)
    ansi2html/converter.py:559: error: Incompatible return value type (got "Union[bool, str, Set[str]]", expected "str")
    ansi2html/converter.py:567: error: Unsupported right operand type for in ("Union[bool, str, Set[str]]")
    ansi2html/converter.py:726: error: "TextIO" has no attribute "detach"
    Found 5 errors in 1 file (checked 1 source file)
    

    Fixes: #140

    bug 
    opened by ziegenberg 10
  • HTML and URI in source text

    HTML and URI in source text

    This is not an issue, but a feature:

    Another cool feature would be to make it do any of two things:

    --linkify : where it sees ://, make hrefs out of them.

    --has-html: where it sees html tags, render rather than escape them.

    Not a big deal, but might be cool for some ;)

    Nima

    opened by nima 9
  • fix including of CHANGELOG.rst

    fix including of CHANGELOG.rst

    Currently building the documentation does not include the changelog. It fails with the following error:

    Running Sphinx v4.2.0
    building [mo]: all of 0 po files
    building [html]: all source files
    updating environment: [new config] 3 added, 0 changed, 0 removed
    reading sources... [ 33%] api
    reading sources... [ 66%] changelog
    reading sources... [100%] index
    
    /home/daniel/Development/github/ansi2html/docs/source/changelog.rst:4: WARNING: Problems with "include" directive path:
    InputError: [Errno 2] No such file or directory: 'changelog.rst'.
    

    As can be seen here the changelog in the documentation is empty. The documentation built by this CI run does include the recent changelog.

    bug docs 
    opened by ziegenberg 8
  • --partial strips newlines from output

    --partial strips newlines from output

    (virtenv) [email protected] ~ws/repos/pkg/testpack % ls -la | ansi2html-3.2 -p
    total 44 drwxr-xr-x  4 mocksoul users  4096 Aug  9 17:28 . drwxr-xr-x 11 mocksoul users  4096 Aug  9 16:50 .. drwxr-xr-x  6 mocksoul users  4096 Aug  8 19:47 build -rw-r--r--  1 mocksoul users  2219 Aug  1 00:34 cat -rw-r--r--  1 mocksoul users   872 Aug  9 17:13 PKGBUILD drwxr-xr-x  2 mocksoul users  4096 Jul 26 17:39 __pycache__ -rw-r--r--  1 mocksoul users 18084 Aug  9 18:01 res.html %```
    
    ansi2html eat my lines! =)
    
    This is expected output:
    
    ```bash
    
    (virtenv) [email protected] ~ws/repos/pkg/testpack % ls -la --color=always | ansi2html-2.7 -p
    total 44
    drwxr-xr-x  4 mocksoul users  4096 Aug  9 17:28 <span class="ansi1 ansi34">.</span>
    drwxr-xr-x 11 mocksoul users  4096 Aug  9 16:50 <span class="ansi1 ansi34">..</span>
    drwxr-xr-x  6 mocksoul users  4096 Aug  8 19:47 <span class="ansi1 ansi34">build</span>
    -rw-r--r--  1 mocksoul users  2219 Aug  1 00:34 cat
    -rw-r--r--  1 mocksoul users   872 Aug  9 17:13 PKGBUILD
    drwxr-xr-x  2 mocksoul users  4096 Jul 26 17:39 <span class="ansi1 ansi34">__pycache__</span>
    -rw-r--r--  1 mocksoul users 18084 Aug  9 18:01 res.html```
    
    opened by mocksoul 8
  • Color mix

    Color mix

    Hi! I use a buildbot running ansi2html with lettuce's default output to serve some test on a website and I noticed a swap between body_foreground & ansi30 css' colors (#000 and #AAA respectively here).

    Also, since I upgraded of 0.6.x (if I remember correctly) to latest release, I had to patch the code to add an encode('utf-8') to the final print statement to make the program run without "ansi" decode error.

    I am running python2.6 and the content of my environment is:

    USER=fab31
    LOGNAME=fab31
    HOME=/home/fab31
    PATH=/home/fab31/.pythonbrew/bin:/home/fab31/pyenv/bbot/bin:/home/fab31/utils:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games:/home/fab31/.local/bin:/sbin:/usr/sbin:/usr/local/bin:/opt/java/jre/bin
    MAIL=/var/mail/fab31
    SHELL=/bin/zsh
    SSH_CLIENT=79.84.236.37 53268 22
    SSH_CONNECTION=79.84.236.37 53268 88.190.18.171 22
    SSH_TTY=/dev/pts/4
    TERM=xterm
    LANG=fr_FR.UTF-8
    SHLVL=1
    PWD=/home/fab31/pyenv/bbot/master
    OLDPWD=/home/fab31/pyenv/bbot/slave
    G_BROKEN_FILENAMES=1
    LC_NUMERIC=C
    CLICOLOR=1
    SVN_EDITOR=~/utils/svn_editor.sh
    GDK_USE_XFT=1
    PAGER=less
    X2=x2x -west -to :0 -west 
    VISUAL=vim
    EDITOR=vim
    PYTHONSTARTUP=/home/fab31/.pystartup
    HG_REPOS=/home/fab31/prog/hg-stable
    PS1=(bbot)%n@%m:%~%# 
    LS_COLORS=no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:ex=01;32:*.cmd=01;32:*.exe=01;32:*.com=01;32:*.btm=01;32:*.bat=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.bz2=01;31:*.rpm=01;31:*.deb=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.jpg=01;35:*.gif=01;35:*.bmp=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.mpg=01;37:*.avi=01;37:*.mov=01;37:*.tbz=01;31:*.zip=01;31:*.mp3=00;34:*.png=01;35:*.89t=00;33
    VIRTUALENVWRAPPER_VIRTUALENV_ARGS=--no-site-packages
    WORKON_HOME=/home/fab31/pyenv
    VIRTUALENVWRAPPER_LOG_DIR=/home/fab31/pyenv
    PROJECT_HOME=/home/fab31/pyenv
    PIP_VIRTUALENV_BASE=/home/fab31/pyenv
    PIP_RESPECT_VIRTUALENV=true
    VIRTUAL_ENV=/home/fab31/pyenv/bbot
    _=/usr/bin/env
    
    
    opened by fdev31 8
  • Fix --input-encoding=<encoding> regression added in PR #143

    Fix --input-encoding= regression added in PR #143

    While adding type-hinting the option to specify an input encoding got ignored. This commit fixes this regression.

    This commit also fixes the tests which call ansi2html as a command. As the pytest documentation states, during test execution stdin is set to a “null” object which will fail on attempts to read from it because it is rarely desired to wait for interactive input when running automated tests. So we also patch now sys.stdin using an io.TextIOWrapper and wrapping any actual input in a io.BytesIO.

    bug 
    opened by ziegenberg 7
  • Add API documentation generation as part of the build worflow

    Add API documentation generation as part of the build worflow

    Hi,

    This PR adds API documentation with pydoctor.

    This avoids having to skim through the code to find the right arguments to the convert function for instance.

    enhancement 
    opened by tristanlatr 7
  • Does not support 24-bit

    Does not support 24-bit "truecolor" escape sequences.

    A good reference for these escape sequences can be found here: https://gist.github.com/XVilka/8346728

    I took a quick glance at the Ansi2HTMLConverter, and it looks like the regex you're using to parse the escape sequences is robust enough to do the business, but I haven't gone any further than that.

    --Jays

    opened by jaysonlarose 7
  • Copyright headers still refer to GPL

    Copyright headers still refer to GPL

    In #72 you all got consensus to relicense this project under the LGPL v3, but the headers in the source code weren't updated. Could you update them and release a new package please, to resolve any ambiguity?

    bug 
    opened by leifwalsh 2
  • [>=1.7.0a0] typing_extensions missing from requirements

    [>=1.7.0a0] typing_extensions missing from requirements

    Hi! I would like to use ansi2html on a machine running Python 3.7. However, I get the following crash:

    Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import ansi2html
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Program Files\Python37\lib\site-packages\ansi2html\__init__.py", line 1, in <module>
        from ansi2html.converter import Ansi2HTMLConverter
      File "C:\Program Files\Python37\lib\site-packages\ansi2html\converter.py", line 45, in <module>
        from typing_extensions import TypedDict
    ModuleNotFoundError: No module named 'typing_extensions'
    

    I guess the package is missing the dependency, for now I installed it manually. I don't have any experience regarding package setups, so I won't try to submit a fix, but at least wanted to mention it :)

    bug 
    opened by nikluep-3ds 1
  • Support white background (currently always #AAAAAA gray)

    Support white background (currently always #AAAAAA gray)

    Hi. Browsing through style.py seems to indicate there's currently no way to override #AAAAAA with plain old #FFFFFF. Am I missing something, or is this a feature request?

    feature 
    opened by lkraav 4
  • ❤️‍🩹 Looking for maintainers!

    ❤️‍🩹 Looking for maintainers!

    This project could really benefit from some love. I am looking for others that are willing to help maintaining it as my time is very limited these days.

    Please state your interest here, I am more than happy to add new contributors to the project.

    opened by ssbarnea 17
  • Crash for `--latex` and italic `^[[3m`

    Crash for `--latex` and italic `^[[3m`

    Using this example file: italic.txt

    $ cat italic.txt | ansi2html --latex --inline
    

    Crashes with this traceback:

    Traceback (most recent call last):
      File "/usr/bin/ansi2html", line 33, in <module>
        sys.exit(load_entry_point('ansi2html==1.6.0', 'console_scripts', 'ansi2html')())
      File "/usr/lib/python3.9/site-packages/ansi2html/converter.py", line 696, in main
        output = conv.convert(
      File "/usr/lib/python3.9/site-packages/ansi2html/converter.py", line 507, in convert
        attrs = self.prepare(ansi, ensure_trailing_newline=ensure_trailing_newline)
      File "/usr/lib/python3.9/site-packages/ansi2html/converter.py", line 485, in prepare
        body, styles = self.apply_regex(ansi)
      File "/usr/lib/python3.9/site-packages/ansi2html/converter.py", line 300, in apply_regex
        parts = self._collapse_cursor(parts)
      File "/usr/lib/python3.9/site-packages/ansi2html/converter.py", line 461, in _collapse_cursor
        for part in parts:
      File "/usr/lib/python3.9/site-packages/ansi2html/converter.py", line 434, in _apply_regex
        yield "\\textcolor[HTML]{%s}{" % style[0]
    IndexError: list index out of range
    
    bug 
    opened by sedrubal 0
Releases(1.8.0)
  • 1.8.0(Jul 7, 2022)

    Minor Changes

    • style.py: Drop unused CSS class .bold (#161) @hartwork
    • Bring back putting a rendered man page into release archives (fixes #124) (#173) @hartwork
    • Migrate from mock to unittest.mock of Python >=3.3 (fixes #169) (#171) @hartwork

    Bugfixes

    • Fix for ANSI color codes that include blank values (#178) @jaysonlarose
    • Added py.typed file (#176) @abrahammurciano
    • style.py: Get CSS class .inv_foreground in sync with .body_foreground (#160) @hartwork
    • Fix --input-encoding= regression added in PR #143 + related tests (alternative to PR #162) (#172) @hartwork
    • Add ability to also recognize colons in ANSI escapes (#167) @jaysonlarose
    • Fixes to respect bright colors in palette (#126) @echuber2
    • CHANGELOG.rst: Fix misleading 1.6.0 entry and missing 1.7.0 entries (#159) @hartwork

    Kudos goes to: @abrahammurciano, @echuber2, @hartwork, @jaysonlarose, @pre-commit-ci and @pre-commit-ci[bot]

    Source code(tar.gz)
    Source code(zip)
  • 1.7.0(Jan 31, 2022)

    Minor Changes

    • Replace recommendation of using system packages with pip3 (#129) @ssbarnea
    • Add truecolor support (#155) @miltolstoy
    • Generate documentation with Sphinx and use Read the Docs (#141) @tristanlatr
    • Adds support for OSC hyperlink sequences. (#131) @hakonhagland

    Bugfixes

    • Add test coverage (#148) @ziegenberg
    • Replace pkg_resources with importlib.metadata (#144) @ziegenberg
    • fix including of CHANGELOG.rst (#151) @ziegenberg
    • Update linting dependencies (#147) @ziegenberg
    • Upgrade the build process (#145) @ziegenberg
    • Add type hinting (#143) @ziegenberg
    • Update CI badges in readme (#142) @ssbarnea
    • Bump setuptools-scm version (#138) @ssbarnea

    Kudos goes to: @hakonhagland, @miltolstoy, @pre-commit-ci, @pre-commit-ci[bot], @ssbarnea, @tristanlatr and @ziegenberg

    Source code(tar.gz)
    Source code(zip)
  • 1.6.0(Oct 15, 2020)

    Changes

    • Switching from nosetest to unittest (#103) @paolostivanin
    • Add dracula colorscheme (#106) @ahmubashshir
    • Refactor packaging by replacing old setup.py based packaging with modern pep517 based one (#112) @ssbarnea
    • Replace travis with github actions (#121) @ssbarnea

    Bugfixes

    • Correct author metadata (#122) @ssbarnea

    Deprecations

    • Officialy retire support for python <= 3.5 (#112) @ssbarnea

    Kudos goes to: @ssbarnea, @paolostivanin, @ahmubashshir

    Source code(tar.gz)
    Source code(zip)
Owner
PyContribs
PyContribs main purpose is to assure that different Python-related projects remain maintained.
PyContribs
The repository for AnyMacro: a Fusion360 Add-In

AnyMacro AnyMacro is an Autodesk® Fusion 360™ add-in for chaining multiple commands in a row to form Macros. Macros are created from a set of commands

1 Jan 07, 2022
Problem 5: Fermat near-misses

Problem 5: Fermat near-misses fermatnearmiss This is a script that computes fermat nearm misses when the -f option is set and requires users to input

CHRIS BYRON (Int0x80) 1 Jan 08, 2022
Repositório do programa ConstruDelas - Trilha Python - Módulos 1 e 2

ConstruDelas - Introdução ao Python Nome: Visão Geral Bem vinda ao repositório do curso ConstruDelas, módulo de Introdução ao Python. Aqui vamos mante

WoMakersCode 8 Oct 14, 2022
Yandex Media Browser

Браузер медиа для плагина Yandex Station Включайте музыку, плейлисты и радио на Яндекс.Станции из Home Assistant! Скриншот Корневой раздел: Библиотека

Alexander Ryazanov 35 Dec 19, 2022
Draw random mazes in python

a-maze Draw random mazes in python This program generates and draws a rectangular maze, with an entrance on one side and one on the opposite side. The

Andrea Pasquali 1 Nov 21, 2021
JurjenLang, an interpreted programming language

JurjenLang An interpreted programming language Getting started Follow these three steps on your computer to get started git clone https://github.com/J

JVerbruggen 5 May 03, 2022
Scientific Programming: A Crash Course

Scientific Programming: A Crash Course Welcome to the Scientific Programming course. My name is Jon Carr and I am a postdoc in Davide Crepaldi's lab.

Jon Carr 1 Feb 17, 2022
What Do Deep Nets Learn? Class-wise Patterns Revealed in the Input Space

What Do Deep Nets Learn? Class-wise Patterns Revealed in the Input Space Introduction: Environment: Python3.6.5, PyTorch1.5.0 Dataset: CIFAR-10, Image

8 Mar 23, 2022
Time tracking program that will format output to be easily put into Gitlab

time_tracker Time tracking program that will format output to be easily put into Gitlab. Feel free to branch and use it yourself! Getting Started Clon

Jake Strasler 2 Oct 13, 2022
System Design Assignments as part of Arpit's System Design Masterclass

System Design Assignments The repository contains a set of problem statements around Software Architecture and System Design as conducted by Arpit's S

Relog 1.1k Jan 09, 2023
A python script for combining multiple native SU2 format meshes into one mesh file for multi-zone simulations.

A python script for combining multiple native SU2 format meshes into one mesh file for multi-zone simulations.

MKursatUzuner 1 Jan 20, 2022
For radiometrically calibrating and PSF deconvolving IRIS data

irispreppy For radiometrically calibrating and PSF deconvolving IRIS data. I dislike how I need to own proprietary software (IDL) just to simply prepa

Aaron W. Peat 4 Nov 01, 2022
This is a simple SV calling package for diploid assemblies.

dipdiff This is a simple SV calling package for diploid assemblies. It uses a modified version of svim-asm. The package includes its own version minim

Mikhail Kolmogorov 11 Jan 05, 2023
Izy - Python functions and classes that make python even easier than it is

izy Python functions and classes that make it even easier! You will wonder why t

5 Jul 04, 2022
Blender 2.80+ Timelapse Capture Tool Addon

SimpleTimelapser Blender 2.80+ Timelapse Capture Tool Addon Developed for Blender 3.0.0, tested working on 2.80.0 It's no ZBrush undo history but it's

4 Jan 19, 2022
the classic version Of torrentleechx #Unmaintained #Archived

TorrentleechX-Classic Old Modified Version Repo #Unmaintained #Archived for support join here working example group Leech Here For Any Issues/Imroveme

XcodersHub 18 Jan 30, 2022
Suite of tools for retrieving USGS NWIS observations and evaluating National Water Model (NWM) data.

Documentation OWPHydroTools GitHub pages documentation Motivation We developed OWPHydroTools with data scientists in mind. We attempted to ensure the

36 Dec 11, 2022
Research using python - Guide for development of research code (using Anaconda Python)

Guide for development of research code (using Anaconda Python) TL;DR: One time s

Ziv Yaniv 1 Feb 01, 2022
Senator Stock Trading Tester

Senator Stock Trading Tester Program to compare stock performance of Senator's transactions vs when the sale is disclosed. Using to find if tracking S

Cole Cestaro 1 Dec 07, 2021
Framework To Ease Operating with Quantum Computers

QType Framework To Ease Operating with Quantum Computers Concept # define an array of 15 cubits:

Antonio Párraga Navarro 2 Jun 06, 2022