An ANSI to HTML5 converter

Related tags

Strings ansi-to-html
Overview

ANSI to HTML5 Converter

This small library only does one thing: converting a text containing ANSI codes to an HTML5 fragment:

require_once __DIR__.'/vendor/autoload.php';

use SensioLabs\AnsiConverter\AnsiToHtmlConverter;

$converter = new AnsiToHtmlConverter();

$html = $converter->convert($ansi);

The $ansi variable should contain a text with ANSI codes, and $html will contain the converted HTML5 version of it.

You can then output the HTML5 fragment in any HTML document:

<html>
    <body>
        <pre style="background-color: black; overflow: auto; padding: 10px 15px; font-family: monospace;"
        ><?php echo $html ?></pre>
    </body>
</html>

The converter supports different color themes:

use SensioLabs\AnsiConverter\Theme\SolarizedTheme;

$theme = new SolarizedTheme();
$converter = new AnsiToHtmlConverter($theme);

By default, the colors are inlined into the HTML, but you can also use classes by turning off style inlining:

$converter = new AnsiToHtmlConverter($theme, false);

And the asCss() method of the theme object lets you retrieve the theme styles as a CSS snippet:

$styles = $theme->asCss();

which you can then use in your HTML document:

<html>
    <head>
        <style>
            <?php echo $styles ?>

            .ansi_box { overflow: auto; padding: 10px 15px; font-family: monospace; }
        </style>
    </head>
    <body>
        <pre class="ansi_color_bg_black ansi_color_fg_white ansi_box"><?php echo $html ?></pre>
    </body>
</html>

Twig Integration

Register the extension:

use SensioLabs\AnsiConverter\Bridge\Twig\AnsiExtension;

$twig->addExtension(AnsiExtension());

It's possible to use a custom AnsiToHtmlConverter:

use SensioLabs\AnsiConverter\Bridge\Twig\AnsiExtension;
use SensioLabs\AnsiConverter\Theme\SolarizedTheme;

$theme = new SolarizedTheme();
$converter = new AnsiToHtmlConverter($theme, false);

$twig->addExtension(AnsiExtension($converter));

Then:

<html>
    <head>
        <style>
            {# This is only need if the inline styling is disabled #}
            {{ ansi_css }}
        </style>
    </head>
    <body>
        {{ some_ansi_code|ansi_to_html }}
    </body>
</html>
Comments
  • carriage return issue

    carriage return issue

    In convert() method, if detect \r, erase the entire line :

    replace: $text = preg_replace('#^.*\r(?!\n)#m', '', $text);

    by: $text = preg_replace('#^(.*)\r(?!\n)#m', '$1', $text);

    opened by Broutard 5
  • minor corrections

    minor corrections

    | Q | A | | --- | --- | | Bug Fix? | no | | New Feature? | no | | BC Breaks? | no | | Deprecations? | no | | Tests Pass? | yes | | Fixed Tickets | | | License | MIT |

    opened by cordoval 3
  • fix convert underline to html style

    fix convert underline to html style

    I had a problem with displaying results is Sismo.

    ( ! ) Notice: Undefined variable: text in Sismo/vendor/sensiolabs/ansi-to-html/SensioLabs/AnsiConverter/AnsiToHtmlConverter.php on line 112
    

    It turns out that converting underline to html isn't properly done so i made this fix.

    opened by adam187 3
  • typo in README.md

    typo in README.md

    I thing in the README.md the following line :

    $twig->addExtension(AnsiExtension($converter));
    

    should be corriged to :

    $twig->addExtension(new AnsiExtension($converter));
    

    AnsiExtension is a class and not a function

    opened by aerogus 1
  • How to preserve new lines

    How to preserve new lines

    My command prints a bunch of lines using writeln function, but the ansi-to-html converter does not make separate lines out of them. Is there a way to achieve this?

    opened by olia-bn 1
  • Create an ESM Browser ready build

    Create an ESM Browser ready build

    Hello,

    What do you think about using rollup to produce minified version of the library to have a browser-ready build? I do this following suggestions from https://www.pika.dev/search?q=ansi-to-html

    Thanks,

    opened by nestarz 1
  • How do I include this in my project?

    How do I include this in my project?

    Hi, I did a git clone of the project. How do I integrate it into my project? with the composer autoloader? I get 'Uncaught error: Class 'AnsiToHtmlConverter' not found when I run it.

    opened by TheDoubleD 1
  • Adds replacement check for character set sequences

    Adds replacement check for character set sequences

    There's special escape sequences (for VT100) that alter character sets. These don't get replaced, like the cursor movements do.

    Escape sequences such as:

    \e(B
    

    http://ascii-table.com/ansi-escape-sequences-vt-100.php

    You can replicate the issue with the use of the command tput sgr0.

    opened by jackbentley 1
  • TwigExtension.

    TwigExtension.

    For one of my project, I had to create a twig extension. Do you want a PR?

    <?php
    
    use SensioLabs\AnsiConverter\AnsiToHtmlConverter;
    
    class AnsiExtension extends \Twig_Extension
    {
        private $converter;
    
        public function __construct(AnsiToHtmlConverter $converter = null)
        {
            $this->converter = $converter ?: new AnsiToHtmlConverter();
        }
    
        public function getFilters()
        {
            return array(
                new \Twig_SimpleFilter('ansi_to_html', array($this, 'ansiToHtml'), array('is_safe' => array('html'))),
            );
        }
    
        public function ansiToHtml($string)
        {
            return $this->converter->convert($string);
        }
    
        public function getName()
        {
            return 'ansi';
        }
    }
    

    It would be nice to add a twig function ansi_css that will ouput the inline CSS. But to do that, we need AnsiToHtmlConverter::getTheme

    opened by lyrixx 1
  • Fix problem with incomplete end sequences

    Fix problem with incomplete end sequences

    Some terminals seem to not issue the complete end sequence '[0m' for returning to default color, but using a shorthand '[m', which can be fixed with a little tweak of the regular expression.

    opened by ntzrbtr 0
  • New 80's Hacker Theme

    New 80's Hacker Theme

    <?php
    
    /*
     * This file is part of ansi-to-html.
     *
     * (c) 2013 Fabien Potencier
     *
     * For the full copyright and license information, please view the LICENSE
     * file that was distributed with this source code.
     */
    
    namespace SensioLabs\AnsiConverter\Theme;
    
    /**
     * Hacker theme.
     *
     * @see http://ethanschoonover.com/solarized
     */
    class HackerTheme extends Theme
    {
        public function asArray()
        {
            return array(
                // normal
                'black' => '#000000',
                'red' => '#800000',
                'green' => '#008000',
                'yellow' => '#808000',
                'blue' => '#000080',
                'magenta' => '#800080',
                'cyan' => '#008080',
                'white' => '#808080',
    
                // bright
                'brblack' => '#606060',
                'brred' => '#FF0000',
                'brgreen' => '#00FF00',
                'bryellow' => '#FFFF00',
                'brblue' => '#0000FF',
                'brmagenta' => '#FF00FF',
                'brcyan' => '#00FFFF',
                'brwhite' => '#FFFFFF',
            );
        }
    }
    
    opened by fctr 0
  • Small bug in choosing intense colors

    Small bug in choosing intense colors

    Here's the fix:

            foreach ($options as $option) {
                if ($option >= 30 && $option < 38) {
                    $fg = $option - 30;
    
                } elseif ($option >= 40 && $option < 48) {
                    $bg = $option - 40;
                } elseif ($option >= 90 && $option < 98) { // This needs to be added
                    $fg = $option - 80; // This needs to be added
                } elseif (39 == $option) {
    

    ... }

    opened by fctr 0
  • fix when pattern like this 'foo\r\r\n', output will be empty

    fix when pattern like this 'foo\r\r\n', output will be empty

    We found some devices (H3C S10508-V) may output like this:

    blahblahblan \r\r\n
    blahblahblan \r\r\n
    

    However the history version may covert it into this:

    \r\n
    \r\n
    
    opened by friparia 0
  • Foreground color is set to background color if sequence lists background first

    Foreground color is set to background color if sequence lists background first

    I came across a weird behavior while using the library - if background color (e.g. 42 - green) is specified before foreground (e.g. 30 - black) the render will contain black text on black background. Weirdly enough this happens only for separated sequences (e.g. ^[[0m^[[42m^[[30m) and not while parsing their short forms (e.g. ^[[42;30m).

    I used following example to demonstrate the problem (also attached): Download raw

    ^[[30;42mWORKS1^[[0m
    ^[[0m^[[42m^[[30mDOESNT1^[[0m
    ^[[0m^[[30m^[[42mWORKS2^[[0m
    ^[[42;30mWORKS1^[[0m
    

    Rendering in GNU bash, version 4.3.30(1)-release (x86_64-pc-linux-gnu) bash-render

    HTML from ansi-to-html v1.1.3

    <?php
    $output = (new AnsiToHtmlConverter())->convert($test);
    
    <span style="background-color: green; color: black">WORKS1</span><span style="background-color: black; color: white"><br />
    </span><span style="background-color: black; color: black">DOESNT1</span><span style="background-color: black; color: white"><br />
    </span><span style="background-color: green; color: white">WORKS2</span><span style="background-color: black; color: white"><br />
    </span><span style="background-color: green; color: black">WORKS1</span><span style="background-color: black; color: white"><br />
    </span>
    
    opened by kiler129 2
  • Support CSS prefix being defined early

    Support CSS prefix being defined early

    The CSS prefix that is part of the theme takes precedence over the prefix supplied to the converter.

    Deprecates $prefix parameter from Theme::asCss()

    It would be cumbersome to support a dynamic prefix at this late stage of the rendering.

    Tests updated to cover the following combinations.

    1. Using the default theme or a supplied theme, with and without its own css prefix.
    2. Using the default css prefix or a supplied prefix.
    3. Using inline styling or CSS.

    Hopefully fixes https://github.com/sensiolabs/ansi-to-html/issues/12

    opened by rquadling 0
Owner
SensioLabs
SensioLabs
PHP Class converter to namepaces.

Namespacer This tool will assist you in taking older underscore/prefix spaced code and will namespace it as best as it can, and also make the files an

Ralph Schindler 59 Sep 9, 2021
Arbitrary number base converter.

Numbase Easily convert numbers between arbitrary bases and symbol sets. Installation This library is available on Packagist as thunderer/numbase. It r

Tomasz Kowalczyk 23 Sep 25, 2022
HTML to PDF converter for PHP

Dompdf Dompdf is an HTML to PDF converter At its heart, dompdf is (mostly) a CSS 2.1 compliant HTML layout and rendering engine written in PHP. It is

null 9.3k Jan 1, 2023
Laravel: Data to Monthly Converter

Laravel: Data to Monthly Converter Using this package you will be able to converts your collection using a timestamp field to order data monthly or ye

101INFOTECH 9 Nov 23, 2022
Unit converter and calculator for php

Unit converter and calculator This library uses the awesome lisachenko/z-engine to allow mathematical operations on objects, allowing to do stuff like

Dominik Chrástecký 8 Apr 8, 2022
UUID <=> ULID bidirectional converter

uuid-ulid-converter UUID <=> ULID bidirectional converter Installing composer require mpyw/uuid-ulid-converter API static string Converter::uuidToUli

mpyw 4 Mar 27, 2022
Google-like values converter

Google-like values converter. Support for different types of conversions, for examples: 1 kilometer -> meters 1 dollar -> THB 1 kilogram -> meters ...

Pavinthan 1 Nov 4, 2021
PHPUnit to Pest Converter

PestConverter PestConverter is a PHP library for converting PHPUnit tests to Pest tests. Before use Before using this converter, make sure your files

null 10 Nov 21, 2022
A full-featured home hosted Cloud Drive, Personal Assistant, App Launcher, File Converter, Streamer, Share Tool & More!

A Fully Featured home-hosted Cloud Storage platform and Personal Assistant that Converts files, OCR's images & documents, Creates archives, Scans for viruses, Protects your server, Keeps itself up-to-date, and Runs your own AppLauncher!

Justin Grimes 178 Dec 26, 2022
JavaScript to JQuery Converter

JQuery To Javascript Converter for helping to removing JQuery on websites.

Michael Parisi 13 Nov 21, 2022
The WordPress Categories to Tags Converter.

=== Categories to Tags Converter === Contributors: wordpressdotorg Donate link: Tags: importer, categories and tags converter Requires at least: 3.0

WordPress 3 Dec 6, 2022
An HTML5 parser and serializer for PHP.

HTML5-PHP HTML5 is a standards-compliant HTML5 parser and writer written entirely in PHP. It is stable and used in many production websites, and has w

null 1.2k Dec 31, 2022
PHP Template Attribute Language — template engine for XSS-proof well-formed XHTML and HTML5 pages

PHPTAL - Template Attribute Language for PHP Requirements If you want to use the builtin internationalisation system (I18N), the php-gettext extension

PHPTAL 175 Dec 13, 2022
Modelo de retorno de listagem com HTML5, PHP e Mysqli

Modelo_listagem Modelo de retorno de listagem com HTML5, PHP e Mysqli. Conexão ao banco de dados usando mysqli; Implementação de rodapé com totalizaçõ

null 4 Oct 14, 2021
WinterCMS plugin adding support for streaming html5 videos

Winter MediaStream Intro This plugin adds streaming support for html5 videos. Installation composer install jaxwilko/wn-mediastream-plugin Usage Once

Jack Wilkinson 4 Dec 20, 2022
This package extends Laravel's FormBuilder to include some (soon all) HTML5 elements

HTML5 Forms for Laravel This package extends Laravel's FormBuilder to include some (soon all) HTML5 elements. How to Install Install the braunson/lara

Braunson Yager 89 Jun 17, 2022
Composer package which adds support for HTML5 elements using Laravels Form interface (e.g. Form::date())

Laravel HTML 5 Inputs Composer package which adds support for HTML5 elements by extending Laravel's Form interface (e.g. Form::date()) Adds support fo

Small Dog Studios 11 Oct 13, 2020
A Magento 1.x module which facilitates automatic purging of static assets from HTTP caches such as browser cache, CDN, Varnish, etc using best practices outlined within the HTML5 boilerplate community.

Magento Cachebuster Cachebuster is a Magento module which facilitates automatic purging of static assets from HTTP caches such as browser cache, CDN,

Gordon Knoppe 129 Apr 1, 2022
HTML5 Twitter Bootstrap 3.1 Magento Boilerplate Template

Magento Boilerplate A HTML5 Twitter Bootstrap 3.1 Magento 1.8 Boilerplate Template Read the blog post or checkout the demo for more information. Insta

null 531 Dec 8, 2022
🧾 Online test site with the human sciences theme. Using: HTML5, CSS3, Js., PHP7 and MySQL. 🚀

form-ciencias-humanas ?? Technologies Lunacy HTML5 CSS3 PHP7 MYSQL Animate.css Illustrations from icons8: Earth care from Anna Antipina Earth and Moon

Vinícius 1 Jan 9, 2022