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:
27 // alias h='./selector -i -b -v -f <(history)'
29 // This software is highly Linux-specific, but I would be glad to get
30 // patches to make it work on other OS
40 #include <sys/ioctl.h>
48 const int buffer_size = 1024;
50 // Yeah, global variables!
52 int nb_lines_max = 1000;
53 char pattern_separator = ';';
54 int output_to_vt_buffer = 0;
56 int zsh_history = 0, bash_history = 0;
57 int inverse_order = 0;
58 int remove_duplicates = 0;
61 //////////////////////////////////////////////////////////////////////
63 // This looks severely Linux-only ...
65 void inject_into_tty_buffer(char *line) {
66 struct termios oldtio, newtio;
67 tcgetattr(STDIN_FILENO,&oldtio);
68 memset(&newtio, 0, sizeof(newtio));
69 // Set input mode (non-canonical, *no echo*,...)
70 tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
71 // Put the selected line in the tty input buffer
72 for(char *k = line; *k; k++) {
73 ioctl(STDIN_FILENO, TIOCSTI, k);
75 // Restore the old settings
76 tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
79 //////////////////////////////////////////////////////////////////////
81 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
82 if(n_opt + n >= argc) {
83 cerr << "Missing argument for " << argv[n_opt] << "."
85 << "Expecting " << help << "."
91 //////////////////////////////////////////////////////////////////////
92 // A quick and dirty hash table
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 int test_and_add(char *new_string, int new_index,
104 char **strings, int *hash_table, int hash_table_size) {
105 unsigned int code = 0;
107 for(int k = 0; new_string[k]; k++) {
108 code += int(new_string[k]) << (8 * k%4);
111 code = code % hash_table_size;
113 while(hash_table[code] >= 0) {
114 if(strcmp(new_string, strings[hash_table[code]]) == 0) return 1;
115 code = (code + 1) % hash_table_size;
118 hash_table[code] = new_index;
123 //////////////////////////////////////////////////////////////////////
124 // A matcher matches either with a collection of substrings, or with a
131 char *splitted_patterns, **patterns;
134 int match(char *string, matcher_t *matcher) {
135 if(matcher->nb_patterns >= 0) {
136 for(int n = 0; n < matcher->nb_patterns; n++) {
137 if(strstr(string, matcher->patterns[n]) == 0) return 0;
141 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
145 void free_matcher(matcher_t *matcher) {
146 if(matcher->nb_patterns >= 0) {
147 delete[] matcher->splitted_patterns;
148 delete[] matcher->patterns;
150 if(!matcher->regexp_error) regfree(&matcher->preg);
154 void initialize_matcher(int use_regexp, matcher_t *matcher, const char *pattern) {
156 matcher->nb_patterns = -1;
157 matcher->regexp_error = regcomp(&matcher->preg, pattern, REG_ICASE);
159 matcher->regexp_error = 0;
160 matcher->nb_patterns = 1;
162 for(const char *s = pattern; *s; s++) {
163 if(*s == pattern_separator) {
164 matcher->nb_patterns++;
168 matcher->splitted_patterns = new char[strlen(pattern) + 1];
169 matcher->patterns = new char*[matcher->nb_patterns];
171 strcpy(matcher->splitted_patterns, pattern);
174 char *last_pattern_start = matcher->splitted_patterns;
175 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
176 if(*s == pattern_separator || *s == '\0') {
178 matcher->patterns[n++] = last_pattern_start;
179 last_pattern_start = s + 1;
185 //////////////////////////////////////////////////////////////////////
187 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
188 int line = current_line - 1;
189 while(line >= 0 && !match(lines[line], matcher)) line--;
193 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
194 int line = current_line + 1;
195 while(line < nb_lines && !match(lines[line], matcher)) line++;
203 //////////////////////////////////////////////////////////////////////
205 void update_screen(int *current_line, int *temporary_line, int motion,
206 int nb_lines, char **lines,
207 char *pattern_list) {
209 char buffer[buffer_size];
212 initialize_matcher(use_regexp, &matcher, pattern_list);
214 // We now take care of printing the lines per se
216 int console_width = getmaxx(stdscr);
217 int console_height = getmaxy(stdscr);
219 // First, we find a visible line. In priority: The current, or the
220 // first visible after it, or the first visible before it.
222 int nb_printed_lines = 0;
225 use_default_colors();
228 if(matcher.regexp_error) {
229 addstr("[regexp error]");
233 if(match(lines[*current_line], &matcher)) {
234 new_line = *current_line;
236 new_line = next_visible(*current_line, nb_lines, lines, &matcher);
238 new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
242 // If we found a visible line and we should move, let's move
244 if(new_line >= 0 && motion != 0) {
247 // We want to go down, let's find the first visible line below
248 for(int m = 0; l >= 0 && m < motion; m++) {
249 l = next_visible(l, nb_lines, lines, &matcher);
255 // We want to go up, let's find the first visible line above
256 for(int m = 0; l >= 0 && m < -motion; m++) {
257 l = previous_visible(l, nb_lines, lines, &matcher);
265 // Here new_line is either a line number matching the patterns, or -1
269 int first_line = new_line, last_line = new_line, nb_match = 1;
271 // We find the first and last line to show, so that the total of
272 // visible lines between them (them include) is console_height - 1
274 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
278 while(first_line > 0 && !match(lines[first_line], &matcher)) {
281 if(match(lines[first_line], &matcher)) {
286 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
288 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
292 if(match(lines[last_line], &matcher)) {
298 // Now we display them
300 for(int l = first_line; l <= last_line; l++) {
301 if(match(lines[l], &matcher)) {
304 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
305 buffer[k] = lines[l][k];
309 // We fill the rest of the line with blanks if either we did
310 // not clear() or if this is the highlighted line
313 while(k < console_width) {
321 // Highlight the highlighted line ...
325 attron(COLOR_PAIR(2));
326 addnstr(buffer, console_width);
327 attroff(COLOR_PAIR(2));
330 addnstr(buffer, console_width);
334 addnstr(buffer, console_width);
342 *current_line = new_line;
346 *temporary_line = new_line;
348 if(nb_printed_lines == 0) {
349 addnstr("[no selection]\n", console_width);
355 sprintf(buffer, "%d/%d pattern: %s%s",
359 use_regexp ? " [regexp]" : "");
361 for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
362 buffer[console_width] = '\0';
366 attron(COLOR_PAIR(1));
367 addnstr(buffer, console_width);
368 attroff(COLOR_PAIR(1));
371 addnstr(buffer, console_width);
378 free_matcher(&matcher);
381 //////////////////////////////////////////////////////////////////////
383 int main(int argc, char **argv) {
384 char buffer[buffer_size];
385 int color_fg_modeline, color_bg_modeline;
386 int color_fg_highlight, color_bg_highlight;
388 color_fg_modeline = COLOR_WHITE;
389 color_bg_modeline = COLOR_BLACK;
390 color_fg_highlight = COLOR_BLACK;
391 color_bg_highlight = COLOR_YELLOW;
393 setlocale(LC_ALL, "");
395 char input_filename[buffer_size], output_filename[buffer_size];
397 strcpy(input_filename, "");
398 strcpy(output_filename, "");
403 if(strcmp(argv[i], "-o") == 0) {
404 check_opt(argc, argv, i, 1, "<output filename>");
405 strncpy(output_filename, argv[i+1], buffer_size);
409 else if(strcmp(argv[i], "-s") == 0) {
410 check_opt(argc, argv, i, 1, "<pattern separator>");
411 pattern_separator = argv[i+1][0];
415 else if(strcmp(argv[i], "-v") == 0) {
416 output_to_vt_buffer = 1;
420 else if(strcmp(argv[i], "-m") == 0) {
425 else if(strcmp(argv[i], "-f") == 0) {
426 check_opt(argc, argv, i, 1, "<input filename>");
427 strncpy(input_filename, argv[i+1], buffer_size);
431 else if(strcmp(argv[i], "-i") == 0) {
436 else if(strcmp(argv[i], "-z") == 0) {
441 else if(strcmp(argv[i], "-b") == 0) {
446 else if(strcmp(argv[i], "-d") == 0) {
447 remove_duplicates = 1;
451 else if(strcmp(argv[i], "-e") == 0) {
456 else if(strcmp(argv[i], "-l") == 0) {
457 check_opt(argc, argv, i, 1, "<maximum number of lines>");
458 nb_lines_max = atoi(argv[i+1]);
462 else if(strcmp(argv[i], "-c") == 0) {
463 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
464 color_fg_modeline = atoi(argv[i+1]);
465 color_bg_modeline = atoi(argv[i+2]);
466 color_fg_highlight = atoi(argv[i+3]);
467 color_bg_highlight = atoi(argv[i+4]);
472 cerr << "Selector version " << VERSION
474 << "Written by Francois Fleuret <francois@fleuret.org>"
484 << " [-c <fg modeline> <bg modeline> <fg highlight> <bg highlight>]"
485 << " [-o <output filename>]"
486 << " [-s <pattern separator>]"
487 << " [-l <max number of lines>]"
488 << " -f <input filename>"
490 if(strcmp(argv[i], "-h") == 0) {
498 char **lines = new char *[nb_lines_max];
500 if(!input_filename[0]) {
501 cerr << "You must specify a input file with -f." << endl;
507 ifstream file(input_filename);
510 cerr << "Can not open " << input_filename << endl;
514 int hash_table_size = nb_lines_max * 10;
517 if(remove_duplicates) {
518 hash_table = new_hash_table(hash_table_size);
521 while(nb_lines < nb_lines_max && !file.eof()) {
522 file.getline(buffer, buffer_size);
523 if(strcmp(buffer, "") != 0) {
526 if(zsh_history && *s == ':') {
527 while(*s && *s != ';') s++;
531 if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
532 while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
535 if(!hash_table || !test_and_add(s, nb_lines, lines, hash_table, hash_table_size)) {
536 lines[nb_lines] = new char[strlen(s) + 1];
537 strcpy(lines[nb_lines], s);
546 for(int i = 0; i < nb_lines/2; i++) {
547 char *s = lines[nb_lines - 1 - i];
548 lines[nb_lines - 1 - i] = lines[i];
553 char patterns[buffer_size];
563 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
564 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
565 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
566 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
570 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
573 init_pair(1, color_fg_modeline, color_bg_modeline);
574 init_pair(2, color_fg_highlight, color_bg_highlight);
581 curs_set(0); // Hide the cursor
582 keypad(stdscr, TRUE); // So that the arrow keys work
585 int current_line = 0, temporary_line = 0;
587 update_screen(¤t_line, &temporary_line, 0, nb_lines, lines, patterns);
595 if(key >= ' ' && key <= '~') {
596 patterns[patterns_point++] = key;
597 patterns[patterns_point] = '\0';
600 else if(key == KEY_BACKSPACE || key == '
\b' || key == '
\7f' ||
601 key == KEY_DC || key == '
\ 4') {
602 if(patterns_point > 0) {
604 patterns[patterns_point] = '\0';
608 else if(key == KEY_HOME) {
612 else if(key == KEY_END) {
613 current_line = nb_lines - 1;
616 else if(key == KEY_NPAGE) {
620 else if(key == KEY_PPAGE) {
624 else if(key == KEY_UP || key == '
\10') {
628 else if(key == '
\12') {
629 use_regexp = !use_regexp;
632 else if(key == KEY_DOWN || key == '
\ e') {
636 update_screen(¤t_line, &temporary_line, motion,
637 nb_lines, lines, patterns);
639 } while(key != '\n' && key != KEY_ENTER && key != '
\a');
645 if((key == KEY_ENTER || key == '\n')) {
647 if(output_to_vt_buffer) {
648 if(temporary_line >= 0 && temporary_line < nb_lines) {
649 inject_into_tty_buffer(lines[temporary_line]);
653 if(output_filename[0]) {
654 ofstream out(output_filename);
656 cerr << "Can not open " << output_filename << " for writing." << endl;
659 if(temporary_line >= 0 && temporary_line < nb_lines) {
660 out << lines[temporary_line] << endl;
670 for(int l = 0; l < nb_lines; l++) {