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;
59 //////////////////////////////////////////////////////////////////////
61 void inject_into_tty_buffer(char *string) {
62 struct termios oldtio, newtio;
63 tcgetattr(STDIN_FILENO, &oldtio);
64 memset(&newtio, 0, sizeof(newtio));
65 // Set input mode (non-canonical, *no echo*,...)
66 tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
67 // Put the selected string in the tty input buffer
68 for(char *k = string; *k; k++) {
69 ioctl(STDIN_FILENO, TIOCSTI, k);
71 // Restore the old settings
72 tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
75 //////////////////////////////////////////////////////////////////////
77 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
78 if(n_opt + n >= argc) {
79 cerr << "Missing argument for " << argv[n_opt] << "."
81 << "Expecting " << help << "."
87 //////////////////////////////////////////////////////////////////////
88 // A quick and dirty hash table
90 // The table itself stores index of the strings in a char
91 // **table. When a string is added, if it was already in the table,
92 // the new index replaces the previous one.
94 int *new_hash_table(int hash_table_size) {
96 result = new int[hash_table_size];
97 for(int k = 0; k < hash_table_size; k++) {
103 // Adds new_string in the table, associated to new_index. If this
104 // string was not already in the table, returns -1. Otherwise, returns
105 // the previous index it had.
107 int test_and_add(char *new_string, int new_index,
108 char **strings, int *hash_table, int hash_table_size) {
109 unsigned int code = 0;
111 // This is my recipe. I checked, it seems to work (as long as
112 // hash_table_size is not a multiple of 387433 that should be okay)
114 for(int k = 0; new_string[k]; k++) {
115 code = code * 387433 + (unsigned int) (new_string[k]);
118 code = code % hash_table_size;
120 while(hash_table[code] >= 0) {
121 // There is a string with that code
122 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
123 // It is the same string, we keep a copy of the stored index
124 int result = hash_table[code];
126 hash_table[code] = new_index;
127 // And return the previous one
130 // This collision was not the same string, let's move to the next
132 code = (code + 1) % hash_table_size;
135 // This string was not already in there, store the index in the
136 // table and return -1
137 hash_table[code] = new_index;
141 //////////////////////////////////////////////////////////////////////
142 // A matcher matches either with a collection of substrings, or with a
150 char *splitted_patterns, **patterns;
153 int match(char *string, matcher_t *matcher) {
154 if(matcher->nb_patterns >= 0) {
155 if(matcher->case_sensitive) {
156 for(int n = 0; n < matcher->nb_patterns; n++) {
157 if(strstr(string, matcher->patterns[n]) == 0) return 0;
160 for(int n = 0; n < matcher->nb_patterns; n++) {
161 if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
166 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
170 void free_matcher(matcher_t *matcher) {
171 if(matcher->nb_patterns >= 0) {
172 delete[] matcher->splitted_patterns;
173 delete[] matcher->patterns;
175 if(!matcher->regexp_error) regfree(&matcher->preg);
179 void initialize_matcher(int use_regexp, int case_sensitive, matcher_t *matcher, const char *pattern) {
181 matcher->nb_patterns = -1;
182 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
184 matcher->regexp_error = 0;
185 matcher->nb_patterns = 1;
186 matcher->case_sensitive = case_sensitive;
188 for(const char *s = pattern; *s; s++) {
189 if(*s == pattern_separator) {
190 matcher->nb_patterns++;
194 matcher->splitted_patterns = new char[strlen(pattern) + 1];
195 matcher->patterns = new char*[matcher->nb_patterns];
197 strcpy(matcher->splitted_patterns, pattern);
200 char *last_pattern_start = matcher->splitted_patterns;
201 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
202 if(*s == pattern_separator || *s == '\0') {
204 matcher->patterns[n++] = last_pattern_start;
205 last_pattern_start = s + 1;
211 //////////////////////////////////////////////////////////////////////
213 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
214 int line = current_line - 1;
215 while(line >= 0 && !match(lines[line], matcher)) line--;
219 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
220 int line = current_line + 1;
221 while(line < nb_lines && !match(lines[line], matcher)) line++;
229 //////////////////////////////////////////////////////////////////////
231 void update_screen(int *current_line, int *temporary_line, int motion,
232 int nb_lines, char **lines,
235 char buffer[buffer_size];
238 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
240 // We now take care of printing the lines per se
242 int console_width = getmaxx(stdscr);
243 int console_height = getmaxy(stdscr);
245 // First, we find a visible line. In priority: The current, or the
246 // first visible after it, or the first visible before it.
248 int nb_printed_lines = 0;
251 use_default_colors();
254 if(matcher.regexp_error) {
255 addstr("[regexp error]");
256 } else if(nb_lines > 0) {
258 if(match(lines[*current_line], &matcher)) {
259 new_line = *current_line;
261 new_line = next_visible(*current_line, nb_lines, lines, &matcher);
263 new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
267 // If we found a visible line and we should move, let's move
269 if(new_line >= 0 && motion != 0) {
272 // We want to go down, let's find the first visible line below
273 for(int m = 0; l >= 0 && m < motion; m++) {
274 l = next_visible(l, nb_lines, lines, &matcher);
280 // We want to go up, let's find the first visible line above
281 for(int m = 0; l >= 0 && m < -motion; m++) {
282 l = previous_visible(l, nb_lines, lines, &matcher);
290 // Here new_line is either a line number matching the patterns, or -1
294 int first_line = new_line, last_line = new_line, nb_match = 1;
296 // We find the first and last line to show, so that the total of
297 // visible lines between them (them include) is console_height - 1
299 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
303 while(first_line > 0 && !match(lines[first_line], &matcher)) {
306 if(match(lines[first_line], &matcher)) {
311 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
313 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
317 if(match(lines[last_line], &matcher)) {
323 // Now we display them
325 for(int l = first_line; l <= last_line; l++) {
326 if(match(lines[l], &matcher)) {
329 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
330 buffer[k] = lines[l][k];
334 // We fill the rest of the line with blanks if either we did
335 // not clear() or if this is the highlighted line
338 while(k < console_width) {
346 // Highlight the highlighted line ...
350 attron(COLOR_PAIR(2));
351 addnstr(buffer, console_width);
352 attroff(COLOR_PAIR(2));
355 addnstr(buffer, console_width);
359 addnstr(buffer, console_width);
367 *current_line = new_line;
371 *temporary_line = new_line;
373 if(nb_printed_lines == 0) {
374 addnstr("[no selection]\n", console_width);
377 addnstr("[empty choice]\n", console_width);
383 sprintf(buffer, "%s %d/%d pattern: %s%s",
388 use_regexp ? " [regexp]" : "");
390 sprintf(buffer, "%d/%d pattern: %s%s",
394 use_regexp ? " [regexp]" : "");
397 for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
398 buffer[console_width] = '\0';
402 attron(COLOR_PAIR(1));
403 addnstr(buffer, console_width);
404 attroff(COLOR_PAIR(1));
407 addnstr(buffer, console_width);
414 free_matcher(&matcher);
417 //////////////////////////////////////////////////////////////////////
419 int main(int argc, char **argv) {
421 if(!ttyname(STDIN_FILENO)) {
422 cerr << "The standard input is not a tty." << endl;
426 char buffer[buffer_size], raw_line[buffer_size];;
427 int color_fg_modeline, color_bg_modeline;
428 int color_fg_highlight, color_bg_highlight;
430 color_fg_modeline = COLOR_WHITE;
431 color_bg_modeline = COLOR_BLACK;
432 color_fg_highlight = COLOR_BLACK;
433 color_bg_highlight = COLOR_YELLOW;
435 setlocale(LC_ALL, "");
437 char input_filename[buffer_size], output_filename[buffer_size];
439 strcpy(input_filename, "");
440 strcpy(output_filename, "");
443 int error = 0, show_help = 0;
445 while(!error && !show_help && i < argc) {
447 if(strcmp(argv[i], "-o") == 0) {
448 check_opt(argc, argv, i, 1, "<output filename>");
449 strncpy(output_filename, argv[i+1], buffer_size);
453 else if(strcmp(argv[i], "-s") == 0) {
454 check_opt(argc, argv, i, 1, "<pattern separator>");
455 pattern_separator = argv[i+1][0];
459 else if(strcmp(argv[i], "-v") == 0) {
460 output_to_vt_buffer = 1;
464 else if(strcmp(argv[i], "-m") == 0) {
469 else if(strcmp(argv[i], "-f") == 0) {
470 check_opt(argc, argv, i, 1, "<input filename>");
471 strncpy(input_filename, argv[i+1], buffer_size);
475 else if(strcmp(argv[i], "-i") == 0) {
480 else if(strcmp(argv[i], "-b") == 0) {
485 else if(strcmp(argv[i], "-z") == 0) {
490 else if(strcmp(argv[i], "-d") == 0) {
491 remove_duplicates = 1;
495 else if(strcmp(argv[i], "-e") == 0) {
500 else if(strcmp(argv[i], "-a") == 0) {
505 else if(strcmp(argv[i], "-t") == 0) {
506 check_opt(argc, argv, i, 1, "<title>");
508 title = new char[strlen(argv[i+1]) + 1];
509 strcpy(title, argv[i+1]);
513 else if(strcmp(argv[i], "-l") == 0) {
514 check_opt(argc, argv, i, 1, "<maximum number of lines>");
515 nb_lines_max = atoi(argv[i+1]);
519 else if(strcmp(argv[i], "-c") == 0) {
520 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
521 color_fg_modeline = atoi(argv[i+1]);
522 color_bg_modeline = atoi(argv[i+2]);
523 color_fg_highlight = atoi(argv[i+3]);
524 color_bg_highlight = atoi(argv[i+4]);
528 else if(strcmp(argv[i], "-h") == 0) {
534 cerr << "Unknown argument " << argv[i] << "." << endl;
539 if(show_help || error) {
540 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
542 << "Written by Francois Fleuret <francois@fleuret.org>."
545 << "Usage: " << argv[0] << " [options] -f <file>" << endl
547 << " -h show this help" << endl
548 << " -v inject the selected line in the tty" << endl
549 << " -d remove duplicated lines" << endl
550 << " -b remove the bash history line prefix" << endl
551 << " -z remove the zsh history line prefix" << endl
552 << " -i invert the order of lines" << endl
553 << " -e start in regexp mode" << endl
554 << " -a case sensitive" << endl
555 << " -m monochrome mode" << endl
556 << " -t <title>" << endl
557 << " add a title in the modeline" << endl
558 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
559 << " set the display colors" << endl
560 << " -o <output filename>" << endl
561 << " set a file to write the selected line to" << endl
562 << " -s <pattern separator>" << endl
563 << " set the symbol to separate substrings in the pattern" << endl
564 << " -l <max number of lines>" << endl
565 << " set the maximum number of lines to take into account" << endl
571 char **lines = new char *[nb_lines_max];
573 if(!input_filename[0]) {
574 cerr << "You must specify a input file with -f." << endl;
580 ifstream file(input_filename);
583 cerr << "Can not open " << input_filename << endl;
587 int hash_table_size = nb_lines_max * 10;
590 if(remove_duplicates) {
591 hash_table = new_hash_table(hash_table_size);
594 while(nb_lines < nb_lines_max && !file.eof()) {
596 file.getline(raw_line, buffer_size);
601 cerr << "Line too long:" << endl;
602 cerr << raw_line << endl;
613 while(*u) { *s++ = *u++; }
619 if(zsh_history && *s == ':') {
620 while(*s && *s != ';') s++;
624 if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
625 while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
631 dup = test_and_add(s, nb_lines, lines, hash_table, hash_table_size);
637 lines[nb_lines] = new char[strlen(s) + 1];
638 strcpy(lines[nb_lines], s);
640 // The string was already in there, so we do not allocate a
641 // new string but use the pointer to the first occurence of it
642 lines[nb_lines] = lines[dup];
652 // Now remove the null strings
655 for(int k = 0; k < nb_lines; k++) {
657 lines[n++] = lines[k];
663 for(int i = 0; i < nb_lines/2; i++) {
664 char *s = lines[nb_lines - 1 - i];
665 lines[nb_lines - 1 - i] = lines[i];
670 char pattern[buffer_size];
675 //////////////////////////////////////////////////////////////////////
676 // Here we start to display with curse
685 // So that the arrow keys work
686 keypad(stdscr, TRUE);
691 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
692 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
693 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
694 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
698 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
701 init_pair(1, color_fg_modeline, color_bg_modeline);
702 init_pair(2, color_fg_highlight, color_bg_highlight);
709 int current_line = 0, temporary_line = 0;
711 update_screen(¤t_line, &temporary_line, 0, nb_lines, lines, pattern);
719 if(key >= ' ' && key <= '~') {
720 pattern[pattern_point++] = key;
721 pattern[pattern_point] = '\0';
724 else if(key == KEY_BACKSPACE || key == '
\b' || key == '
\7f' ||
725 key == KEY_DC || key == '
\ 4') {
726 if(pattern_point > 0) {
728 pattern[pattern_point] = '\0';
732 else if(key == KEY_HOME) {
736 else if(key == KEY_END) {
737 current_line = nb_lines - 1;
740 else if(key == KEY_NPAGE) {
744 else if(key == KEY_PPAGE) {
748 else if(key == KEY_DOWN || key == '
\ e') {
752 else if(key == KEY_UP || key == '
\10') {
756 else if(key == '
\12') {
757 use_regexp = !use_regexp;
760 else if(key == '
\15') {
762 pattern[pattern_point] = '\0';
765 update_screen(¤t_line, &temporary_line, motion,
766 nb_lines, lines, pattern);
768 } while(key != '\n' && key != KEY_ENTER && key != '
\a');
774 //////////////////////////////////////////////////////////////////////
775 // Here we come back to standard display
777 if((key == KEY_ENTER || key == '\n')) {
779 if(output_to_vt_buffer) {
780 if(temporary_line >= 0 && temporary_line < nb_lines) {
781 inject_into_tty_buffer(lines[temporary_line]);
785 if(output_filename[0]) {
786 ofstream out(output_filename);
788 cerr << "Can not open " << output_filename << " for writing." << endl;
791 if(temporary_line >= 0 && temporary_line < nb_lines) {
792 out << lines[temporary_line] << endl;
802 for(int l = 0; l < nb_lines; l++) {