Skip to content

Commit fdde19d

Browse files
en0memawesomekling
authored andcommitted
Utilities: Add option to control when to use colored output for grep
Fixes #9351.
1 parent 0729610 commit fdde19d

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

Userland/Utilities/grep.cpp

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ int main(int argc, char** argv)
4747
BinaryFileMode binary_mode { BinaryFileMode::Binary };
4848
bool case_insensitive = false;
4949
bool invert_match = false;
50+
bool colored_output = isatty(STDOUT_FILENO);
5051

5152
Core::ArgsParser args_parser;
5253
args_parser.add_option(recursive, "Recursively scan files starting in working directory", "recursive", 'r');
@@ -90,6 +91,22 @@ int main(int argc, char** argv)
9091
return true;
9192
},
9293
});
94+
args_parser.add_option(Core::ArgsParser::Option {
95+
.requires_argument = true,
96+
.help_string = "When to use colored output for the matching text ([auto], never, always)",
97+
.long_name = "color",
98+
.short_name = 0,
99+
.value_name = "WHEN",
100+
.accept_value = [&](auto* str) {
101+
if ("never"sv == str)
102+
colored_output = false;
103+
else if ("always"sv == str)
104+
colored_output = true;
105+
else if ("auto"sv != str)
106+
return false;
107+
return true;
108+
},
109+
});
93110
args_parser.add_positional_argument(files, "File(s) to process", "file", Core::ArgsParser::Required::No);
94111
args_parser.parse(argc, argv);
95112

@@ -114,15 +131,13 @@ int main(int argc, char** argv)
114131
auto result = re.match(str, PosixFlags::Global);
115132
if (result.success ^ invert_match) {
116133
if (is_binary && binary_mode == BinaryFileMode::Binary) {
117-
outln("binary file \x1B[34m{}\x1B[0m matches", filename);
134+
outln(colored_output ? "binary file \x1B[34m{}\x1B[0m matches" : "binary file {} matches", filename);
118135
} else {
119-
if ((result.matches.size() || invert_match) && print_filename) {
120-
out("\x1B[34m{}:\x1B[0m", filename);
121-
}
136+
if ((result.matches.size() || invert_match) && print_filename)
137+
out(colored_output ? "\x1B[34m{}:\x1B[0m" : "{}:", filename);
122138

123139
for (auto& match : result.matches) {
124-
125-
out("{}\x1B[32m{}\x1B[0m",
140+
out(colored_output ? "{}\x1B[32m{}\x1B[0m" : "{}{}",
126141
StringView(&str[last_printed_char_pos], match.global_offset - last_printed_char_pos),
127142
match.view.to_string());
128143
last_printed_char_pos = match.global_offset + match.view.length();

0 commit comments

Comments
 (0)