3 * selector is a simple command line utility for selection of strings
4 * with a 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 // selector -q -b -i -d -v -w -l 10000 <(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 char label_separator = '\0';
51 int output_to_vt_buffer = 0;
52 int add_control_qs = 0;
56 int inverse_order = 0;
57 int remove_duplicates = 0;
59 int case_sensitive = 0;
63 #define COLOR_MODELINE 1
64 #define COLOR_FOCUS_LINE 2
67 int attr_modeline, attr_focus_line, attr_error;
69 //////////////////////////////////////////////////////////////////////
71 void inject_into_tty_buffer(char *string) {
72 struct termios oldtio, newtio;
73 tcgetattr(STDIN_FILENO, &oldtio);
74 memset(&newtio, 0, sizeof(newtio));
75 // Set input mode (non-canonical, *no echo*,...)
76 tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
77 const char control_q = '\021';
78 // Put the selected string in the tty input buffer
79 for(const char *k = string; *k; k++) {
80 if(add_control_qs && !(*k >= ' ' && *k <= '~')) {
81 // Add ^Q to quote control characters
82 ioctl(STDIN_FILENO, TIOCSTI, &control_q);
84 ioctl(STDIN_FILENO, TIOCSTI, k);
86 // Restore the old settings
87 tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
90 //////////////////////////////////////////////////////////////////////
92 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
93 if(n_opt + n >= argc) {
94 cerr << "Missing argument for " << argv[n_opt] << "."
96 << "Expecting " << help << "."
102 int string_to_positive_integer(char *string) {
107 for(char *s = string; *s; s++) {
108 if(*s >= '0' && *s <= '9') {
109 result = result * 10 + int(*s - '0');
115 cerr << "Value `" << string << "' is not a positive integer." << endl;
122 void error_feedback() {
130 //////////////////////////////////////////////////////////////////////
131 // A quick and dirty hash table
133 // The table itself stores index of the strings in a char
134 // **table. When a string is added, if it was already in the table,
135 // the new index replaces the previous one.
137 int *new_hash_table(int hash_table_size) {
139 result = new int[hash_table_size];
140 for(int k = 0; k < hash_table_size; k++) {
146 // Adds new_string in the table, associated to new_index. If this
147 // string was not already in the table, returns -1. Otherwise, returns
148 // the previous index it had.
150 int test_and_add(char *new_string, int new_index,
151 char **strings, int *hash_table, int hash_table_size) {
153 unsigned int code = 0;
155 // This is my recipe. I checked, it seems to work (as long as
156 // hash_table_size is not a multiple of 387433 that should be okay)
158 for(int k = 0; new_string[k]; k++) {
159 code = code * 387433 + (unsigned int) (new_string[k]);
162 code = code % hash_table_size;
164 while(hash_table[code] >= 0) {
165 // There is a string with that code
166 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
167 // It is the same string, we keep a copy of the stored index
168 int result = hash_table[code];
170 hash_table[code] = new_index;
171 // And return the previous one
174 // This collision was not the same string, let's move to the next
176 code = (code + 1) % hash_table_size;
179 // This string was not already in there, store the index in the
180 // table and return -1
181 hash_table[code] = new_index;
185 //////////////////////////////////////////////////////////////////////
186 // A matcher matches either with a collection of substrings, or with a
194 char *splitted_patterns, **patterns;
197 int match(char *string, matcher_t *matcher) {
198 if(matcher->nb_patterns >= 0) {
199 if(matcher->case_sensitive) {
200 for(int n = 0; n < matcher->nb_patterns; n++) {
201 if(strstr(string, matcher->patterns[n]) == 0) return 0;
204 for(int n = 0; n < matcher->nb_patterns; n++) {
205 if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
210 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
214 void free_matcher(matcher_t *matcher) {
215 if(matcher->nb_patterns < 0) {
216 if(!matcher->regexp_error) regfree(&matcher->preg);
218 delete[] matcher->splitted_patterns;
219 delete[] matcher->patterns;
223 void initialize_matcher(int use_regexp, int case_sensitive,
224 matcher_t *matcher, const char *pattern) {
227 matcher->nb_patterns = -1;
228 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
230 matcher->regexp_error = 0;
231 matcher->nb_patterns = 1;
232 matcher->case_sensitive = case_sensitive;
234 for(const char *s = pattern; *s; s++) {
235 if(*s == pattern_separator) {
236 matcher->nb_patterns++;
240 matcher->splitted_patterns = new char[strlen(pattern) + 1];
241 matcher->patterns = new char*[matcher->nb_patterns];
243 strcpy(matcher->splitted_patterns, pattern);
246 char *last_pattern_start = matcher->splitted_patterns;
247 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
248 if(*s == pattern_separator || *s == '\0') {
250 matcher->patterns[n++] = last_pattern_start;
251 last_pattern_start = s + 1;
257 //////////////////////////////////////////////////////////////////////
260 void delete_char(char *buffer, int *position) {
261 if(buffer[*position]) {
263 while(c < buffer_size && buffer[c]) {
264 buffer[c] = buffer[c+1];
267 } else error_feedback();
270 void backspace_char(char *buffer, int *position) {
272 if(buffer[*position]) {
273 int c = *position - 1;
275 buffer[c] = buffer[c+1];
279 buffer[*position - 1] = '\0';
283 } else error_feedback();
286 void insert_char(char *buffer, int *position, char character) {
287 if(strlen(buffer) < buffer_size - 1) {
289 char t = buffer[c], u;
298 buffer[(*position)++] = character;
299 } else error_feedback();
302 void kill_before_cursor(char *buffer, int *position) {
304 while(buffer[*position + s]) {
305 buffer[s] = buffer[*position + s];
312 void kill_after_cursor(char *buffer, int *position) {
313 buffer[*position] = '\0';
316 //////////////////////////////////////////////////////////////////////
318 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
319 int line = current_line - 1;
320 while(line >= 0 && !match(lines[line], matcher)) line--;
324 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
325 int line = current_line + 1;
326 while(line < nb_lines && !match(lines[line], matcher)) line++;
334 //////////////////////////////////////////////////////////////////////
336 // The value passed to this routine in current_focus_line is the index
337 // of the line to highlighted if it matches the matcher. The line
338 // highlighted is the first the one matching the matcher in that
339 // order: The current_focus_line itself, the first with a greated
340 // index, the first with a lesser index.
342 // The index of the line actually shown highlighted is written in
343 // displayed_focus_line (it can be -1)
345 // If there is a motion and a line is actually shown highlighted, its
346 // value is written in current_focus_line
348 void update_screen(int *current_focus_line, int *displayed_focus_line,
350 int nb_lines, char **lines,
354 char buffer[buffer_size];
357 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
359 int console_width = getmaxx(stdscr);
360 int console_height = getmaxy(stdscr);
362 // First, we find a visible line. In priority: The current, or the
363 // first visible after it, or the first visible before it.
365 int nb_printed_lines = 0;
367 use_default_colors();
370 if(matcher.regexp_error) {
372 addnstr("Regexp syntax error", console_width);
374 } else if(nb_lines > 0) {
376 if(match(lines[*current_focus_line], &matcher)) {
377 new_focus_line = *current_focus_line;
379 new_focus_line = next_visible(*current_focus_line, nb_lines, lines, &matcher);
380 if(new_focus_line < 0) {
381 new_focus_line = previous_visible(*current_focus_line, nb_lines, lines, &matcher);
385 // If we found a visible line and we should move, let's move
387 if(new_focus_line >= 0 && motion != 0) {
388 int l = new_focus_line;
390 // We want to go down, let's find the first visible line below
391 for(int m = 0; l >= 0 && m < motion; m++) {
392 l = next_visible(l, nb_lines, lines, &matcher);
398 // We want to go up, let's find the first visible line above
399 for(int m = 0; l >= 0 && m < -motion; m++) {
400 l = previous_visible(l, nb_lines, lines, &matcher);
408 // Here new_focus_line is either a line number matching the pattern, or -1
410 if(new_focus_line >= 0) {
412 int first_line = new_focus_line, last_line = new_focus_line, nb_match = 1;
414 // We find the first and last line to show, so that the total of
415 // visible lines between them (them included) is console_height-1
417 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
421 while(first_line > 0 && !match(lines[first_line], &matcher)) {
424 if(match(lines[first_line], &matcher)) {
429 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
431 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
435 if(match(lines[last_line], &matcher)) {
441 // Now we display them
443 for(int l = first_line; l <= last_line; l++) {
444 if(match(lines[l], &matcher)) {
447 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
448 buffer[k] = lines[l][k];
452 // We fill the rest of the line with blanks if this is the
455 if(l == new_focus_line) {
456 while(k < console_width) {
466 // Highlight the highlighted line ...
468 if(l == new_focus_line) {
469 attron(attr_focus_line);
470 addnstr(buffer, console_width);
471 attroff(attr_focus_line);
473 addnstr(buffer, console_width);
480 // If we are on a focused line and we moved, this become the new
484 *current_focus_line = new_focus_line;
488 *displayed_focus_line = new_focus_line;
490 if(nb_printed_lines == 0) {
492 addnstr("No selection", console_width);
497 addnstr("Empty choice", console_width);
507 attron(attr_modeline);
509 for(int k = 0; k < console_width; k++) buffer[k] = ' ';
510 buffer[console_width] = '\0';
511 addnstr(buffer, console_width);
515 // There must be a more elegant way of moving the cursor at a
516 // location met during display
523 cursor_x += strlen(title) + 1;
526 sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
528 cursor_x += strlen(buffer);
530 addnstr(pattern, cursor_position);
531 cursor_x += cursor_position;
533 if(pattern[cursor_position]) {
534 addstr(pattern + cursor_position);
539 if(use_regexp || case_sensitive) {
556 attroff(attr_modeline);
561 free_matcher(&matcher);
564 //////////////////////////////////////////////////////////////////////
566 void read_file(const char *input_filename,
567 int nb_lines_max, int *nb_lines, char **lines,
568 int hash_table_size, int *hash_table) {
570 char raw_line[buffer_size];;
572 ifstream file(input_filename);
575 cerr << "Can not open " << input_filename << endl;
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;
595 // Remove the zsh history prefix
597 if(zsh_history && *t == ':') {
598 while(*t && *t != ';') t++;
602 // Remove the bash history prefix
605 while(*t == ' ') t++;
606 while(*t >= '0' && *t <= '9') t++;
607 while(*t == ' ') t++;
610 // Check for duplicates with the hash table and insert the line
611 // in the list if necessary
616 dup = test_and_add(t, *nb_lines, lines, hash_table, hash_table_size);
622 lines[*nb_lines] = new char[strlen(t) + 1];
623 strcpy(lines[*nb_lines], t);
625 // The string was already in there, so we do not allocate a
626 // new string but use the pointer to the first occurence of it
627 lines[*nb_lines] = lines[dup];
636 //////////////////////////////////////////////////////////////////////
638 int main(int argc, char **argv) {
640 if(!ttyname(STDIN_FILENO)) {
641 cerr << "The standard input is not a tty." << endl;
645 int color_fg_modeline, color_bg_modeline;
646 int color_fg_highlight, color_bg_highlight;
648 color_fg_modeline = COLOR_WHITE;
649 color_bg_modeline = COLOR_BLACK;
650 color_fg_highlight = COLOR_BLACK;
651 color_bg_highlight = COLOR_YELLOW;
653 setlocale(LC_ALL, "");
655 char input_filename[buffer_size], output_filename[buffer_size];
657 strcpy(input_filename, "");
658 strcpy(output_filename, "");
661 int error = 0, show_help = 0;
662 int rest_are_files = 0;
664 while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
666 if(strcmp(argv[i], "-o") == 0) {
667 check_opt(argc, argv, i, 1, "<output filename>");
668 strncpy(output_filename, argv[i+1], buffer_size);
672 else if(strcmp(argv[i], "-s") == 0) {
673 check_opt(argc, argv, i, 1, "<pattern separator>");
674 pattern_separator = argv[i+1][0];
678 else if(strcmp(argv[i], "-x") == 0) {
679 check_opt(argc, argv, i, 1, "<label separator>");
680 label_separator = argv[i+1][0];
684 else if(strcmp(argv[i], "-v") == 0) {
685 output_to_vt_buffer = 1;
689 else if(strcmp(argv[i], "-w") == 0) {
694 else if(strcmp(argv[i], "-m") == 0) {
699 else if(strcmp(argv[i], "-q") == 0) {
704 else if(strcmp(argv[i], "-f") == 0) {
705 check_opt(argc, argv, i, 1, "<input filename>");
706 strncpy(input_filename, argv[i+1], buffer_size);
710 else if(strcmp(argv[i], "-i") == 0) {
715 else if(strcmp(argv[i], "-b") == 0) {
720 else if(strcmp(argv[i], "-z") == 0) {
725 else if(strcmp(argv[i], "-d") == 0) {
726 remove_duplicates = 1;
730 else if(strcmp(argv[i], "-e") == 0) {
735 else if(strcmp(argv[i], "-a") == 0) {
740 else if(strcmp(argv[i], "-t") == 0) {
741 check_opt(argc, argv, i, 1, "<title>");
743 title = new char[strlen(argv[i+1]) + 1];
744 strcpy(title, argv[i+1]);
748 else if(strcmp(argv[i], "-l") == 0) {
749 check_opt(argc, argv, i, 1, "<maximum number of lines>");
750 nb_lines_max = string_to_positive_integer(argv[i+1]);
754 else if(strcmp(argv[i], "-c") == 0) {
755 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
756 color_fg_modeline = string_to_positive_integer(argv[i + 1]);
757 color_bg_modeline = string_to_positive_integer(argv[i + 2]);
758 color_fg_highlight = string_to_positive_integer(argv[i + 3]);
759 color_bg_highlight = string_to_positive_integer(argv[i + 4]);
763 else if(strcmp(argv[i], "--") == 0) {
768 else if(strcmp(argv[i], "-h") == 0) {
774 cerr << "Unknown option " << argv[i] << "." << endl;
779 if(show_help || error) {
780 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
782 << "Written by Francois Fleuret <francois@fleuret.org>."
785 << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
787 << " -h show this help" << endl
788 << " -v inject the selected line in the tty" << endl
789 << " -w quote control characters with ^Qs when using -v" << endl
790 << " -d remove duplicated lines" << endl
791 << " -b remove the bash history line prefix" << endl
792 << " -z remove the zsh history line prefix" << endl
793 << " -i invert the order of lines" << endl
794 << " -e start in regexp mode" << endl
795 << " -a case sensitive" << endl
796 << " -m monochrome mode" << endl
797 << " -q make a flash instead of a beep on an edition error" << endl
798 << " -- all following arguments are filenames" << endl
799 << " -t <title>" << endl
800 << " add a title in the modeline" << endl
801 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
802 << " set the display colors" << endl
803 << " -o <output filename>" << endl
804 << " set a file to write the selected line to" << endl
805 << " -s <pattern separator>" << endl
806 << " set the symbol to separate substrings in the pattern" << endl
807 << " -x <label separator>" << endl
808 << " set the symbol to terminate the label" << endl
809 << " -l <max number of lines>" << endl
810 << " set the maximum number of lines to take into account" << endl
816 char **lines = new char *[nb_lines_max];
819 int hash_table_size = nb_lines_max * 10;
822 if(remove_duplicates) {
823 hash_table = new_hash_table(hash_table_size);
826 if(input_filename[0]) {
827 read_file(input_filename,
828 nb_lines_max, &nb_lines, lines,
829 hash_table_size, hash_table);
834 nb_lines_max, &nb_lines, lines,
835 hash_table_size, hash_table);
841 // Now remove the null strings
844 for(int k = 0; k < nb_lines; k++) {
846 lines[n++] = lines[k];
853 for(int i = 0; i < nb_lines / 2; i++) {
854 char *s = lines[nb_lines - 1 - i];
855 lines[nb_lines - 1 - i] = lines[i];
860 // Build the labels from the strings, take only the part before the
861 // label_separator and transform control characters to printable
864 char **labels = new char *[nb_lines];
865 for(int l = 0; l < nb_lines; l++) {
870 while(*t && *t != label_separator) {
874 labels[l] = new char[e + 1];
877 while(*t && *t != label_separator) {
879 while(*u) { *s++ = *u++; }
884 char pattern[buffer_size];
890 //////////////////////////////////////////////////////////////////////
891 // Here we start to display with curse
897 // So that the arrow keys work
898 keypad(stdscr, TRUE);
900 attr_error = A_STANDOUT;
901 attr_modeline = A_REVERSE;
902 attr_focus_line = A_STANDOUT;
904 if(with_colors && has_colors()) {
908 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
909 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
910 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
911 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
914 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
918 init_pair(COLOR_MODELINE, color_fg_modeline, color_bg_modeline);
919 init_pair(COLOR_FOCUS_LINE, color_fg_highlight, color_bg_highlight);
920 init_pair(COLOR_ERROR, COLOR_WHITE, COLOR_RED);
922 attr_modeline = COLOR_PAIR(COLOR_MODELINE);
923 attr_focus_line = COLOR_PAIR(COLOR_FOCUS_LINE);
924 attr_error = COLOR_PAIR(COLOR_ERROR);
929 int current_focus_line = 0, displayed_focus_line = 0;
931 update_screen(¤t_focus_line, &displayed_focus_line,
933 nb_lines, labels, cursor_position, pattern);
941 if(key >= ' ' && key <= '~') { // Insert character
942 insert_char(pattern, &cursor_position, key);
945 else if(key == KEY_BACKSPACE ||
946 key == '\010' || // ^H
947 key == '\177') { // ^?
948 backspace_char(pattern, &cursor_position);
951 else if(key == KEY_DC ||
952 key == '\004') { // ^D
953 delete_char(pattern, &cursor_position);
956 else if(key == KEY_HOME) {
957 current_focus_line = 0;
960 else if(key == KEY_END) {
961 current_focus_line = nb_lines - 1;
964 else if(key == KEY_NPAGE) {
968 else if(key == KEY_PPAGE) {
972 else if(key == KEY_DOWN ||
973 key == '\016') { // ^N
977 else if(key == KEY_UP ||
978 key == '\020') { // ^P
982 else if(key == KEY_LEFT ||
983 key == '\002') { // ^B
984 if(cursor_position > 0) cursor_position--;
985 else error_feedback();
988 else if(key == KEY_RIGHT ||
989 key == '\006') { // ^F
990 if(pattern[cursor_position]) cursor_position++;
991 else error_feedback();
994 else if(key == '\001') { // ^A
998 else if(key == '\005') { // ^E
999 cursor_position = strlen(pattern);
1002 else if(key == '\022') { // ^R
1003 use_regexp = !use_regexp;
1006 else if(key == '\011') { // ^I
1007 case_sensitive = !case_sensitive;
1010 else if(key == '\025') { // ^U
1011 kill_before_cursor(pattern, &cursor_position);
1014 else if(key == '\013') { // ^K
1015 kill_after_cursor(pattern, &cursor_position);
1018 else if(key == '\014') { // ^L
1019 // I suspect that we may sometime mess up the display
1023 update_screen(¤t_focus_line, &displayed_focus_line,
1025 nb_lines, labels, cursor_position, pattern);
1027 } while(key != '\007' && // ^G
1028 key != '\033' && // ^[ (escape)
1035 //////////////////////////////////////////////////////////////////////
1036 // Here we come back to standard display
1038 if((key == KEY_ENTER || key == '\n')) {
1040 if(output_to_vt_buffer) {
1041 if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1042 inject_into_tty_buffer(lines[displayed_focus_line]);
1046 if(output_filename[0]) {
1047 ofstream out(output_filename);
1049 cerr << "Can not open " << output_filename << " for writing." << endl;
1052 if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1053 out << lines[displayed_focus_line] << endl;
1061 cout << "Aborted." << endl;
1064 for(int l = 0; l < nb_lines; l++) {