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

fix crash in terminal256 formatter with escaped tokens #1402

Merged
merged 2 commits into from
Jan 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions lib/rouge/formatters/terminal256.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ def initialize(theme = Themes::ThankfulEyes.new)

def stream(tokens, &b)
tokens.each do |tok, val|
escape = escape_sequence(tok)
yield escape.style_string
yield val.gsub("\n", "#{escape.reset_string}\n#{escape.style_string}")
yield escape.reset_string
escape_sequence(tok).stream_value(val, &b)
end
end

Expand Down Expand Up @@ -85,6 +82,14 @@ def bg
@bg = style.bg && self.class.color_index(style.bg)
end


def stream_value(val, &b)
yield style_string
yield val.gsub("\n", "#{reset_string}\n#{style_string}")
.gsub("\e", "\\e")
pyrmont marked this conversation as resolved.
Show resolved Hide resolved
yield reset_string
end

def style_string
@style_string ||= begin
attrs = []
Expand Down Expand Up @@ -157,9 +162,16 @@ def self.closest_color(r, g, b)
end
end

class Unescape < EscapeSequence
def initialize(*) end
def style_string(*) '' end
def reset_string(*) '' end
def stream_value(val) yield val end
end

# private
def escape_sequence(token)
return '' if escape?(token)
return Unescape.new if escape?(token)
@escape_sequences ||= {}
@escape_sequences[token.qualname] ||=
EscapeSequence.new(get_style(token))
Expand Down
26 changes: 26 additions & 0 deletions spec/lexers/escape_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
describe Rouge::Lexers::Escape do
let(:lexer) { Rouge::Lexers::Escape.new(lang: 'json') }
let(:text) { '{ "foo": <!<bar>!> }' }
let(:result) {
Rouge::Formatter.with_escape do
formatter.format(lexer.lex(text))
end
}

describe 'html' do
let(:formatter) { Rouge::Formatters::HTML.new }

it 'unescapes' do
assert { result =~ /<bar>/ }
end
end

describe 'terminal256' do
let(:formatter) { Rouge::Formatters::Terminal256.new }
let(:text) { %({ "foo": <!\e123!> }) }

it 'unescapes' do
assert { result =~ /\e123/ }
end
end
end