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

Add Colorize::Object#ansi_escape #15113

Merged
merged 5 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
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.print.should eq("\e[1m")
Colorize.with.bright.print.should eq("\e[1m")
Colorize.with.dim.print.should eq("\e[2m")
Colorize.with.italic.print.should eq("\e[3m")
Colorize.with.underline.print.should eq("\e[4m")
Colorize.with.blink.print.should eq("\e[5m")
Colorize.with.blink_fast.print.should eq("\e[6m")
Colorize.with.reverse.print.should eq("\e[7m")
Colorize.with.hidden.print.should eq("\e[8m")
Colorize.with.strikethrough.print.should eq("\e[9m")
Colorize.with.double_underline.print.should eq("\e[21m")
Colorize.with.overline.print.should eq("\e[53m")
end

it "only prints colorize ANSI escape codes" do
colorize("hello").red.bold.print.should eq("\e[31;1m")
colorize("hello").bold.dim.underline.blink.reverse.hidden.print.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.print # => "\e[31m"
# "hello world".green.bold.print # => "\e[32;1m"
# ```
def print : String
String.build do |io|
print io
end
end

# Same as `print` but writes to a given *io*.
def print(io : IO) : Nil
self.class.print(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.print(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
Loading