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) mocksoul@mocksoul-notebook ~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) mocksoul@mocksoul-notebook ~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
Terminal compatible with ansi-bbs. Meant to be a prototype, but published because why not.

pybbsterm: Terminal emulator for calling BBSs. Use cases (non-exhaustive) Explore terminal protocols. Connect to BBSs. Highlights Python 3.8+ code. Bu

Roc Vallès i Domènech 9 Apr 29, 2022
TB Set color display - Add-on for Blender to set multiple objects and material Display Color at once.

TB_Set_color_display Add-on for Blender with operations to transfer name between object, data, materials and action names Set groups of object's or ma

null 1 Jun 1, 2022
It is a Blender Tool which can convert the Object Data Attributes in face corner to the UVs or Vertex Color.

Blender_ObjectDataAttributesConvertTool It is a Blender Tool which can convert the Object Data Attributes in face corner to the UVs or Vertex Color. D

Takeshi Chō 2 Jan 8, 2022
Print 'text color' and 'text format' on Term with Python

term-printer Print 'text color' and 'text format' on Term with Python ※ It may not work depending on the OS and shell used. PIP $ pip install term-pri

ななといつ 10 Nov 12, 2022
laTEX is awesome but we are lazy -> groff with markdown syntax and inline code execution

pyGroff A wrapper for groff using python to have a nicer syntax for groff documents DOCUMENTATION Very similar to markdown. So if you know what that i

Subhaditya Mukherjee 27 Jul 23, 2022
A minimalist personal blogging system that natively supports Markdown, LaTeX, and code highlighting.

December Welcome to the December blogging system's code repository! Introduction December is a minimalist personal blogging system that natively suppo

TriNitroTofu 10 Dec 5, 2022
Configure request params such as text, color, size etc. And then download the image

Configure request params such as text, color, size etc. And then download the image

null 6 Aug 18, 2022
Scientific color maps and standardization tools

Scicomap is a package that provides scientific color maps and tools to standardize your favourite color maps if you don't like the built-in ones. Scicomap currently provides sequential, bi-sequential, diverging, circular, qualitative and miscellaneous color maps. You can easily draw examples, compare the rendering, see how colorblind people will perceive the color maps. I will illustrate the scicomap capabilities below.

Thomas Bury 14 Nov 30, 2022
A new mini-batch framework for optimal transport in deep generative models, deep domain adaptation, approximate Bayesian computation, color transfer, and gradient flow.

BoMb-OT Python3 implementation of the papers On Transportation of Mini-batches: A Hierarchical Approach and Improving Mini-batch Optimal Transport via

Khai Ba Nguyen 18 Nov 14, 2022
A simple single-color identicon generator

Identicons What are identicons? Setup: git clone https://github.com/vjdad4m/identicons.git cd identicons pip3 install -r requirements.txt chmod +x

Adam Vajda 1 Oct 31, 2021
The goal of this program was to find the most common color in my living room.

The goal of this program was to find the most common color in my living room. I found a dataset online with colors names and their corr

null 1 Nov 9, 2021
A lighweight screen color picker tool

tkpick A lighweigt screen color picker tool Availability Only GNU/Linux ?? Installing Install via pip (No auto-update): [sudo] pip install tkpick Usa

Adil Gürbüz 7 Aug 30, 2021
Coursework project for DIP class. The goal is to use vision to guide the Dashgo robot through two traffic cones in bright color.

Coursework project for DIP class. The goal is to use vision to guide the Dashgo robot through two traffic cones in bright color.

Yueqian Liu 3 Oct 24, 2022
A Tandy Color Computer 1, 2, and 3 assembler written in Python

CoCo Assembler and File Utility Table of Contents What is it? Requirements License Installing Assembler Assembler Usage Input File Format Print Symbol

Craig Thomas 16 Nov 3, 2022
Visualize Data From Stray Scanner https://keke.dev/blog/2021/03/10/Stray-Scanner.html

StrayVisualizer A set of scripts to work with data collected using Stray Scanner. Usage Installing Dependencies Install dependencies with pip -r requi

Kenneth Blomqvist 45 Dec 30, 2022
Fetch data from an excel file and create HTML file

excel-to-html Problem Statement! - Fetch data from excel file and create html file Excel.xlsx file contain the information.in multiple rows that is ne

Vivek Kashyap 1 Oct 25, 2021
This python code will get requests from SET (The Stock Exchange of Thailand) a previously-close stock price and return it in Thai Baht currency using beautiful soup 4 HTML scrapper.

This python code will get requests from SET (The Stock Exchange of Thailand) a previously-close stock price and return it in Thai Baht currency using beautiful soup 4 HTML scrapper.

Andre 1 Oct 24, 2022
apysc is the Python frontend library to create html and js file, that has ActionScript 3 (as3)-like interface.

apysc apysc is the Python frontend library to create HTML and js files, that has ActionScript 3 (as3)-like interface. Notes: Currently developing and

simonritchie 17 Dec 14, 2022
We'll be using HTML, CSS and JavaScript for the frontend

We'll be using HTML, CSS and JavaScript for the frontend. Nothing to install in specific. Open your text-editor and start coding a beautiful front-end.

Mugada sai tilak 1 Dec 15, 2021