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 #define COLOR_MODELINE 1
60 #define COLOR_HIGHLIGHTED_LINE 2
62 //////////////////////////////////////////////////////////////////////
64 void inject_into_tty_buffer(char *string) {
65 struct termios oldtio, newtio;
66 tcgetattr(STDIN_FILENO, &oldtio);
67 memset(&newtio, 0, sizeof(newtio));
68 // Set input mode (non-canonical, *no echo*,...)
69 tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
70 // Put the selected string in the tty input buffer
71 for(char *k = string; *k; k++) {
72 ioctl(STDIN_FILENO, TIOCSTI, k);
74 // Restore the old settings
75 tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
78 //////////////////////////////////////////////////////////////////////
80 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
81 if(n_opt + n >= argc) {
82 cerr << "Missing argument for " << argv[n_opt] << "."
84 << "Expecting " << help << "."
90 int string_to_positive_integer(char *string) {
95 for(char *s = string; *s; s++) {
96 if(*s >= '0' && *s <= '9') {
97 result = result * 10 + int(*s - '0');
103 cerr << "Value `" << string << "' is not a positive integer." << endl;
110 //////////////////////////////////////////////////////////////////////
111 // A quick and dirty hash table
113 // The table itself stores index of the strings in a char
114 // **table. When a string is added, if it was already in the table,
115 // the new index replaces the previous one.
117 int *new_hash_table(int hash_table_size) {
119 result = new int[hash_table_size];
120 for(int k = 0; k < hash_table_size; k++) {
126 // Adds new_string in the table, associated to new_index. If this
127 // string was not already in the table, returns -1. Otherwise, returns
128 // the previous index it had.
130 int test_and_add(char *new_string, int new_index,
131 char **strings, int *hash_table, int hash_table_size) {
132 unsigned int code = 0;
134 // This is my recipe. I checked, it seems to work (as long as
135 // hash_table_size is not a multiple of 387433 that should be okay)
137 for(int k = 0; new_string[k]; k++) {
138 code = code * 387433 + (unsigned int) (new_string[k]);
141 code = code % hash_table_size;
143 while(hash_table[code] >= 0) {
144 // There is a string with that code
145 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
146 // It is the same string, we keep a copy of the stored index
147 int result = hash_table[code];
149 hash_table[code] = new_index;
150 // And return the previous one
153 // This collision was not the same string, let's move to the next
155 code = (code + 1) % hash_table_size;
158 // This string was not already in there, store the index in the
159 // table and return -1
160 hash_table[code] = new_index;
164 //////////////////////////////////////////////////////////////////////
165 // A matcher matches either with a collection of substrings, or with a
173 char *splitted_patterns, **patterns;
176 int match(char *string, matcher_t *matcher) {
177 if(matcher->nb_patterns >= 0) {
178 if(matcher->case_sensitive) {
179 for(int n = 0; n < matcher->nb_patterns; n++) {
180 if(strstr(string, matcher->patterns[n]) == 0) return 0;
183 for(int n = 0; n < matcher->nb_patterns; n++) {
184 if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
189 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
193 void free_matcher(matcher_t *matcher) {
194 if(matcher->nb_patterns >= 0) {
195 delete[] matcher->splitted_patterns;
196 delete[] matcher->patterns;
198 if(!matcher->regexp_error) regfree(&matcher->preg);
202 void initialize_matcher(int use_regexp, int case_sensitive,
203 matcher_t *matcher, const char *pattern) {
206 matcher->nb_patterns = -1;
207 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
209 matcher->regexp_error = 0;
210 matcher->nb_patterns = 1;
211 matcher->case_sensitive = case_sensitive;
213 for(const char *s = pattern; *s; s++) {
214 if(*s == pattern_separator) {
215 matcher->nb_patterns++;
219 matcher->splitted_patterns = new char[strlen(pattern) + 1];
220 matcher->patterns = new char*[matcher->nb_patterns];
222 strcpy(matcher->splitted_patterns, pattern);
225 char *last_pattern_start = matcher->splitted_patterns;
226 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
227 if(*s == pattern_separator || *s == '\0') {
229 matcher->patterns[n++] = last_pattern_start;
230 last_pattern_start = s + 1;
236 //////////////////////////////////////////////////////////////////////
239 void delete_char(char *buffer, int *position) {
240 if(buffer[*position]) {
242 while(c < buffer_size && buffer[c]) {
243 buffer[c] = buffer[c+1];
249 void backspace_char(char *buffer, int *position) {
251 if(buffer[*position]) {
252 int c = *position - 1;
254 buffer[c] = buffer[c+1];
258 buffer[*position - 1] = '\0';
265 void insert_char(char *buffer, int *position, char character) {
266 if(strlen(buffer) < buffer_size - 1) {
268 char t = buffer[c], u;
277 buffer[(*position)++] = character;
281 void kill_before_cursor(char *buffer, int *position) {
283 while(buffer[*position + s]) {
284 buffer[s] = buffer[*position + s];
291 void kill_after_cursor(char *buffer, int *position) {
292 buffer[*position] = '\0';
295 //////////////////////////////////////////////////////////////////////
297 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
298 int line = current_line - 1;
299 while(line >= 0 && !match(lines[line], matcher)) line--;
303 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
304 int line = current_line + 1;
305 while(line < nb_lines && !match(lines[line], matcher)) line++;
313 //////////////////////////////////////////////////////////////////////
315 void update_screen(int *current_line, int *temporary_line, int motion,
316 int nb_lines, char **lines,
320 char buffer[buffer_size];
323 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
325 // We now take care of printing the lines per se
327 int console_width = getmaxx(stdscr);
328 int console_height = getmaxy(stdscr);
330 // First, we find a visible line. In priority: The current, or the
331 // first visible after it, or the first visible before it.
333 int nb_printed_lines = 0;
336 use_default_colors();
339 if(matcher.regexp_error) {
340 addstr("[regexp error]");
341 } else if(nb_lines > 0) {
343 if(match(lines[*current_line], &matcher)) {
344 new_line = *current_line;
346 new_line = next_visible(*current_line, nb_lines, lines, &matcher);
348 new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
352 // If we found a visible line and we should move, let's move
354 if(new_line >= 0 && motion != 0) {
357 // We want to go down, let's find the first visible line below
358 for(int m = 0; l >= 0 && m < motion; m++) {
359 l = next_visible(l, nb_lines, lines, &matcher);
365 // We want to go up, let's find the first visible line above
366 for(int m = 0; l >= 0 && m < -motion; m++) {
367 l = previous_visible(l, nb_lines, lines, &matcher);
375 // Here new_line is either a line number matching the patterns, or -1
379 int first_line = new_line, last_line = new_line, nb_match = 1;
381 // We find the first and last line to show, so that the total of
382 // visible lines between them (them include) is console_height - 1
384 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
388 while(first_line > 0 && !match(lines[first_line], &matcher)) {
391 if(match(lines[first_line], &matcher)) {
396 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
398 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
402 if(match(lines[last_line], &matcher)) {
408 // Now we display them
410 for(int l = first_line; l <= last_line; l++) {
411 if(match(lines[l], &matcher)) {
414 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
415 buffer[k] = lines[l][k];
419 // We fill the rest of the line with blanks if either we did
420 // not clear() or if this is the highlighted line
423 while(k < console_width) {
431 // Highlight the highlighted line ...
435 attron(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
436 addnstr(buffer, console_width);
437 attroff(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
440 addnstr(buffer, console_width);
444 addnstr(buffer, console_width);
452 *current_line = new_line;
456 *temporary_line = new_line;
458 if(nb_printed_lines == 0) {
459 addnstr("[no selection]\n", console_width);
462 addnstr("[empty choice]\n", console_width);
470 attron(COLOR_PAIR(COLOR_MODELINE));
475 for(int k = 0; k < console_width; k++) buffer[k] = ' ';
476 buffer[console_width] = '\0';
477 addnstr(buffer, console_width);
481 // There must be a more elegant way of moving the cursor at a
482 // location met during display
489 cursor_x += strlen(title) + 1;
492 sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
494 cursor_x += strlen(buffer);
496 addnstr(pattern, cursor_position);
497 cursor_x += cursor_position;
499 if(pattern[cursor_position]) {
500 addstr(pattern + cursor_position);
505 if(use_regexp || case_sensitive) {
523 attroff(COLOR_PAIR(COLOR_MODELINE));
531 free_matcher(&matcher);
534 //////////////////////////////////////////////////////////////////////
536 void read_file(const char *input_filename,
537 int nb_lines_max, int *nb_lines, char **lines,
538 int hash_table_size, int *hash_table) {
540 char buffer[buffer_size], raw_line[buffer_size];;
542 ifstream file(input_filename);
545 cerr << "Can not open " << input_filename << endl;
549 while(*nb_lines < nb_lines_max && !file.eof()) {
551 file.getline(raw_line, buffer_size);
556 cerr << "Line too long:" << endl;
557 cerr << raw_line << endl;
568 while(*u) { *s++ = *u++; }
574 if(zsh_history && *s == ':') {
575 while(*s && *s != ';') s++;
579 if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
580 while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
586 dup = test_and_add(s, *nb_lines, lines, hash_table, hash_table_size);
592 lines[*nb_lines] = new char[strlen(s) + 1];
593 strcpy(lines[*nb_lines], s);
595 // The string was already in there, so we do not allocate a
596 // new string but use the pointer to the first occurence of it
597 lines[*nb_lines] = lines[dup];
606 //////////////////////////////////////////////////////////////////////
608 int main(int argc, char **argv) {
610 if(!ttyname(STDIN_FILENO)) {
611 cerr << "The standard input is not a tty." << endl;
615 int color_fg_modeline, color_bg_modeline;
616 int color_fg_highlight, color_bg_highlight;
618 color_fg_modeline = COLOR_WHITE;
619 color_bg_modeline = COLOR_BLACK;
620 color_fg_highlight = COLOR_BLACK;
621 color_bg_highlight = COLOR_YELLOW;
623 setlocale(LC_ALL, "");
625 char input_filename[buffer_size], output_filename[buffer_size];
627 strcpy(input_filename, "");
628 strcpy(output_filename, "");
631 int error = 0, show_help = 0;
632 int rest_are_files = 0;
634 while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
636 if(strcmp(argv[i], "-o") == 0) {
637 check_opt(argc, argv, i, 1, "<output filename>");
638 strncpy(output_filename, argv[i+1], buffer_size);
642 else if(strcmp(argv[i], "-s") == 0) {
643 check_opt(argc, argv, i, 1, "<pattern separator>");
644 pattern_separator = argv[i+1][0];
648 else if(strcmp(argv[i], "-v") == 0) {
649 output_to_vt_buffer = 1;
653 else if(strcmp(argv[i], "-m") == 0) {
658 else if(strcmp(argv[i], "-f") == 0) {
659 check_opt(argc, argv, i, 1, "<input filename>");
660 strncpy(input_filename, argv[i+1], buffer_size);
664 else if(strcmp(argv[i], "-i") == 0) {
669 else if(strcmp(argv[i], "-b") == 0) {
674 else if(strcmp(argv[i], "-z") == 0) {
679 else if(strcmp(argv[i], "-d") == 0) {
680 remove_duplicates = 1;
684 else if(strcmp(argv[i], "-e") == 0) {
689 else if(strcmp(argv[i], "-a") == 0) {
694 else if(strcmp(argv[i], "-t") == 0) {
695 check_opt(argc, argv, i, 1, "<title>");
697 title = new char[strlen(argv[i+1]) + 1];
698 strcpy(title, argv[i+1]);
702 else if(strcmp(argv[i], "-l") == 0) {
703 check_opt(argc, argv, i, 1, "<maximum number of lines>");
704 nb_lines_max = string_to_positive_integer(argv[i+1]);
708 else if(strcmp(argv[i], "-c") == 0) {
709 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
710 color_fg_modeline = string_to_positive_integer(argv[i + 1]);
711 color_bg_modeline = string_to_positive_integer(argv[i + 2]);
712 color_fg_highlight = string_to_positive_integer(argv[i + 3]);
713 color_bg_highlight = string_to_positive_integer(argv[i + 4]);
717 else if(strcmp(argv[i], "--") == 0) {
722 else if(strcmp(argv[i], "-h") == 0) {
728 cerr << "Unknown option " << argv[i] << "." << endl;
733 if(show_help || error) {
734 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
736 << "Written by Francois Fleuret <francois@fleuret.org>."
739 << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
741 << " -h show this help" << endl
742 << " -v inject the selected line in the tty" << endl
743 << " -d remove duplicated lines" << endl
744 << " -b remove the bash history line prefix" << endl
745 << " -z remove the zsh history line prefix" << endl
746 << " -i invert the order of lines" << endl
747 << " -e start in regexp mode" << endl
748 << " -a case sensitive" << endl
749 << " -m monochrome mode" << endl
750 << " -- rest of the arguments are filenames" << endl
751 << " -t <title>" << endl
752 << " add a title in the modeline" << endl
753 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
754 << " set the display colors" << endl
755 << " -o <output filename>" << endl
756 << " set a file to write the selected line to" << endl
757 << " -s <pattern separator>" << endl
758 << " set the symbol to separate substrings in the pattern" << endl
759 << " -l <max number of lines>" << endl
760 << " set the maximum number of lines to take into account" << endl
766 char **lines = new char *[nb_lines_max];
769 int hash_table_size = nb_lines_max * 10;
772 if(remove_duplicates) {
773 hash_table = new_hash_table(hash_table_size);
776 // if(i == argc && !input_filename[0]) {
777 // cerr << "You must provide a filename." << endl;
781 if(input_filename[0]) {
782 read_file(input_filename,
783 nb_lines_max, &nb_lines, lines,
784 hash_table_size, hash_table);
789 nb_lines_max, &nb_lines, lines,
790 hash_table_size, hash_table);
796 // Now remove the null strings
799 for(int k = 0; k < nb_lines; k++) {
801 lines[n++] = lines[k];
808 for(int i = 0; i < nb_lines / 2; i++) {
809 char *s = lines[nb_lines - 1 - i];
810 lines[nb_lines - 1 - i] = lines[i];
815 char pattern[buffer_size];
820 //////////////////////////////////////////////////////////////////////
821 // Here we start to display with curse
830 // So that the arrow keys work
831 keypad(stdscr, TRUE);
836 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
837 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
838 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
839 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
843 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
846 init_pair(COLOR_MODELINE , color_fg_modeline, color_bg_modeline);
847 init_pair(COLOR_HIGHLIGHTED_LINE, color_fg_highlight, color_bg_highlight);
854 int current_line = 0, temporary_line = 0;
856 update_screen(¤t_line, &temporary_line, 0, nb_lines, lines, cursor_position, pattern);
864 if(key >= ' ' && key <= '~') { // Insert character
865 insert_char(pattern, &cursor_position, key);
868 else if(key == KEY_BACKSPACE ||
869 key == '\010' || // ^H
870 key == '\177') { // ^?
871 backspace_char(pattern, &cursor_position);
874 else if(key == KEY_DC ||
875 key == '\004') { // ^D
876 delete_char(pattern, &cursor_position);
879 else if(key == KEY_HOME) {
883 else if(key == KEY_END) {
884 current_line = nb_lines - 1;
887 else if(key == KEY_NPAGE) {
891 else if(key == KEY_PPAGE) {
895 else if(key == KEY_DOWN ||
896 key == '\016') { // ^N
900 else if(key == KEY_UP ||
901 key == '\020') { // ^P
905 else if(key == KEY_LEFT ||
906 key == '\002') { // ^B
907 if(cursor_position > 0) cursor_position--;
910 else if(key == KEY_RIGHT ||
911 key == '\006') { // ^F
912 if(pattern[cursor_position]) cursor_position++;
915 else if(key == '\001') { // ^A
919 else if(key == '\005') { // ^E
920 cursor_position = strlen(pattern);
923 else if(key == '\022') { // ^R
924 use_regexp = !use_regexp;
927 else if(key == '\011') { // ^I
928 case_sensitive = !case_sensitive;
931 else if(key == '\025') { // ^U
932 kill_before_cursor(pattern, &cursor_position);
935 else if(key == '\013') { // ^K
936 kill_after_cursor(pattern, &cursor_position);
939 update_screen(¤t_line, &temporary_line, motion,
940 nb_lines, lines, cursor_position, pattern);
942 } while(key != '\n' && key != KEY_ENTER && key != '\007'); // ^G
948 //////////////////////////////////////////////////////////////////////
949 // Here we come back to standard display
951 if((key == KEY_ENTER || key == '\n')) {
953 if(output_to_vt_buffer) {
954 if(temporary_line >= 0 && temporary_line < nb_lines) {
955 inject_into_tty_buffer(lines[temporary_line]);
959 if(output_filename[0]) {
960 ofstream out(output_filename);
962 cerr << "Can not open " << output_filename << " for writing." << endl;
965 if(temporary_line >= 0 && temporary_line < nb_lines) {
966 out << lines[temporary_line] << endl;
974 cout << "Aborted." << endl;
977 for(int l = 0; l < nb_lines; l++) {