Skip to content

Commit

Permalink
added initial code
Browse files Browse the repository at this point in the history
  • Loading branch information
fabpot committed Mar 19, 2013
0 parents commit ab21fe6
Show file tree
Hide file tree
Showing 10 changed files with 461 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
composer.lock
/vendor/
19 changes: 19 additions & 0 deletions LICENSE
@@ -0,0 +1,19 @@
Copyright (c) 2013 Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
69 changes: 69 additions & 0 deletions README.md
@@ -0,0 +1,69 @@
ANSI to HTML5 Converter
=======================

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

```php
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+php
<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:

```php
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:

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

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

```php
$styles = $theme->asCss();
```

which you can then use in your HTML document:

```html+php
<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>
```
143 changes: 143 additions & 0 deletions SensioLabs/AnsiConverter/AnsiToHtmlConverter.php
@@ -0,0 +1,143 @@
<?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;

use SensioLabs\AnsiConverter\Theme\Theme;

/**
* Converts an ANSI text to HTML5.
*/
class AnsiToHtmlConverter
{
protected $theme;
protected $charset;
protected $inlineStyles;
protected $inlineColors;
protected $colorNames;

public function __construct(Theme $theme = null, $inlineStyles = true, $charset = 'UTF-8')
{
$this->theme = null === $theme ? new Theme() : $theme;
$this->inlineStyles = $inlineStyles;
$this->charset = $charset;
$this->inlineColors = $this->theme->asArray();
$this->colorNames = array(
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white',
'', '',
'brblack', 'brred', 'brgreen', 'bryellow', 'brblue', 'brmagenta', 'brcyan', 'brwhite',
);
}

public function convert($text)
{
// remove cursor movement sequences
$text = preg_replace('#\e\[(K|s|u|2J|2K|\d+(A|B|C|D|E|F|G|J|K|S|T)|\d+;\d+(H|f))#', '', $text);
$text = htmlspecialchars($text, ENT_QUOTES, $this->charset);

$tokens = $this->tokenize($text);

// a backspace remove the previous character but only from a text token
foreach ($tokens as $i => $token) {
if ('backspace' == $token[0]) {
$j = $i;
while (--$j >= 0) {
if ('text' == $tokens[$j][0] && strlen($tokens[$j][1]) > 0) {
$tokens[$j][1] = substr($tokens[$j][1], 0, -1);

break;
}
}
}
}

$html = '';
foreach ($tokens as $token) {
if ('text' == $token[0]) {
$html .= $token[1];
} elseif ('color' == $token[0]) {
$html .= $this->convertAnsiToColor($token[1]);
}
}

if ($this->inlineStyles) {
$html = sprintf('<span style="background-color: %s; color: %s">%s</span>', $this->inlineColors['black'], $this->inlineColors['white'], $html);
} else {
$html = sprintf('<span class="ansi_color_fg_black ansi_color_bg_white">%s</span>', $html);
}

// remove empty span
$html = preg_replace('#<span[^>]*></span>#', '', $html);

return $html;
}

protected function convertAnsiToColor($ansi)
{
$bg = 0;
$fg = 7;
if ('0' != $ansi) {
$options = explode(';', $ansi);

foreach ($options as $option) {
if ($option >= 30 && $option < 38) {
$fg = $option - 30;
} elseif ($option >= 40 && $option < 48) {
$bg = $option - 40;
} elseif (39 == $option) {
$fg = 7;
} elseif (49 == $option) {
$bg = 0;
}
}

// options: bold => 1, underscore => 4, blink => 5, reverse => 7, conceal => 8
if (in_array(1, $options)) {
$fg += 8;
$bg += 8;
}

if (in_array(4, $options)) {
$text = sprintf('<u>%s</u>', $text);

This comment has been minimized.

Copy link
@pborreli

pborreli Mar 26, 2013

probably a wrong copy/paste $text is undefined and then unused

}

if (in_array(7, $options)) {
$tmp = $fg; $fg = $bg; $bg = $tmp;
}
}

if ($this->inlineStyles) {
return sprintf('</span><span style="background-color: %s; color: %s">', $this->inlineColors[$this->colorNames[$bg]], $this->inlineColors[$this->colorNames[$fg]]);
} else {
return sprintf('</span><span class="ansi_color_bg_%s ansi_color_fg_%s">', $this->colorNames[$bg], $this->colorNames[$fg]);
}
}

protected function tokenize($text)
{
$tokens = array();
preg_match_all("/(?:\e\[(.+?)m|(\x08))/", $text, $matches, PREG_OFFSET_CAPTURE);

$offset = 0;
foreach ($matches[0] as $i => $match) {
if ($match[1] - $offset > 0) {
$tokens[] = array('text', substr($text, $offset, $match[1] - $offset));
}
$tokens[] = array("\x08" == $match[0] ? 'backspace' : 'color', $matches[1][$i][0]);
$offset = $match[1] + strlen($match[0]);
}
if ($offset < strlen($text)) {
$tokens[] = array('text', substr($text, $offset));
}

return $tokens;
}
}
44 changes: 44 additions & 0 deletions SensioLabs/AnsiConverter/Tests/AnsiToHtmlConverterTest.php
@@ -0,0 +1,44 @@
<?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\Tests;

use SensioLabs\AnsiConverter\AnsiToHtmlConverter;

class AnsiToHtmlConverterTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider getConvertData
*/
public function testConvert($expected, $input)
{
$converter = new AnsiToHtmlConverter();
$this->assertEquals($expected, $converter->convert($input));
}

public function getConvertData()
{
return array(
// text is escaped
array('<span style="background-color: black; color: white">foo &lt;br /&gt;</span>', 'foo <br />'),

// newlines are preserved
array("<span style=\"background-color: black; color: white\">foo\nbar</span>", "foo\nbar"),

// backspaces
array("<span style=\"background-color: black; color: white\">foo </span>", "foobar\x08\x08\x08 "),
array("<span style=\"background-color: black; color: white\">foo</span><span style=\"background-color: black; color: white\"> </span>", "foob\e[31;41ma\e[0mr\x08\x08\x08 "),

// color
array("<span style=\"background-color: red; color: red\">foo</span>", "\e[31;41mfoo\e[0m"),
);
}
}
45 changes: 45 additions & 0 deletions SensioLabs/AnsiConverter/Theme/SolarizedTheme.php
@@ -0,0 +1,45 @@
<?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;

/**
* Solarized theme.
*
* @see http://ethanschoonover.com/solarized
*/
class SolarizedTheme extends Theme
{
public function asArray()
{
return array(
// normal
'black' => '#073642',
'red' => '#dc322f',
'green' => '#859900',
'yellow' => '#b58900',
'blue' => '#268bd2',
'magenta' => '#d33682',
'cyan' => '#2aa198',
'white' => '#eee8d5',

// bright
'brblack' => '#002b36',
'brred' => '#cb4b16',
'brgreen' => '#586e75',
'bryellow' => '#657b83',
'brblue' => '#839496',
'brmagenta' => '#6c71c4',
'brcyan' => '#93a1a1',
'brwhite' => '#fdf6e3',
);
}
}
45 changes: 45 additions & 0 deletions SensioLabs/AnsiConverter/Theme/SolarizedXTermTheme.php
@@ -0,0 +1,45 @@
<?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;

/**
* Solarized XTerm theme.
*
* @see http://ethanschoonover.com/solarized
*/
class SolarizedXTermTheme extends Theme
{
public function asArray()
{
return array(
// normal
'black' => '#262626',
'red' => '#d70000',
'green' => '#5f8700',
'yellow' => '#af8700',
'blue' => '#0087ff',
'magenta' => '#af005f',
'cyan' => '#00afaf',
'white' => '#e4e4e4',

// bright
'brblack' => '#1c1c1c',
'brred' => '#d75f00',
'brgreen' => '#585858',
'bryellow' => '#626262',
'brblue' => '#808080',
'brmagenta' => '#5f5faf',
'brcyan' => '#8a8a8a',
'brwhite' => '#ffffd7',
);
}
}

0 comments on commit ab21fe6

Please sign in to comment.