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 int string_to_positive_integer(char *string) {
92 for(char *s = string; *s; s++) {
93 if(*s >= '0' && *s <= '9') {
94 result = result * 10 + int(*s - '0');
100 cerr << "Value `" << string << "' is not a positive integer." << endl;
107 //////////////////////////////////////////////////////////////////////
108 // A quick and dirty hash table
110 // The table itself stores index of the strings in a char
111 // **table. When a string is added, if it was already in the table,
112 // the new index replaces the previous one.
114 int *new_hash_table(int hash_table_size) {
116 result = new int[hash_table_size];
117 for(int k = 0; k < hash_table_size; k++) {
123 // Adds new_string in the table, associated to new_index. If this
124 // string was not already in the table, returns -1. Otherwise, returns
125 // the previous index it had.
127 int test_and_add(char *new_string, int new_index,
128 char **strings, int *hash_table, int hash_table_size) {
129 unsigned int code = 0;
131 // This is my recipe. I checked, it seems to work (as long as
132 // hash_table_size is not a multiple of 387433 that should be okay)
134 for(int k = 0; new_string[k]; k++) {
135 code = code * 387433 + (unsigned int) (new_string[k]);
138 code = code % hash_table_size;
140 while(hash_table[code] >= 0) {
141 // There is a string with that code
142 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
143 // It is the same string, we keep a copy of the stored index
144 int result = hash_table[code];
146 hash_table[code] = new_index;
147 // And return the previous one
150 // This collision was not the same string, let's move to the next
152 code = (code + 1) % hash_table_size;
155 // This string was not already in there, store the index in the
156 // table and return -1
157 hash_table[code] = new_index;
161 //////////////////////////////////////////////////////////////////////
162 // A matcher matches either with a collection of substrings, or with a
170 char *splitted_patterns, **patterns;
173 int match(char *string, matcher_t *matcher) {
174 if(matcher->nb_patterns >= 0) {
175 if(matcher->case_sensitive) {
176 for(int n = 0; n < matcher->nb_patterns; n++) {
177 if(strstr(string, matcher->patterns[n]) == 0) return 0;
180 for(int n = 0; n < matcher->nb_patterns; n++) {
181 if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
186 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
190 void free_matcher(matcher_t *matcher) {
191 if(matcher->nb_patterns >= 0) {
192 delete[] matcher->splitted_patterns;
193 delete[] matcher->patterns;
195 if(!matcher->regexp_error) regfree(&matcher->preg);
199 void initialize_matcher(int use_regexp, int case_sensitive,
200 matcher_t *matcher, const char *pattern) {
203 matcher->nb_patterns = -1;
204 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
206 matcher->regexp_error = 0;
207 matcher->nb_patterns = 1;
208 matcher->case_sensitive = case_sensitive;
210 for(const char *s = pattern; *s; s++) {
211 if(*s == pattern_separator) {
212 matcher->nb_patterns++;
216 matcher->splitted_patterns = new char[strlen(pattern) + 1];
217 matcher->patterns = new char*[matcher->nb_patterns];
219 strcpy(matcher->splitted_patterns, pattern);
222 char *last_pattern_start = matcher->splitted_patterns;
223 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
224 if(*s == pattern_separator || *s == '\0') {
226 matcher->patterns[n++] = last_pattern_start;
227 last_pattern_start = s + 1;
233 //////////////////////////////////////////////////////////////////////
236 void delete_char(char *buffer, int *position) {
237 if(buffer[*position]) {
239 while(c < buffer_size && buffer[c]) {
240 buffer[c] = buffer[c+1];
246 void backspace_char(char *buffer, int *position) {
248 if(buffer[*position]) {
249 int c = *position - 1;
251 buffer[c] = buffer[c+1];
255 buffer[*position - 1] = '\0';
262 void insert_char(char *buffer, int *position, char character) {
263 if(strlen(buffer) < buffer_size - 1) {
265 char t = buffer[c], u;
274 buffer[(*position)++] = character;
278 void kill_before_cursor(char *buffer, int *position) {
280 while(buffer[*position + s]) {
281 buffer[s] = buffer[*position + s];
288 void kill_after_cursor(char *buffer, int *position) {
289 buffer[*position] = '\0';
292 //////////////////////////////////////////////////////////////////////
294 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
295 int line = current_line - 1;
296 while(line >= 0 && !match(lines[line], matcher)) line--;
300 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
301 int line = current_line + 1;
302 while(line < nb_lines && !match(lines[line], matcher)) line++;
310 //////////////////////////////////////////////////////////////////////
312 void update_screen(int *current_line, int *temporary_line, int motion,
313 int nb_lines, char **lines,
317 char buffer[buffer_size];
320 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
322 // We now take care of printing the lines per se
324 int console_width = getmaxx(stdscr);
325 int console_height = getmaxy(stdscr);
327 // First, we find a visible line. In priority: The current, or the
328 // first visible after it, or the first visible before it.
330 int nb_printed_lines = 0;
333 use_default_colors();
336 if(matcher.regexp_error) {
337 addstr("[regexp error]");
338 } else if(nb_lines > 0) {
340 if(match(lines[*current_line], &matcher)) {
341 new_line = *current_line;
343 new_line = next_visible(*current_line, nb_lines, lines, &matcher);
345 new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
349 // If we found a visible line and we should move, let's move
351 if(new_line >= 0 && motion != 0) {
354 // We want to go down, let's find the first visible line below
355 for(int m = 0; l >= 0 && m < motion; m++) {
356 l = next_visible(l, nb_lines, lines, &matcher);
362 // We want to go up, let's find the first visible line above
363 for(int m = 0; l >= 0 && m < -motion; m++) {
364 l = previous_visible(l, nb_lines, lines, &matcher);
372 // Here new_line is either a line number matching the patterns, or -1
376 int first_line = new_line, last_line = new_line, nb_match = 1;
378 // We find the first and last line to show, so that the total of
379 // visible lines between them (them include) is console_height - 1
381 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
385 while(first_line > 0 && !match(lines[first_line], &matcher)) {
388 if(match(lines[first_line], &matcher)) {
393 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
395 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
399 if(match(lines[last_line], &matcher)) {
405 // Now we display them
407 for(int l = first_line; l <= last_line; l++) {
408 if(match(lines[l], &matcher)) {
411 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
412 buffer[k] = lines[l][k];
416 // We fill the rest of the line with blanks if either we did
417 // not clear() or if this is the highlighted line
420 while(k < console_width) {
428 // Highlight the highlighted line ...
432 attron(COLOR_PAIR(2));
433 addnstr(buffer, console_width);
434 attroff(COLOR_PAIR(2));
437 addnstr(buffer, console_width);
441 addnstr(buffer, console_width);
449 *current_line = new_line;
453 *temporary_line = new_line;
455 if(nb_printed_lines == 0) {
456 addnstr("[no selection]\n", console_width);
459 addnstr("[empty choice]\n", console_width);
467 attron(COLOR_PAIR(1));
472 for(int k = 0; k < console_width; k++) buffer[k] = ' ';
473 buffer[console_width] = '\0';
474 addnstr(buffer, console_width);
478 // There must be a more elegant way of moving the cursor at a
479 // location met during display
486 cursor_x += strlen(title) + 1;
489 sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
491 cursor_x += strlen(buffer);
493 addnstr(pattern, cursor_position);
494 cursor_x += cursor_position;
496 if(pattern[cursor_position]) {
497 addstr(pattern + cursor_position);
513 attroff(COLOR_PAIR(1));
521 free_matcher(&matcher);
524 //////////////////////////////////////////////////////////////////////
526 void read_file(const char *input_filename,
527 int nb_lines_max, int *nb_lines, char **lines,
528 int hash_table_size, int *hash_table) {
530 char buffer[buffer_size], raw_line[buffer_size];;
532 ifstream file(input_filename);
535 cerr << "Can not open " << input_filename << endl;
539 while(*nb_lines < nb_lines_max && !file.eof()) {
541 file.getline(raw_line, buffer_size);
546 cerr << "Line too long:" << endl;
547 cerr << raw_line << endl;
558 while(*u) { *s++ = *u++; }
564 if(zsh_history && *s == ':') {
565 while(*s && *s != ';') s++;
569 if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
570 while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
576 dup = test_and_add(s, *nb_lines, lines, hash_table, hash_table_size);
582 lines[*nb_lines] = new char[strlen(s) + 1];
583 strcpy(lines[*nb_lines], s);
585 // The string was already in there, so we do not allocate a
586 // new string but use the pointer to the first occurence of it
587 lines[*nb_lines] = lines[dup];
596 //////////////////////////////////////////////////////////////////////
598 int main(int argc, char **argv) {
600 if(!ttyname(STDIN_FILENO)) {
601 cerr << "The standard input is not a tty." << endl;
605 int color_fg_modeline, color_bg_modeline;
606 int color_fg_highlight, color_bg_highlight;
608 color_fg_modeline = COLOR_WHITE;
609 color_bg_modeline = COLOR_BLACK;
610 color_fg_highlight = COLOR_BLACK;
611 color_bg_highlight = COLOR_YELLOW;
613 setlocale(LC_ALL, "");
615 char input_filename[buffer_size], output_filename[buffer_size];
617 strcpy(input_filename, "");
618 strcpy(output_filename, "");
621 int error = 0, show_help = 0;
622 int rest_are_files = 0;
624 while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
626 if(strcmp(argv[i], "-o") == 0) {
627 check_opt(argc, argv, i, 1, "<output filename>");
628 strncpy(output_filename, argv[i+1], buffer_size);
632 else if(strcmp(argv[i], "-s") == 0) {
633 check_opt(argc, argv, i, 1, "<pattern separator>");
634 pattern_separator = argv[i+1][0];
638 else if(strcmp(argv[i], "-v") == 0) {
639 output_to_vt_buffer = 1;
643 else if(strcmp(argv[i], "-m") == 0) {
648 else if(strcmp(argv[i], "-f") == 0) {
649 check_opt(argc, argv, i, 1, "<input filename>");
650 strncpy(input_filename, argv[i+1], buffer_size);
654 else if(strcmp(argv[i], "-i") == 0) {
659 else if(strcmp(argv[i], "-b") == 0) {
664 else if(strcmp(argv[i], "-z") == 0) {
669 else if(strcmp(argv[i], "-d") == 0) {
670 remove_duplicates = 1;
674 else if(strcmp(argv[i], "-e") == 0) {
679 else if(strcmp(argv[i], "-a") == 0) {
684 else if(strcmp(argv[i], "-t") == 0) {
685 check_opt(argc, argv, i, 1, "<title>");
687 title = new char[strlen(argv[i+1]) + 1];
688 strcpy(title, argv[i+1]);
692 else if(strcmp(argv[i], "-l") == 0) {
693 check_opt(argc, argv, i, 1, "<maximum number of lines>");
694 nb_lines_max = string_to_positive_integer(argv[i+1]);
698 else if(strcmp(argv[i], "-c") == 0) {
699 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
700 color_fg_modeline = string_to_positive_integer(argv[i + 1]);
701 color_bg_modeline = string_to_positive_integer(argv[i + 2]);
702 color_fg_highlight = string_to_positive_integer(argv[i + 3]);
703 color_bg_highlight = string_to_positive_integer(argv[i + 4]);
707 else if(strcmp(argv[i], "--") == 0) {
712 else if(strcmp(argv[i], "-h") == 0) {
718 cerr << "Unknown option " << argv[i] << "." << endl;
723 if(show_help || error) {
724 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
726 << "Written by Francois Fleuret <francois@fleuret.org>."
729 << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
731 << " -h show this help" << endl
732 << " -v inject the selected line in the tty" << endl
733 << " -d remove duplicated lines" << endl
734 << " -b remove the bash history line prefix" << endl
735 << " -z remove the zsh history line prefix" << endl
736 << " -i invert the order of lines" << endl
737 << " -e start in regexp mode" << endl
738 << " -a case sensitive" << endl
739 << " -m monochrome mode" << endl
740 << " -- rest of the arguments are filenames" << endl
741 << " -t <title>" << endl
742 << " add a title in the modeline" << endl
743 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
744 << " set the display colors" << endl
745 << " -o <output filename>" << endl
746 << " set a file to write the selected line to" << endl
747 << " -s <pattern separator>" << endl
748 << " set the symbol to separate substrings in the pattern" << endl
749 << " -l <max number of lines>" << endl
750 << " set the maximum number of lines to take into account" << endl
756 char **lines = new char *[nb_lines_max];
759 int hash_table_size = nb_lines_max * 10;
762 if(remove_duplicates) {
763 hash_table = new_hash_table(hash_table_size);
766 // if(i == argc && !input_filename[0]) {
767 // cerr << "You must provide a filename." << endl;
771 if(input_filename[0]) {
772 read_file(input_filename,
773 nb_lines_max, &nb_lines, lines,
774 hash_table_size, hash_table);
779 nb_lines_max, &nb_lines, lines,
780 hash_table_size, hash_table);
786 // Now remove the null strings
789 for(int k = 0; k < nb_lines; k++) {
791 lines[n++] = lines[k];
798 for(int i = 0; i < nb_lines / 2; i++) {
799 char *s = lines[nb_lines - 1 - i];
800 lines[nb_lines - 1 - i] = lines[i];
805 char pattern[buffer_size];
810 //////////////////////////////////////////////////////////////////////
811 // Here we start to display with curse
820 // So that the arrow keys work
821 keypad(stdscr, TRUE);
826 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
827 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
828 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
829 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
833 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
836 init_pair(1, color_fg_modeline, color_bg_modeline);
837 init_pair(2, color_fg_highlight, color_bg_highlight);
838 init_pair(3, color_bg_modeline, color_fg_modeline);
845 int current_line = 0, temporary_line = 0;
847 update_screen(¤t_line, &temporary_line, 0, nb_lines, lines, cursor_position, pattern);
855 if(key >= ' ' && key <= '~') { // Insert character
856 insert_char(pattern, &cursor_position, key);
859 else if(key == KEY_BACKSPACE ||
860 key == '\010' || // ^H
861 key == '\177') { // ^?
862 backspace_char(pattern, &cursor_position);
865 else if(key == KEY_DC ||
866 key == '\004') { // ^D
867 delete_char(pattern, &cursor_position);
870 else if(key == KEY_HOME) {
874 else if(key == KEY_END) {
875 current_line = nb_lines - 1;
878 else if(key == KEY_NPAGE) {
882 else if(key == KEY_PPAGE) {
886 else if(key == KEY_DOWN ||
887 key == '\016') { // ^N
891 else if(key == KEY_UP ||
892 key == '\020') { // ^P
896 else if(key == KEY_LEFT ||
897 key == '\002') { // ^B
898 if(cursor_position > 0) cursor_position--;
901 else if(key == KEY_RIGHT ||
902 key == '\006') { // ^F
903 if(pattern[cursor_position]) cursor_position++;
906 else if(key == '\001') { // ^A
910 else if(key == '\005') { // ^E
911 cursor_position = strlen(pattern);
914 else if(key == '\022') { // ^R
915 use_regexp = !use_regexp;
918 else if(key == '\011') { // ^I
919 case_sensitive = !case_sensitive;
922 else if(key == '\025') { // ^U
923 kill_before_cursor(pattern, &cursor_position);
926 else if(key == '\013') { // ^K
927 kill_after_cursor(pattern, &cursor_position);
930 update_screen(¤t_line, &temporary_line, motion,
931 nb_lines, lines, cursor_position, pattern);
933 } while(key != '\n' && key != KEY_ENTER && key != '\007'); // ^G
939 //////////////////////////////////////////////////////////////////////
940 // Here we come back to standard display
942 if((key == KEY_ENTER || key == '\n')) {
944 if(output_to_vt_buffer) {
945 if(temporary_line >= 0 && temporary_line < nb_lines) {
946 inject_into_tty_buffer(lines[temporary_line]);
950 if(output_filename[0]) {
951 ofstream out(output_filename);
953 cerr << "Can not open " << output_filename << " for writing." << endl;
956 if(temporary_line >= 0 && temporary_line < nb_lines) {
957 out << lines[temporary_line] << endl;
965 cout << "Aborted." << endl;
968 for(int l = 0; l < nb_lines; l++) {