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,
180 matcher_t *matcher, const char *pattern) {
183 matcher->nb_patterns = -1;
184 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
186 matcher->regexp_error = 0;
187 matcher->nb_patterns = 1;
188 matcher->case_sensitive = case_sensitive;
190 for(const char *s = pattern; *s; s++) {
191 if(*s == pattern_separator) {
192 matcher->nb_patterns++;
196 matcher->splitted_patterns = new char[strlen(pattern) + 1];
197 matcher->patterns = new char*[matcher->nb_patterns];
199 strcpy(matcher->splitted_patterns, pattern);
202 char *last_pattern_start = matcher->splitted_patterns;
203 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
204 if(*s == pattern_separator || *s == '\0') {
206 matcher->patterns[n++] = last_pattern_start;
207 last_pattern_start = s + 1;
213 //////////////////////////////////////////////////////////////////////
216 void delete_char(char *buffer, int *position) {
217 if(buffer[*position]) {
219 while(c < buffer_size && buffer[c]) {
220 buffer[c] = buffer[c+1];
226 void backspace_char(char *buffer, int *position) {
228 if(buffer[*position]) {
229 int c = *position - 1;
231 buffer[c] = buffer[c+1];
235 buffer[*position - 1] = '\0';
242 void insert_char(char *buffer, int *position, char character) {
243 if(strlen(buffer) < buffer_size - 1) {
245 char t = buffer[c], u;
254 buffer[(*position)++] = character;
258 void kill_before_cursor(char *buffer, int *position) {
260 while(buffer[*position + s]) {
261 buffer[s] = buffer[*position + s];
268 void kill_after_cursor(char *buffer, int *position) {
269 buffer[*position] = '\0';
272 //////////////////////////////////////////////////////////////////////
274 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
275 int line = current_line - 1;
276 while(line >= 0 && !match(lines[line], matcher)) line--;
280 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
281 int line = current_line + 1;
282 while(line < nb_lines && !match(lines[line], matcher)) line++;
290 //////////////////////////////////////////////////////////////////////
292 void update_screen(int *current_line, int *temporary_line, int motion,
293 int nb_lines, char **lines,
297 char buffer[buffer_size];
300 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
302 // We now take care of printing the lines per se
304 int console_width = getmaxx(stdscr);
305 int console_height = getmaxy(stdscr);
307 // First, we find a visible line. In priority: The current, or the
308 // first visible after it, or the first visible before it.
310 int nb_printed_lines = 0;
313 use_default_colors();
316 if(matcher.regexp_error) {
317 addstr("[regexp error]");
318 } else if(nb_lines > 0) {
320 if(match(lines[*current_line], &matcher)) {
321 new_line = *current_line;
323 new_line = next_visible(*current_line, nb_lines, lines, &matcher);
325 new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
329 // If we found a visible line and we should move, let's move
331 if(new_line >= 0 && motion != 0) {
334 // We want to go down, let's find the first visible line below
335 for(int m = 0; l >= 0 && m < motion; m++) {
336 l = next_visible(l, nb_lines, lines, &matcher);
342 // We want to go up, let's find the first visible line above
343 for(int m = 0; l >= 0 && m < -motion; m++) {
344 l = previous_visible(l, nb_lines, lines, &matcher);
352 // Here new_line is either a line number matching the patterns, or -1
356 int first_line = new_line, last_line = new_line, nb_match = 1;
358 // We find the first and last line to show, so that the total of
359 // visible lines between them (them include) is console_height - 1
361 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
365 while(first_line > 0 && !match(lines[first_line], &matcher)) {
368 if(match(lines[first_line], &matcher)) {
373 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
375 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
379 if(match(lines[last_line], &matcher)) {
385 // Now we display them
387 for(int l = first_line; l <= last_line; l++) {
388 if(match(lines[l], &matcher)) {
391 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
392 buffer[k] = lines[l][k];
396 // We fill the rest of the line with blanks if either we did
397 // not clear() or if this is the highlighted line
400 while(k < console_width) {
408 // Highlight the highlighted line ...
412 attron(COLOR_PAIR(2));
413 addnstr(buffer, console_width);
414 attroff(COLOR_PAIR(2));
417 addnstr(buffer, console_width);
421 addnstr(buffer, console_width);
429 *current_line = new_line;
433 *temporary_line = new_line;
435 if(nb_printed_lines == 0) {
436 addnstr("[no selection]\n", console_width);
439 addnstr("[empty choice]\n", console_width);
446 attron(COLOR_PAIR(1));
451 for(int k = 0; k < console_width; k++) buffer[k] = ' ';
452 buffer[console_width] = '\0';
453 addnstr(buffer, console_width);
462 printw("%d/%d ", nb_printed_lines, nb_lines);
464 addnstr(pattern, cursor_position);
466 // Now we print the cursor. All that mess to have reverse video with
467 // and without color.
470 attroff(COLOR_PAIR(1));
471 attron(COLOR_PAIR(3));
476 if(pattern[cursor_position]) {
477 addnstr(&pattern[cursor_position], 1);
483 attroff(COLOR_PAIR(3));
484 attron(COLOR_PAIR(1));
489 if(pattern[cursor_position]) {
490 addstr(pattern + cursor_position + 1);
493 // Finished printing the cursor
500 attroff(COLOR_PAIR(1));
508 free_matcher(&matcher);
511 //////////////////////////////////////////////////////////////////////
513 int main(int argc, char **argv) {
515 if(!ttyname(STDIN_FILENO)) {
516 cerr << "The standard input is not a tty." << endl;
520 char buffer[buffer_size], raw_line[buffer_size];;
521 int color_fg_modeline, color_bg_modeline;
522 int color_fg_highlight, color_bg_highlight;
524 color_fg_modeline = COLOR_WHITE;
525 color_bg_modeline = COLOR_BLACK;
526 color_fg_highlight = COLOR_BLACK;
527 color_bg_highlight = COLOR_YELLOW;
529 setlocale(LC_ALL, "");
531 char input_filename[buffer_size], output_filename[buffer_size];
533 strcpy(input_filename, "");
534 strcpy(output_filename, "");
537 int error = 0, show_help = 0;
539 while(!error && !show_help && i < argc) {
541 if(strcmp(argv[i], "-o") == 0) {
542 check_opt(argc, argv, i, 1, "<output filename>");
543 strncpy(output_filename, argv[i+1], buffer_size);
547 else if(strcmp(argv[i], "-s") == 0) {
548 check_opt(argc, argv, i, 1, "<pattern separator>");
549 pattern_separator = argv[i+1][0];
553 else if(strcmp(argv[i], "-v") == 0) {
554 output_to_vt_buffer = 1;
558 else if(strcmp(argv[i], "-m") == 0) {
563 else if(strcmp(argv[i], "-f") == 0) {
564 check_opt(argc, argv, i, 1, "<input filename>");
565 strncpy(input_filename, argv[i+1], buffer_size);
569 else if(strcmp(argv[i], "-i") == 0) {
574 else if(strcmp(argv[i], "-b") == 0) {
579 else if(strcmp(argv[i], "-z") == 0) {
584 else if(strcmp(argv[i], "-d") == 0) {
585 remove_duplicates = 1;
589 else if(strcmp(argv[i], "-e") == 0) {
594 else if(strcmp(argv[i], "-a") == 0) {
599 else if(strcmp(argv[i], "-t") == 0) {
600 check_opt(argc, argv, i, 1, "<title>");
602 title = new char[strlen(argv[i+1]) + 1];
603 strcpy(title, argv[i+1]);
607 else if(strcmp(argv[i], "-l") == 0) {
608 check_opt(argc, argv, i, 1, "<maximum number of lines>");
609 nb_lines_max = atoi(argv[i+1]);
613 else if(strcmp(argv[i], "-c") == 0) {
614 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
615 color_fg_modeline = atoi(argv[i+1]);
616 color_bg_modeline = atoi(argv[i+2]);
617 color_fg_highlight = atoi(argv[i+3]);
618 color_bg_highlight = atoi(argv[i+4]);
622 else if(strcmp(argv[i], "-h") == 0) {
628 cerr << "Unknown argument " << argv[i] << "." << endl;
633 if(show_help || error) {
634 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
636 << "Written by Francois Fleuret <francois@fleuret.org>."
639 << "Usage: " << argv[0] << " [options] -f <file>" << endl
641 << " -h show this help" << endl
642 << " -v inject the selected line in the tty" << endl
643 << " -d remove duplicated lines" << endl
644 << " -b remove the bash history line prefix" << endl
645 << " -z remove the zsh history line prefix" << endl
646 << " -i invert the order of lines" << endl
647 << " -e start in regexp mode" << endl
648 << " -a case sensitive" << endl
649 << " -m monochrome mode" << endl
650 << " -t <title>" << endl
651 << " add a title in the modeline" << endl
652 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
653 << " set the display colors" << endl
654 << " -o <output filename>" << endl
655 << " set a file to write the selected line to" << endl
656 << " -s <pattern separator>" << endl
657 << " set the symbol to separate substrings in the pattern" << endl
658 << " -l <max number of lines>" << endl
659 << " set the maximum number of lines to take into account" << endl
665 char **lines = new char *[nb_lines_max];
667 if(!input_filename[0]) {
668 cerr << "You must specify a input file with -f." << endl;
674 ifstream file(input_filename);
677 cerr << "Can not open " << input_filename << endl;
681 int hash_table_size = nb_lines_max * 10;
684 if(remove_duplicates) {
685 hash_table = new_hash_table(hash_table_size);
688 while(nb_lines < nb_lines_max && !file.eof()) {
690 file.getline(raw_line, buffer_size);
695 cerr << "Line too long:" << endl;
696 cerr << raw_line << endl;
707 while(*u) { *s++ = *u++; }
713 if(zsh_history && *s == ':') {
714 while(*s && *s != ';') s++;
718 if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
719 while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
725 dup = test_and_add(s, nb_lines, lines, hash_table, hash_table_size);
731 lines[nb_lines] = new char[strlen(s) + 1];
732 strcpy(lines[nb_lines], s);
734 // The string was already in there, so we do not allocate a
735 // new string but use the pointer to the first occurence of it
736 lines[nb_lines] = lines[dup];
746 // Now remove the null strings
749 for(int k = 0; k < nb_lines; k++) {
751 lines[n++] = lines[k];
758 for(int i = 0; i < nb_lines / 2; i++) {
759 char *s = lines[nb_lines - 1 - i];
760 lines[nb_lines - 1 - i] = lines[i];
765 char pattern[buffer_size];
770 //////////////////////////////////////////////////////////////////////
771 // Here we start to display with curse
780 // So that the arrow keys work
781 keypad(stdscr, TRUE);
786 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
787 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
788 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
789 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
793 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
796 init_pair(1, color_fg_modeline, color_bg_modeline);
797 init_pair(2, color_fg_highlight, color_bg_highlight);
798 init_pair(3, color_bg_modeline, color_fg_modeline);
805 int current_line = 0, temporary_line = 0;
807 update_screen(¤t_line, &temporary_line, 0, nb_lines, lines, cursor_position, pattern);
815 if(key >= ' ' && key <= '~') { // Insert character
816 insert_char(pattern, &cursor_position, key);
819 else if(key == KEY_BACKSPACE ||
820 key == '\010' || // ^H
821 key == '\177') { // ^?
822 backspace_char(pattern, &cursor_position);
825 else if(key == KEY_DC ||
826 key == '\004') { // ^D
827 delete_char(pattern, &cursor_position);
830 else if(key == KEY_HOME) {
834 else if(key == KEY_END) {
835 current_line = nb_lines - 1;
838 else if(key == KEY_NPAGE) {
842 else if(key == KEY_PPAGE) {
846 else if(key == KEY_DOWN ||
847 key == '\014') { // ^N
851 else if(key == KEY_UP ||
852 key == '\016') { // ^P
856 else if(key == KEY_LEFT ||
857 key == '\002') { // ^B
858 if(cursor_position > 0) cursor_position--;
861 else if(key == KEY_RIGHT ||
862 key == '\006') { // ^F
863 if(pattern[cursor_position]) cursor_position++;
866 else if(key == '\001') { // ^A
870 else if(key == '\005') { // ^E
871 cursor_position = strlen(pattern);
874 else if(key == '\022') { // ^R
875 use_regexp = !use_regexp;
878 else if(key == '\025') { // ^U
879 kill_before_cursor(pattern, &cursor_position);
882 else if(key == '\013') { // ^K
883 kill_after_cursor(pattern, &cursor_position);
886 update_screen(¤t_line, &temporary_line, motion,
887 nb_lines, lines, cursor_position, pattern);
889 } while(key != '\n' && key != KEY_ENTER && key != '\007'); // ^G
895 //////////////////////////////////////////////////////////////////////
896 // Here we come back to standard display
898 if((key == KEY_ENTER || key == '\n')) {
900 if(output_to_vt_buffer) {
901 if(temporary_line >= 0 && temporary_line < nb_lines) {
902 inject_into_tty_buffer(lines[temporary_line]);
906 if(output_filename[0]) {
907 ofstream out(output_filename);
909 cerr << "Can not open " << output_filename << " for writing." << endl;
912 if(temporary_line >= 0 && temporary_line < nb_lines) {
913 out << lines[temporary_line] << endl;
923 for(int l = 0; l < nb_lines; l++) {