Skip to content

Commit

Permalink
Add Colorize::Object#ansi_escape (#15113)
Browse files Browse the repository at this point in the history
Co-authored-by: Johannes Müller <straightshoota@gmail.com>
  • Loading branch information
devnote-dev and straight-shoota authored Dec 18, 2024
1 parent 4f00889 commit 7629863
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
20 changes: 20 additions & 0 deletions spec/std/colorize_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,26 @@ describe "colorize" do
colorize("hello").overline.to_s.should eq("\e[53mhello\e[0m")
end

it "prints colorize ANSI escape codes" do
Colorize.with.bold.ansi_escape.should eq("\e[1m")
Colorize.with.bright.ansi_escape.should eq("\e[1m")
Colorize.with.dim.ansi_escape.should eq("\e[2m")
Colorize.with.italic.ansi_escape.should eq("\e[3m")
Colorize.with.underline.ansi_escape.should eq("\e[4m")
Colorize.with.blink.ansi_escape.should eq("\e[5m")
Colorize.with.blink_fast.ansi_escape.should eq("\e[6m")
Colorize.with.reverse.ansi_escape.should eq("\e[7m")
Colorize.with.hidden.ansi_escape.should eq("\e[8m")
Colorize.with.strikethrough.ansi_escape.should eq("\e[9m")
Colorize.with.double_underline.ansi_escape.should eq("\e[21m")
Colorize.with.overline.ansi_escape.should eq("\e[53m")
end

it "only prints colorize ANSI escape codes" do
colorize("hello").red.bold.ansi_escape.should eq("\e[31;1m")
colorize("hello").bold.dim.underline.blink.reverse.hidden.ansi_escape.should eq("\e[1;2;4;5;7;8m")
end

it "colorizes mode combination" do
colorize("hello").bold.dim.underline.blink.reverse.hidden.to_s.should eq("\e[1;2;4;5;7;8mhello\e[0m")
end
Expand Down
26 changes: 26 additions & 0 deletions src/colorize.cr
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,26 @@ struct Colorize::Object(T)
end
end

# Prints the ANSI escape codes for an object. Note that this has no effect on a `Colorize::Object` with content,
# only the escape codes.
#
# ```
# require "colorize"
#
# Colorize.with.red.ansi_escape # => "\e[31m"
# "hello world".green.bold.ansi_escape # => "\e[32;1m"
# ```
def ansi_escape : String
String.build do |io|
ansi_escape io
end
end

# Same as `ansi_escape` but writes to a given *io*.
def ansi_escape(io : IO) : Nil
self.class.ansi_escape(io, to_named_tuple)
end

private def to_named_tuple
{
fore: @fore,
Expand All @@ -474,6 +494,12 @@ struct Colorize::Object(T)
mode: Mode::None,
}

protected def self.ansi_escape(io : IO, color : {fore: Color, back: Color, mode: Mode}) : Nil
last_color = @@last_color
append_start(io, color)
@@last_color = last_color
end

protected def self.surround(io, color, &)
last_color = @@last_color
must_append_end = append_start(io, color)
Expand Down

0 comments on commit 7629863

Please sign in to comment.