@@ -47,6 +47,7 @@ int main(int argc, char** argv)
47
47
BinaryFileMode binary_mode { BinaryFileMode::Binary };
48
48
bool case_insensitive = false ;
49
49
bool invert_match = false ;
50
+ bool colored_output = isatty (STDOUT_FILENO);
50
51
51
52
Core::ArgsParser args_parser;
52
53
args_parser.add_option (recursive, " Recursively scan files starting in working directory" , " recursive" , ' r' );
@@ -90,6 +91,22 @@ int main(int argc, char** argv)
90
91
return true ;
91
92
},
92
93
});
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
+ });
93
110
args_parser.add_positional_argument (files, " File(s) to process" , " file" , Core::ArgsParser::Required::No);
94
111
args_parser.parse (argc, argv);
95
112
@@ -114,15 +131,13 @@ int main(int argc, char** argv)
114
131
auto result = re.match (str, PosixFlags::Global);
115
132
if (result.success ^ invert_match) {
116
133
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);
118
135
} 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);
122
138
123
139
for (auto & match : result.matches ) {
124
-
125
- out (" {}\x1B [32m{}\x1B [0m" ,
140
+ out (colored_output ? " {}\x1B [32m{}\x1B [0m" : " {}{}" ,
126
141
StringView (&str[last_printed_char_pos], match.global_offset - last_printed_char_pos),
127
142
match.view .to_string ());
128
143
last_printed_char_pos = match.global_offset + match.view .length ();
0 commit comments