Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exclude escape sequences about cursor and screen from text #2

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 28 additions & 0 deletions lib/HTML/FromANSI/Tiny.pm
Expand Up @@ -185,6 +185,9 @@ In scalar context returns a single string of concatenated HTML.

sub html {
my ($self, $text) = @_;

$text = $self->_exclude_cursor_escape_sequences($text);

$text = $self->ansi_parser->parse($text)
unless ref($text) eq 'ARRAY';

Expand Down Expand Up @@ -213,6 +216,31 @@ sub html {
return wantarray ? @html : join('', @html);
}

sub _exclude_cursor_escape_sequences {
my ($self, $text) = @_;

$text =~ s/\e\[2j//gi; # 2J: clear screen

# 0K: clear row to the right end from current cursor position
# 1K: clear row to the left end from current cursor position
# 2K: clear row
for my $type (0..2) {
$text =~ s/\e\[${type}k//gi;
}

$text =~ s/\e\[\d+?;\d+?h//gi; # %d;%dH: move cursor by lengthwise and crosswise

# %dA: move cursor to above
# %dB: move cursor to below
# %dC: move cursor to right
# %dD: move cursor to left
for my $direction ('a'..'d') {
$text =~ s/\e\[\d+?${direction}//gi;
}

return $text;
}

=method html_encode

my $html = $hfat->html_encode($text);
Expand Down
20 changes: 20 additions & 0 deletions t/html.t
Expand Up @@ -49,4 +49,24 @@ eq_or_diff
q[hey <span class="t_on_white t_black">LOOK AT THIS</span>],
'with auto_reverse get default colors';

eq_or_diff
scalar $h->html("\e[2j\e[2Jfoo"),
q[foo],
'with escape sequence to clear screen';

eq_or_diff
scalar $h->html("\e[0k\e[0K\e[1k\e[1K\e[2k\e[2Kfoo"),
q[foo],
'with escape sequence to clear row';

eq_or_diff
scalar $h->html("\e[1;2h\e[10;20Hfoo"),
q[foo],
'with escape sequence to move cursor by lengthwise and crosswise';

eq_or_diff
scalar $h->html("\e[10a\e[10A\e[10b\e[10B\e[10c\e[10C\e[10d\e[10Dfoo"),
q[foo],
'with escape sequence to move cursor';

done_testing;