Skip to content

Commit

Permalink
feat: support NO_COLOR environment variable
Browse files Browse the repository at this point in the history
Support supression of terminal colors with the presence of a non-empty
string NO_COLOR env variable.

See #7 and https://no-color.org/
  • Loading branch information
natecraddock committed Jul 2, 2022
1 parent 7c6b0a6 commit 541052a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,12 @@ pub fn main() anyerror!void {
}
} else {
const prompt_str = std.process.getEnvVarOwned(allocator, "ZF_PROMPT") catch "> ";
const no_color = if (std.process.getEnvVarOwned(allocator, "NO_COLOR")) |value| blk: {
break :blk value.len > 0;
}
else |_| false;

var terminal = try ui.Terminal.init(@minimum(candidates.len, config.lines));
var terminal = try ui.Terminal.init(@minimum(candidates.len, config.lines), no_color);
var selected = try ui.run(allocator, &terminal, candidates, config.keep_order, prompt_str);
try ui.cleanUp(&terminal);
terminal.deinit();
Expand Down
7 changes: 5 additions & 2 deletions src/ui.zig
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ pub const Terminal = struct {
height: usize = undefined,
max_height: usize,

pub fn init(max_height: usize) !Terminal {
no_color: bool,

pub fn init(max_height: usize, no_color: bool) !Terminal {
var tty = try std.fs.openFileAbsolute("/dev/tty", .{ .read = true, .write = true });

// store original terminal settings to restore later
Expand All @@ -44,6 +46,7 @@ pub const Terminal = struct {
.termios = termios,
.raw_termios = raw_termios,
.max_height = max_height,
.no_color = no_color,
};
}

Expand Down Expand Up @@ -264,7 +267,7 @@ inline fn drawCandidate(terminal: *Terminal, candidate: Candidate, width: usize,
const str = candidate.str[0..std.math.min(width, candidate.str.len)];

// no highlights, just draw the string
if (candidate.ranges == null) {
if (candidate.ranges == null or terminal.no_color) {
_ = terminal.writer.write(str) catch unreachable;
} else {
var slicer = Slicer.init(str, candidate.ranges.?);
Expand Down

0 comments on commit 541052a

Please sign in to comment.