diff --git a/src/formatter.cr b/src/formatter.cr index b9f8381..3203078 100644 --- a/src/formatter.cr +++ b/src/formatter.cr @@ -12,7 +12,11 @@ module Tartrazine property theme : Theme = Tartrazine.theme("default-dark") # Format the text using the given lexer. - def format(text : String, lexer : Lexer, io : IO? = nil) : String? + def format(text : String, lexer : Lexer, io : IO = nil) : Nil + raise Exception.new("Not implemented") + end + + def format(text : String, lexer : Lexer) : String raise Exception.new("Not implemented") end diff --git a/src/formatters/ansi.cr b/src/formatters/ansi.cr index 19d72f3..8efeb25 100644 --- a/src/formatters/ansi.cr +++ b/src/formatters/ansi.cr @@ -11,8 +11,13 @@ module Tartrazine "#{i + 1}".rjust(4).ljust(5) end - def format(text : String, lexer : Lexer, io : IO? = nil) : String? - outp = io.nil? ? String::Builder.new("") : io + def format(text : String, lexer : Lexer) : String + outp = String::Builder.new("") + format(text, lexer, outp) + return outp.to_s + end + + def format(text : String, lexer : Lexer, outp : IO) : Nil tokenizer = Tokenizer.new(lexer, text) i = 0 outp << line_label(i) if line_numbers? @@ -23,7 +28,6 @@ module Tartrazine outp << line_label(i) if line_numbers? end end - return outp.to_s if io.nil? end def colorize(text : String, token : String) : String diff --git a/src/formatters/html.cr b/src/formatters/html.cr index 3938820..4217cdd 100644 --- a/src/formatters/html.cr +++ b/src/formatters/html.cr @@ -34,13 +34,18 @@ module Tartrazine @weight_of_bold : Int32 = 600) end - def format(text : String, lexer : Lexer, io : IO? = nil) : String? - outp = io.nil? ? String::Builder.new("") : io + def format(text : String, lexer : Lexer) : String + outp = String::Builder.new("") + format(text, lexer, outp) + return outp.to_s + end + + + def format(text : String, lexer : Lexer, io : IO) : Nil pre, post = wrap_standalone - outp << pre if standalone? - format_text(text, lexer, outp) - outp << post if standalone? - return outp.to_s if io.nil? + io << pre if standalone? + format_text(text, lexer, io) + io << post if standalone? end # Wrap text into a full HTML document, including the CSS for the theme diff --git a/src/formatters/json.cr b/src/formatters/json.cr index 39271c8..c9d6a39 100644 --- a/src/formatters/json.cr +++ b/src/formatters/json.cr @@ -4,11 +4,16 @@ module Tartrazine class Json < Formatter property name = "json" - def format(text : String, lexer : Lexer, io : IO? = nil) : String? - outp = io.nil? ? String::Builder.new("") : io + def format(text : String, lexer : Lexer) : String + outp = String::Builder.new("") + format(text, lexer, outp) + return outp.to_s + end + + + def format(text : String, lexer : Lexer, io : IO) : Nil tokenizer = Tokenizer.new(lexer, text) - outp << Tartrazine::Lexer.collapse_tokens(tokenizer.to_a).to_json - return outp.to_s if io.nil? + io << Tartrazine::Lexer.collapse_tokens(tokenizer.to_a).to_json end end end