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 int *new_hash_table(int hash_table_size) {
92 result = new int[hash_table_size];
93 for(int k = 0; k < hash_table_size; k++) {
99 int test_and_add(char *new_string, int new_index,
100 char **strings, int *hash_table, int hash_table_size) {
101 unsigned int code = 0;
103 // This is my recipe. I checked, it seems to work (as long as
104 // hash_table_size is not a multiple of 387433 that should be okay)
106 for(int k = 0; new_string[k]; k++) {
107 code = code * 387433 + (unsigned int) (new_string[k]);
110 code = code % hash_table_size;
112 while(hash_table[code] >= 0) {
113 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
114 int result = hash_table[code];
115 hash_table[code] = new_index;
118 code = (code + 1) % hash_table_size;
121 hash_table[code] = new_index;
126 //////////////////////////////////////////////////////////////////////
127 // A matcher matches either with a collection of substrings, or with a
135 char *splitted_patterns, **patterns;
138 int match(char *string, matcher_t *matcher) {
139 if(matcher->nb_patterns >= 0) {
140 if(matcher->case_sensitive) {
141 for(int n = 0; n < matcher->nb_patterns; n++) {
142 if(strstr(string, matcher->patterns[n]) == 0) return 0;
145 for(int n = 0; n < matcher->nb_patterns; n++) {
146 if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
151 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
155 void free_matcher(matcher_t *matcher) {
156 if(matcher->nb_patterns >= 0) {
157 delete[] matcher->splitted_patterns;
158 delete[] matcher->patterns;
160 if(!matcher->regexp_error) regfree(&matcher->preg);
164 void initialize_matcher(int use_regexp, int case_sensitive, matcher_t *matcher, const char *pattern) {
166 matcher->nb_patterns = -1;
167 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
169 matcher->regexp_error = 0;
170 matcher->nb_patterns = 1;
171 matcher->case_sensitive = case_sensitive;
173 for(const char *s = pattern; *s; s++) {
174 if(*s == pattern_separator) {
175 matcher->nb_patterns++;
179 matcher->splitted_patterns = new char[strlen(pattern) + 1];
180 matcher->patterns = new char*[matcher->nb_patterns];
182 strcpy(matcher->splitted_patterns, pattern);
185 char *last_pattern_start = matcher->splitted_patterns;
186 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
187 if(*s == pattern_separator || *s == '\0') {
189 matcher->patterns[n++] = last_pattern_start;
190 last_pattern_start = s + 1;
196 //////////////////////////////////////////////////////////////////////
198 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
199 int line = current_line - 1;
200 while(line >= 0 && !match(lines[line], matcher)) line--;
204 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
205 int line = current_line + 1;
206 while(line < nb_lines && !match(lines[line], matcher)) line++;
214 //////////////////////////////////////////////////////////////////////
216 void update_screen(int *current_line, int *temporary_line, int motion,
217 int nb_lines, char **lines,
220 char buffer[buffer_size];
223 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
225 // We now take care of printing the lines per se
227 int console_width = getmaxx(stdscr);
228 int console_height = getmaxy(stdscr);
230 // First, we find a visible line. In priority: The current, or the
231 // first visible after it, or the first visible before it.
233 int nb_printed_lines = 0;
236 use_default_colors();
239 if(matcher.regexp_error) {
240 addstr("[regexp error]");
241 } else if(nb_lines > 0) {
243 if(match(lines[*current_line], &matcher)) {
244 new_line = *current_line;
246 new_line = next_visible(*current_line, nb_lines, lines, &matcher);
248 new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
252 // If we found a visible line and we should move, let's move
254 if(new_line >= 0 && motion != 0) {
257 // We want to go down, let's find the first visible line below
258 for(int m = 0; l >= 0 && m < motion; m++) {
259 l = next_visible(l, nb_lines, lines, &matcher);
265 // We want to go up, let's find the first visible line above
266 for(int m = 0; l >= 0 && m < -motion; m++) {
267 l = previous_visible(l, nb_lines, lines, &matcher);
275 // Here new_line is either a line number matching the patterns, or -1
279 int first_line = new_line, last_line = new_line, nb_match = 1;
281 // We find the first and last line to show, so that the total of
282 // visible lines between them (them include) is console_height - 1
284 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
288 while(first_line > 0 && !match(lines[first_line], &matcher)) {
291 if(match(lines[first_line], &matcher)) {
296 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
298 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
302 if(match(lines[last_line], &matcher)) {
308 // Now we display them
310 for(int l = first_line; l <= last_line; l++) {
311 if(match(lines[l], &matcher)) {
314 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
315 buffer[k] = lines[l][k];
319 // We fill the rest of the line with blanks if either we did
320 // not clear() or if this is the highlighted line
323 while(k < console_width) {
331 // Highlight the highlighted line ...
335 attron(COLOR_PAIR(2));
336 addnstr(buffer, console_width);
337 attroff(COLOR_PAIR(2));
340 addnstr(buffer, console_width);
344 addnstr(buffer, console_width);
352 *current_line = new_line;
356 *temporary_line = new_line;
358 if(nb_printed_lines == 0) {
359 addnstr("[no selection]\n", console_width);
362 addnstr("[empty choice]\n", console_width);
368 sprintf(buffer, "%s %d/%d pattern: %s%s",
373 use_regexp ? " [regexp]" : "");
375 sprintf(buffer, "%d/%d pattern: %s%s",
379 use_regexp ? " [regexp]" : "");
382 for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
383 buffer[console_width] = '\0';
387 attron(COLOR_PAIR(1));
388 addnstr(buffer, console_width);
389 attroff(COLOR_PAIR(1));
392 addnstr(buffer, console_width);
399 free_matcher(&matcher);
402 //////////////////////////////////////////////////////////////////////
404 int main(int argc, char **argv) {
406 if(!ttyname(STDIN_FILENO)) {
407 cerr << "The standard input is not a tty." << endl;
411 char buffer[buffer_size], raw_line[buffer_size];;
412 int color_fg_modeline, color_bg_modeline;
413 int color_fg_highlight, color_bg_highlight;
415 color_fg_modeline = COLOR_WHITE;
416 color_bg_modeline = COLOR_BLACK;
417 color_fg_highlight = COLOR_BLACK;
418 color_bg_highlight = COLOR_YELLOW;
420 setlocale(LC_ALL, "");
422 char input_filename[buffer_size], output_filename[buffer_size];
424 strcpy(input_filename, "");
425 strcpy(output_filename, "");
428 int error = 0, show_help = 0;
430 while(!error && !show_help && i < argc) {
432 if(strcmp(argv[i], "-o") == 0) {
433 check_opt(argc, argv, i, 1, "<output filename>");
434 strncpy(output_filename, argv[i+1], buffer_size);
438 else if(strcmp(argv[i], "-s") == 0) {
439 check_opt(argc, argv, i, 1, "<pattern separator>");
440 pattern_separator = argv[i+1][0];
444 else if(strcmp(argv[i], "-v") == 0) {
445 output_to_vt_buffer = 1;
449 else if(strcmp(argv[i], "-m") == 0) {
454 else if(strcmp(argv[i], "-f") == 0) {
455 check_opt(argc, argv, i, 1, "<input filename>");
456 strncpy(input_filename, argv[i+1], buffer_size);
460 else if(strcmp(argv[i], "-i") == 0) {
465 else if(strcmp(argv[i], "-b") == 0) {
470 else if(strcmp(argv[i], "-z") == 0) {
475 else if(strcmp(argv[i], "-d") == 0) {
476 remove_duplicates = 1;
480 else if(strcmp(argv[i], "-e") == 0) {
485 else if(strcmp(argv[i], "-a") == 0) {
490 else if(strcmp(argv[i], "-t") == 0) {
491 check_opt(argc, argv, i, 1, "<title>");
493 title = new char[strlen(argv[i+1]) + 1];
494 strcpy(title, argv[i+1]);
498 else if(strcmp(argv[i], "-l") == 0) {
499 check_opt(argc, argv, i, 1, "<maximum number of lines>");
500 nb_lines_max = atoi(argv[i+1]);
504 else if(strcmp(argv[i], "-c") == 0) {
505 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
506 color_fg_modeline = atoi(argv[i+1]);
507 color_bg_modeline = atoi(argv[i+2]);
508 color_fg_highlight = atoi(argv[i+3]);
509 color_bg_highlight = atoi(argv[i+4]);
513 else if(strcmp(argv[i], "-h") == 0) {
519 cerr << "Unknown argument " << argv[i] << "." << endl;
524 if(show_help || error) {
525 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
527 << "Written by Francois Fleuret <francois@fleuret.org>."
530 << "Usage: " << argv[0] << " [options] -f <file>" << endl
532 << " -h show this help" << endl
533 << " -v inject the selected line in the tty" << endl
534 << " -d remove duplicated lines" << endl
535 << " -b remove the bash history line prefix" << endl
536 << " -z remove the zsh history line prefix" << endl
537 << " -i invert the order of lines" << endl
538 << " -e start in regexp mode" << endl
539 << " -a case sensitive" << endl
540 << " -m monochrome mode" << endl
541 << " -t <title>" << endl
542 << " add a title in the modeline" << endl
543 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
544 << " set the display colors" << endl
545 << " -o <output filename>" << endl
546 << " set a file to write the selected line to" << endl
547 << " -s <pattern separator>" << endl
548 << " set the symbol to separate substrings in the pattern" << endl
549 << " -l <max number of lines>" << endl
550 << " set the maximum number of lines to take into account" << endl
556 char **lines = new char *[nb_lines_max];
558 if(!input_filename[0]) {
559 cerr << "You must specify a input file with -f." << endl;
565 ifstream file(input_filename);
568 cerr << "Can not open " << input_filename << endl;
572 int hash_table_size = nb_lines_max * 10;
575 if(remove_duplicates) {
576 hash_table = new_hash_table(hash_table_size);
579 while(nb_lines < nb_lines_max && !file.eof()) {
581 file.getline(raw_line, buffer_size);
586 cerr << "Line too long:" << endl;
587 cerr << raw_line << endl;
598 while(*u) { *s++ = *u++; }
604 if(zsh_history && *s == ':') {
605 while(*s && *s != ';') s++;
609 if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
610 while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
616 dup = test_and_add(s, nb_lines, lines, hash_table, hash_table_size);
622 lines[nb_lines] = new char[strlen(s) + 1];
623 strcpy(lines[nb_lines], s);
625 // We do not allocate a new string but use the pointer to the
626 // first occurence of it
627 lines[nb_lines] = lines[dup];
637 // Now remove the null strings
640 for(int k = 0; k < nb_lines; k++) {
642 lines[n++] = lines[k];
648 for(int i = 0; i < nb_lines/2; i++) {
649 char *s = lines[nb_lines - 1 - i];
650 lines[nb_lines - 1 - i] = lines[i];
655 char pattern[buffer_size];
660 //////////////////////////////////////////////////////////////////////
661 // Here we start to display with curse
670 // So that the arrow keys work
671 keypad(stdscr, TRUE);
676 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
677 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
678 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
679 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
683 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
686 init_pair(1, color_fg_modeline, color_bg_modeline);
687 init_pair(2, color_fg_highlight, color_bg_highlight);
694 int current_line = 0, temporary_line = 0;
696 update_screen(¤t_line, &temporary_line, 0, nb_lines, lines, pattern);
704 if(key >= ' ' && key <= '~') {
705 pattern[pattern_point++] = key;
706 pattern[pattern_point] = '\0';
709 else if(key == KEY_BACKSPACE || key == '
\b' || key == '
\7f' ||
710 key == KEY_DC || key == '
\ 4') {
711 if(pattern_point > 0) {
713 pattern[pattern_point] = '\0';
717 else if(key == KEY_HOME) {
721 else if(key == KEY_END) {
722 current_line = nb_lines - 1;
725 else if(key == KEY_NPAGE) {
729 else if(key == KEY_PPAGE) {
733 else if(key == KEY_DOWN || key == '
\ e') {
737 else if(key == KEY_UP || key == '
\10') {
741 else if(key == '
\12') {
742 use_regexp = !use_regexp;
745 else if(key == '
\15') {
747 pattern[pattern_point] = '\0';
750 update_screen(¤t_line, &temporary_line, motion,
751 nb_lines, lines, pattern);
753 } while(key != '\n' && key != KEY_ENTER && key != '
\a');
759 //////////////////////////////////////////////////////////////////////
760 // Here we come back to standard display
762 if((key == KEY_ENTER || key == '\n')) {
764 if(output_to_vt_buffer) {
765 if(temporary_line >= 0 && temporary_line < nb_lines) {
766 inject_into_tty_buffer(lines[temporary_line]);
770 if(output_filename[0]) {
771 ofstream out(output_filename);
773 cerr << "Can not open " << output_filename << " for writing." << endl;
776 if(temporary_line >= 0 && temporary_line < nb_lines) {
777 out << lines[temporary_line] << endl;
787 for(int l = 0; l < nb_lines; l++) {