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 = 1024;
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;
57 //////////////////////////////////////////////////////////////////////
59 void inject_into_tty_buffer(char *string) {
60 struct termios oldtio, newtio;
61 tcgetattr(STDIN_FILENO, &oldtio);
62 memset(&newtio, 0, sizeof(newtio));
63 // Set input mode (non-canonical, *no echo*,...)
64 tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
65 // Put the selected string in the tty input buffer
66 for(char *k = string; *k; k++) {
67 ioctl(STDIN_FILENO, TIOCSTI, k);
69 // Restore the old settings
70 tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
73 //////////////////////////////////////////////////////////////////////
75 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
76 if(n_opt + n >= argc) {
77 cerr << "Missing argument for " << argv[n_opt] << "."
79 << "Expecting " << help << "."
85 //////////////////////////////////////////////////////////////////////
86 // A quick and dirty hash table
88 int *new_hash_table(int hash_table_size) {
90 result = new int[hash_table_size];
91 for(int k = 0; k < hash_table_size; k++) {
97 int test_and_add(char *new_string, int new_index,
98 char **strings, int *hash_table, int hash_table_size) {
99 unsigned int code = 0;
101 // This is my recipe. I checked, it seems to work (as long as
102 // hash_table_size is not a multiple of 387433 that should be okay)
104 for(int k = 0; new_string[k]; k++) {
105 code = code * 387433 + (unsigned int) (new_string[k]);
108 code = code % hash_table_size;
110 while(hash_table[code] >= 0) {
111 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
112 int result = hash_table[code];
113 hash_table[code] = new_index;
116 code = (code + 1) % hash_table_size;
119 hash_table[code] = new_index;
124 //////////////////////////////////////////////////////////////////////
125 // A matcher matches either with a collection of substrings, or with a
132 char *splitted_patterns, **patterns;
135 int match(char *string, matcher_t *matcher) {
136 if(matcher->nb_patterns >= 0) {
137 for(int n = 0; n < matcher->nb_patterns; n++) {
138 if(strstr(string, matcher->patterns[n]) == 0) return 0;
142 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
146 void free_matcher(matcher_t *matcher) {
147 if(matcher->nb_patterns >= 0) {
148 delete[] matcher->splitted_patterns;
149 delete[] matcher->patterns;
151 if(!matcher->regexp_error) regfree(&matcher->preg);
155 void initialize_matcher(int use_regexp, matcher_t *matcher, const char *pattern) {
157 matcher->nb_patterns = -1;
158 matcher->regexp_error = regcomp(&matcher->preg, pattern, REG_ICASE);
160 matcher->regexp_error = 0;
161 matcher->nb_patterns = 1;
163 for(const char *s = pattern; *s; s++) {
164 if(*s == pattern_separator) {
165 matcher->nb_patterns++;
169 matcher->splitted_patterns = new char[strlen(pattern) + 1];
170 matcher->patterns = new char*[matcher->nb_patterns];
172 strcpy(matcher->splitted_patterns, pattern);
175 char *last_pattern_start = matcher->splitted_patterns;
176 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
177 if(*s == pattern_separator || *s == '\0') {
179 matcher->patterns[n++] = last_pattern_start;
180 last_pattern_start = s + 1;
186 //////////////////////////////////////////////////////////////////////
188 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
189 int line = current_line - 1;
190 while(line >= 0 && !match(lines[line], matcher)) line--;
194 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
195 int line = current_line + 1;
196 while(line < nb_lines && !match(lines[line], matcher)) line++;
204 //////////////////////////////////////////////////////////////////////
206 void update_screen(int *current_line, int *temporary_line, int motion,
207 int nb_lines, char **lines,
210 char buffer[buffer_size];
213 initialize_matcher(use_regexp, &matcher, pattern);
215 // We now take care of printing the lines per se
217 int console_width = getmaxx(stdscr);
218 int console_height = getmaxy(stdscr);
220 // First, we find a visible line. In priority: The current, or the
221 // first visible after it, or the first visible before it.
223 int nb_printed_lines = 0;
226 use_default_colors();
229 if(matcher.regexp_error) {
230 addstr("[regexp error]");
234 if(match(lines[*current_line], &matcher)) {
235 new_line = *current_line;
237 new_line = next_visible(*current_line, nb_lines, lines, &matcher);
239 new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
243 // If we found a visible line and we should move, let's move
245 if(new_line >= 0 && motion != 0) {
248 // We want to go down, let's find the first visible line below
249 for(int m = 0; l >= 0 && m < motion; m++) {
250 l = next_visible(l, nb_lines, lines, &matcher);
256 // We want to go up, let's find the first visible line above
257 for(int m = 0; l >= 0 && m < -motion; m++) {
258 l = previous_visible(l, nb_lines, lines, &matcher);
266 // Here new_line is either a line number matching the patterns, or -1
270 int first_line = new_line, last_line = new_line, nb_match = 1;
272 // We find the first and last line to show, so that the total of
273 // visible lines between them (them include) is console_height - 1
275 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
279 while(first_line > 0 && !match(lines[first_line], &matcher)) {
282 if(match(lines[first_line], &matcher)) {
287 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
289 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
293 if(match(lines[last_line], &matcher)) {
299 // Now we display them
301 for(int l = first_line; l <= last_line; l++) {
302 if(match(lines[l], &matcher)) {
305 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
306 buffer[k] = lines[l][k];
310 // We fill the rest of the line with blanks if either we did
311 // not clear() or if this is the highlighted line
314 while(k < console_width) {
322 // Highlight the highlighted line ...
326 attron(COLOR_PAIR(2));
327 addnstr(buffer, console_width);
328 attroff(COLOR_PAIR(2));
331 addnstr(buffer, console_width);
335 addnstr(buffer, console_width);
343 *current_line = new_line;
347 *temporary_line = new_line;
349 if(nb_printed_lines == 0) {
350 addnstr("[no selection]\n", console_width);
356 sprintf(buffer, "%d/%d pattern: %s%s",
360 use_regexp ? " [regexp]" : "");
362 for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
363 buffer[console_width] = '\0';
367 attron(COLOR_PAIR(1));
368 addnstr(buffer, console_width);
369 attroff(COLOR_PAIR(1));
372 addnstr(buffer, console_width);
379 free_matcher(&matcher);
382 //////////////////////////////////////////////////////////////////////
384 int main(int argc, char **argv) {
386 if(!ttyname(STDIN_FILENO)) {
387 cerr << "The standard input is not a tty." << endl;
391 char buffer[buffer_size], raw_line[buffer_size];;
392 int color_fg_modeline, color_bg_modeline;
393 int color_fg_highlight, color_bg_highlight;
395 color_fg_modeline = COLOR_WHITE;
396 color_bg_modeline = COLOR_BLACK;
397 color_fg_highlight = COLOR_BLACK;
398 color_bg_highlight = COLOR_YELLOW;
400 setlocale(LC_ALL, "");
402 char input_filename[buffer_size], output_filename[buffer_size];
404 strcpy(input_filename, "");
405 strcpy(output_filename, "");
408 int error = 0, show_help = 0;
410 while(!error && !show_help && i < argc) {
412 if(strcmp(argv[i], "-o") == 0) {
413 check_opt(argc, argv, i, 1, "<output filename>");
414 strncpy(output_filename, argv[i+1], buffer_size);
418 else if(strcmp(argv[i], "-s") == 0) {
419 check_opt(argc, argv, i, 1, "<pattern separator>");
420 pattern_separator = argv[i+1][0];
424 else if(strcmp(argv[i], "-v") == 0) {
425 output_to_vt_buffer = 1;
429 else if(strcmp(argv[i], "-m") == 0) {
434 else if(strcmp(argv[i], "-f") == 0) {
435 check_opt(argc, argv, i, 1, "<input filename>");
436 strncpy(input_filename, argv[i+1], buffer_size);
440 else if(strcmp(argv[i], "-i") == 0) {
445 else if(strcmp(argv[i], "-b") == 0) {
450 else if(strcmp(argv[i], "-z") == 0) {
455 else if(strcmp(argv[i], "-d") == 0) {
456 remove_duplicates = 1;
460 else if(strcmp(argv[i], "-e") == 0) {
465 else if(strcmp(argv[i], "-l") == 0) {
466 check_opt(argc, argv, i, 1, "<maximum number of lines>");
467 nb_lines_max = atoi(argv[i+1]);
471 else if(strcmp(argv[i], "-c") == 0) {
472 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
473 color_fg_modeline = atoi(argv[i+1]);
474 color_bg_modeline = atoi(argv[i+2]);
475 color_fg_highlight = atoi(argv[i+3]);
476 color_bg_highlight = atoi(argv[i+4]);
480 else if(strcmp(argv[i], "-h") == 0) {
486 cerr << "Unknown argument " << argv[i] << "." << endl;
491 if(show_help || error) {
492 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
494 << "Written by Francois Fleuret <francois@fleuret.org>."
497 << "Usage: " << argv[0] << " [options] -f <file>" << endl
499 << " -h show this help" << endl
500 << " -v inject the selected line in the tty" << endl
501 << " -d remove duplicated lines" << endl
502 << " -b remove the bash history line prefix" << endl
503 << " -z remove the zsh history line prefix" << endl
504 << " -i invert the order of lines" << endl
505 << " -e start in regexp mode" << endl
506 << " -m monochrome mode" << endl
507 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
508 << " set the display colors" << endl
509 << " -o <output filename>" << endl
510 << " set a file to write the selected line to" << endl
511 << " -s <pattern separator>" << endl
512 << " set the symbol to separate substrings in the pattern" << endl
513 << " -l <max number of lines>" << endl
514 << " set the maximum number of lines to take into account" << endl
520 char **lines = new char *[nb_lines_max];
522 if(!input_filename[0]) {
523 cerr << "You must specify a input file with -f." << endl;
529 ifstream file(input_filename);
532 cerr << "Can not open " << input_filename << endl;
536 int hash_table_size = nb_lines_max * 10;
539 if(remove_duplicates) {
540 hash_table = new_hash_table(hash_table_size);
543 while(nb_lines < nb_lines_max && !file.eof()) {
545 file.getline(raw_line, buffer_size);
556 while(*u) { *s++ = *u++; }
562 if(zsh_history && *s == ':') {
563 while(*s && *s != ';') s++;
567 if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
568 while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
574 dup = test_and_add(s, nb_lines, lines, hash_table, hash_table_size);
580 lines[nb_lines] = new char[strlen(s) + 1];
581 strcpy(lines[nb_lines], s);
583 // We do not allocate a new string but use the pointer to the
584 // first occurence of it
585 lines[nb_lines] = lines[dup];
595 // Now remove the null strings
598 for(int k = 0; k < nb_lines; k++) {
600 lines[n++] = lines[k];
606 for(int i = 0; i < nb_lines/2; i++) {
607 char *s = lines[nb_lines - 1 - i];
608 lines[nb_lines - 1 - i] = lines[i];
613 char pattern[buffer_size];
618 //////////////////////////////////////////////////////////////////////
619 // Here we start to display with curse
628 // So that the arrow keys work
629 keypad(stdscr, TRUE);
634 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
635 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
636 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
637 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
641 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
644 init_pair(1, color_fg_modeline, color_bg_modeline);
645 init_pair(2, color_fg_highlight, color_bg_highlight);
652 int current_line = 0, temporary_line = 0;
654 update_screen(¤t_line, &temporary_line, 0, nb_lines, lines, pattern);
662 if(key >= ' ' && key <= '~') {
663 pattern[pattern_point++] = key;
664 pattern[pattern_point] = '\0';
667 else if(key == KEY_BACKSPACE || key == '
\b' || key == '
\7f' ||
668 key == KEY_DC || key == '
\ 4') {
669 if(pattern_point > 0) {
671 pattern[pattern_point] = '\0';
675 else if(key == KEY_HOME) {
679 else if(key == KEY_END) {
680 current_line = nb_lines - 1;
683 else if(key == KEY_NPAGE) {
687 else if(key == KEY_PPAGE) {
691 else if(key == KEY_DOWN || key == '
\ e') {
695 else if(key == KEY_UP || key == '
\10') {
699 else if(key == '
\12') {
700 use_regexp = !use_regexp;
703 else if(key == '
\15') {
705 pattern[pattern_point] = '\0';
708 update_screen(¤t_line, &temporary_line, motion,
709 nb_lines, lines, pattern);
711 } while(key != '\n' && key != KEY_ENTER && key != '
\a');
717 //////////////////////////////////////////////////////////////////////
718 // Here we come back to standard display
720 if((key == KEY_ENTER || key == '\n')) {
722 if(output_to_vt_buffer) {
723 if(temporary_line >= 0 && temporary_line < nb_lines) {
724 inject_into_tty_buffer(lines[temporary_line]);
728 if(output_filename[0]) {
729 ofstream out(output_filename);
731 cerr << "Can not open " << output_filename << " for writing." << endl;
734 if(temporary_line >= 0 && temporary_line < nb_lines) {
735 out << lines[temporary_line] << endl;
745 for(int l = 0; l < nb_lines; l++) {