3 * selector is a simple shell command for selection of strings with a
4 * dynamic pattern-matching.
6 * Copyright (c) 2009 Francois Fleuret
7 * Written by Francois Fleuret <francois@fleuret.org>
9 * This file is part of selector.
11 * selector is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 3 as
13 * published by the Free Software Foundation.
15 * selector is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with selector. If not, see <http://www.gnu.org/licenses/>.
25 // To use it as a super-history-search for bash:
26 // alias h='selector -d -i -b -v -f <(history)'
36 #include <sys/ioctl.h>
44 const int buffer_size = 4096;
46 // Yeah, global variables!
48 int nb_lines_max = 1000;
49 char pattern_separator = ';';
50 int output_to_vt_buffer = 0;
52 int zsh_history = 0, bash_history = 0;
53 int inverse_order = 0;
54 int remove_duplicates = 0;
56 int case_sensitive = 0;
58 //////////////////////////////////////////////////////////////////////
60 void inject_into_tty_buffer(char *string) {
61 struct termios oldtio, newtio;
62 tcgetattr(STDIN_FILENO, &oldtio);
63 memset(&newtio, 0, sizeof(newtio));
64 // Set input mode (non-canonical, *no echo*,...)
65 tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
66 // Put the selected string in the tty input buffer
67 for(char *k = string; *k; k++) {
68 ioctl(STDIN_FILENO, TIOCSTI, k);
70 // Restore the old settings
71 tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
74 //////////////////////////////////////////////////////////////////////
76 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
77 if(n_opt + n >= argc) {
78 cerr << "Missing argument for " << argv[n_opt] << "."
80 << "Expecting " << help << "."
86 //////////////////////////////////////////////////////////////////////
87 // A quick and dirty hash table
89 int *new_hash_table(int hash_table_size) {
91 result = new int[hash_table_size];
92 for(int k = 0; k < hash_table_size; k++) {
98 int test_and_add(char *new_string, int new_index,
99 char **strings, int *hash_table, int hash_table_size) {
100 unsigned int code = 0;
102 // This is my recipe. I checked, it seems to work (as long as
103 // hash_table_size is not a multiple of 387433 that should be okay)
105 for(int k = 0; new_string[k]; k++) {
106 code = code * 387433 + (unsigned int) (new_string[k]);
109 code = code % hash_table_size;
111 while(hash_table[code] >= 0) {
112 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
113 int result = hash_table[code];
114 hash_table[code] = new_index;
117 code = (code + 1) % hash_table_size;
120 hash_table[code] = new_index;
125 //////////////////////////////////////////////////////////////////////
126 // A matcher matches either with a collection of substrings, or with a
134 char *splitted_patterns, **patterns;
137 int match(char *string, matcher_t *matcher) {
138 if(matcher->nb_patterns >= 0) {
139 if(matcher->case_sensitive) {
140 for(int n = 0; n < matcher->nb_patterns; n++) {
141 if(strstr(string, matcher->patterns[n]) == 0) return 0;
144 for(int n = 0; n < matcher->nb_patterns; n++) {
145 if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
150 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
154 void free_matcher(matcher_t *matcher) {
155 if(matcher->nb_patterns >= 0) {
156 delete[] matcher->splitted_patterns;
157 delete[] matcher->patterns;
159 if(!matcher->regexp_error) regfree(&matcher->preg);
163 void initialize_matcher(int use_regexp, int case_sensitive, matcher_t *matcher, const char *pattern) {
165 matcher->nb_patterns = -1;
166 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
168 matcher->regexp_error = 0;
169 matcher->nb_patterns = 1;
170 matcher->case_sensitive = case_sensitive;
172 for(const char *s = pattern; *s; s++) {
173 if(*s == pattern_separator) {
174 matcher->nb_patterns++;
178 matcher->splitted_patterns = new char[strlen(pattern) + 1];
179 matcher->patterns = new char*[matcher->nb_patterns];
181 strcpy(matcher->splitted_patterns, pattern);
184 char *last_pattern_start = matcher->splitted_patterns;
185 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
186 if(*s == pattern_separator || *s == '\0') {
188 matcher->patterns[n++] = last_pattern_start;
189 last_pattern_start = s + 1;
195 //////////////////////////////////////////////////////////////////////
197 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
198 int line = current_line - 1;
199 while(line >= 0 && !match(lines[line], matcher)) line--;
203 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
204 int line = current_line + 1;
205 while(line < nb_lines && !match(lines[line], matcher)) line++;
213 //////////////////////////////////////////////////////////////////////
215 void update_screen(int *current_line, int *temporary_line, int motion,
216 int nb_lines, char **lines,
219 char buffer[buffer_size];
222 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
224 // We now take care of printing the lines per se
226 int console_width = getmaxx(stdscr);
227 int console_height = getmaxy(stdscr);
229 // First, we find a visible line. In priority: The current, or the
230 // first visible after it, or the first visible before it.
232 int nb_printed_lines = 0;
235 use_default_colors();
238 if(matcher.regexp_error) {
239 addstr("[regexp error]");
240 } else if(nb_lines > 0) {
242 if(match(lines[*current_line], &matcher)) {
243 new_line = *current_line;
245 new_line = next_visible(*current_line, nb_lines, lines, &matcher);
247 new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
251 // If we found a visible line and we should move, let's move
253 if(new_line >= 0 && motion != 0) {
256 // We want to go down, let's find the first visible line below
257 for(int m = 0; l >= 0 && m < motion; m++) {
258 l = next_visible(l, nb_lines, lines, &matcher);
264 // We want to go up, let's find the first visible line above
265 for(int m = 0; l >= 0 && m < -motion; m++) {
266 l = previous_visible(l, nb_lines, lines, &matcher);
274 // Here new_line is either a line number matching the patterns, or -1
278 int first_line = new_line, last_line = new_line, nb_match = 1;
280 // We find the first and last line to show, so that the total of
281 // visible lines between them (them include) is console_height - 1
283 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
287 while(first_line > 0 && !match(lines[first_line], &matcher)) {
290 if(match(lines[first_line], &matcher)) {
295 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
297 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
301 if(match(lines[last_line], &matcher)) {
307 // Now we display them
309 for(int l = first_line; l <= last_line; l++) {
310 if(match(lines[l], &matcher)) {
313 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
314 buffer[k] = lines[l][k];
318 // We fill the rest of the line with blanks if either we did
319 // not clear() or if this is the highlighted line
322 while(k < console_width) {
330 // Highlight the highlighted line ...
334 attron(COLOR_PAIR(2));
335 addnstr(buffer, console_width);
336 attroff(COLOR_PAIR(2));
339 addnstr(buffer, console_width);
343 addnstr(buffer, console_width);
351 *current_line = new_line;
355 *temporary_line = new_line;
357 if(nb_printed_lines == 0) {
358 addnstr("[no selection]\n", console_width);
361 addnstr("[empty choice]\n", console_width);
366 sprintf(buffer, "%d/%d pattern: %s%s",
370 use_regexp ? " [regexp]" : "");
372 for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
373 buffer[console_width] = '\0';
377 attron(COLOR_PAIR(1));
378 addnstr(buffer, console_width);
379 attroff(COLOR_PAIR(1));
382 addnstr(buffer, console_width);
389 free_matcher(&matcher);
392 //////////////////////////////////////////////////////////////////////
394 int main(int argc, char **argv) {
396 if(!ttyname(STDIN_FILENO)) {
397 cerr << "The standard input is not a tty." << endl;
401 char buffer[buffer_size], raw_line[buffer_size];;
402 int color_fg_modeline, color_bg_modeline;
403 int color_fg_highlight, color_bg_highlight;
405 color_fg_modeline = COLOR_WHITE;
406 color_bg_modeline = COLOR_BLACK;
407 color_fg_highlight = COLOR_BLACK;
408 color_bg_highlight = COLOR_YELLOW;
410 setlocale(LC_ALL, "");
412 char input_filename[buffer_size], output_filename[buffer_size];
414 strcpy(input_filename, "");
415 strcpy(output_filename, "");
418 int error = 0, show_help = 0;
420 while(!error && !show_help && i < argc) {
422 if(strcmp(argv[i], "-o") == 0) {
423 check_opt(argc, argv, i, 1, "<output filename>");
424 strncpy(output_filename, argv[i+1], buffer_size);
428 else if(strcmp(argv[i], "-s") == 0) {
429 check_opt(argc, argv, i, 1, "<pattern separator>");
430 pattern_separator = argv[i+1][0];
434 else if(strcmp(argv[i], "-v") == 0) {
435 output_to_vt_buffer = 1;
439 else if(strcmp(argv[i], "-m") == 0) {
444 else if(strcmp(argv[i], "-f") == 0) {
445 check_opt(argc, argv, i, 1, "<input filename>");
446 strncpy(input_filename, argv[i+1], buffer_size);
450 else if(strcmp(argv[i], "-i") == 0) {
455 else if(strcmp(argv[i], "-b") == 0) {
460 else if(strcmp(argv[i], "-z") == 0) {
465 else if(strcmp(argv[i], "-d") == 0) {
466 remove_duplicates = 1;
470 else if(strcmp(argv[i], "-e") == 0) {
475 else if(strcmp(argv[i], "-a") == 0) {
480 else if(strcmp(argv[i], "-l") == 0) {
481 check_opt(argc, argv, i, 1, "<maximum number of lines>");
482 nb_lines_max = atoi(argv[i+1]);
486 else if(strcmp(argv[i], "-c") == 0) {
487 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
488 color_fg_modeline = atoi(argv[i+1]);
489 color_bg_modeline = atoi(argv[i+2]);
490 color_fg_highlight = atoi(argv[i+3]);
491 color_bg_highlight = atoi(argv[i+4]);
495 else if(strcmp(argv[i], "-h") == 0) {
501 cerr << "Unknown argument " << argv[i] << "." << endl;
506 if(show_help || error) {
507 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
509 << "Written by Francois Fleuret <francois@fleuret.org>."
512 << "Usage: " << argv[0] << " [options] -f <file>" << endl
514 << " -h show this help" << endl
515 << " -v inject the selected line in the tty" << endl
516 << " -d remove duplicated lines" << endl
517 << " -b remove the bash history line prefix" << endl
518 << " -z remove the zsh history line prefix" << endl
519 << " -i invert the order of lines" << endl
520 << " -e start in regexp mode" << endl
521 << " -a case sensitive" << endl
522 << " -m monochrome mode" << endl
523 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
524 << " set the display colors" << endl
525 << " -o <output filename>" << endl
526 << " set a file to write the selected line to" << endl
527 << " -s <pattern separator>" << endl
528 << " set the symbol to separate substrings in the pattern" << endl
529 << " -l <max number of lines>" << endl
530 << " set the maximum number of lines to take into account" << endl
536 char **lines = new char *[nb_lines_max];
538 if(!input_filename[0]) {
539 cerr << "You must specify a input file with -f." << endl;
545 ifstream file(input_filename);
548 cerr << "Can not open " << input_filename << endl;
552 int hash_table_size = nb_lines_max * 10;
555 if(remove_duplicates) {
556 hash_table = new_hash_table(hash_table_size);
559 while(nb_lines < nb_lines_max && !file.eof()) {
561 file.getline(raw_line, buffer_size);
566 cerr << "Line too long:" << endl;
567 cerr << raw_line << endl;
578 while(*u) { *s++ = *u++; }
584 if(zsh_history && *s == ':') {
585 while(*s && *s != ';') s++;
589 if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
590 while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
596 dup = test_and_add(s, nb_lines, lines, hash_table, hash_table_size);
602 lines[nb_lines] = new char[strlen(s) + 1];
603 strcpy(lines[nb_lines], s);
605 // We do not allocate a new string but use the pointer to the
606 // first occurence of it
607 lines[nb_lines] = lines[dup];
617 // Now remove the null strings
620 for(int k = 0; k < nb_lines; k++) {
622 lines[n++] = lines[k];
628 for(int i = 0; i < nb_lines/2; i++) {
629 char *s = lines[nb_lines - 1 - i];
630 lines[nb_lines - 1 - i] = lines[i];
635 char pattern[buffer_size];
640 //////////////////////////////////////////////////////////////////////
641 // Here we start to display with curse
650 // So that the arrow keys work
651 keypad(stdscr, TRUE);
656 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
657 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
658 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
659 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
663 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
666 init_pair(1, color_fg_modeline, color_bg_modeline);
667 init_pair(2, color_fg_highlight, color_bg_highlight);
674 int current_line = 0, temporary_line = 0;
676 update_screen(¤t_line, &temporary_line, 0, nb_lines, lines, pattern);
684 if(key >= ' ' && key <= '~') {
685 pattern[pattern_point++] = key;
686 pattern[pattern_point] = '\0';
689 else if(key == KEY_BACKSPACE || key == '
\b' || key == '
\7f' ||
690 key == KEY_DC || key == '
\ 4') {
691 if(pattern_point > 0) {
693 pattern[pattern_point] = '\0';
697 else if(key == KEY_HOME) {
701 else if(key == KEY_END) {
702 current_line = nb_lines - 1;
705 else if(key == KEY_NPAGE) {
709 else if(key == KEY_PPAGE) {
713 else if(key == KEY_DOWN || key == '
\ e') {
717 else if(key == KEY_UP || key == '
\10') {
721 else if(key == '
\12') {
722 use_regexp = !use_regexp;
725 else if(key == '
\15') {
727 pattern[pattern_point] = '\0';
730 update_screen(¤t_line, &temporary_line, motion,
731 nb_lines, lines, pattern);
733 } while(key != '\n' && key != KEY_ENTER && key != '
\a');
739 //////////////////////////////////////////////////////////////////////
740 // Here we come back to standard display
742 if((key == KEY_ENTER || key == '\n')) {
744 if(output_to_vt_buffer) {
745 if(temporary_line >= 0 && temporary_line < nb_lines) {
746 inject_into_tty_buffer(lines[temporary_line]);
750 if(output_filename[0]) {
751 ofstream out(output_filename);
753 cerr << "Can not open " << output_filename << " for writing." << endl;
756 if(temporary_line >= 0 && temporary_line < nb_lines) {
757 out << lines[temporary_line] << endl;
767 for(int l = 0; l < nb_lines; l++) {