Added the option to use a standard regexp. You can either activate it
[selector.git] / selector.cc
1
2 /*
3  *  selector is a simple shell command for selection of strings with a
4  *  dynamic pattern-matching.
5  *
6  *  Copyright (c) 2009 Francois Fleuret
7  *  Written by Francois Fleuret <francois@fleuret.org>
8  *
9  *  This file is part of selector.
10  *
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.
14  *
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.
19  *
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/>.
22  *
23  */
24
25 // To use it as a super-history-search for bash:
26 //
27 // alias h='./selector -i -b -v -f <(history)'
28
29 // This software is highly Linux-specific, but I would be glad to get
30 // patches to make it work on other OS
31
32 #include <fstream>
33 #include <iostream>
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <ncurses.h>
39 #include <fcntl.h>
40 #include <sys/ioctl.h>
41 #include <termios.h>
42 #include <regex.h>
43
44 using namespace std;
45
46 #define VERSION "1.0"
47
48 const int buffer_size = 1024;
49
50 // Yeah, global variables!
51
52 int nb_lines_max = 1000;
53 char pattern_separator = ';';
54 int output_to_vt_buffer = 0;
55 int with_colors = 1;
56 int zsh_history = 0, bash_history = 0;
57 int inverse_order = 0;
58 int remove_duplicates = 0;
59 int use_regexp = 0;
60
61 //////////////////////////////////////////////////////////////////////
62
63 // This looks severely Linux-only ...
64
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);
74   }
75   // Restore the old settings
76   tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
77 }
78
79 //////////////////////////////////////////////////////////////////////
80
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] << "."
84          << " "
85          << "Expecting " << help << "."
86          << endl;
87     exit(1);
88   }
89 }
90
91 //////////////////////////////////////////////////////////////////////
92 // A quick and dirty hash table
93
94 int *new_hash_table(int hash_table_size) {
95   int *result;
96   result = new int[hash_table_size];
97   for(int k = 0; k < hash_table_size; k++) {
98     result[k] = -1;
99   }
100   return result;
101 }
102
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;
106
107   for(int k = 0; new_string[k]; k++) {
108     code += int(new_string[k]) << (8 * k%4);
109   }
110
111   code = code % hash_table_size;
112
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;
116   }
117
118   hash_table[code] = new_index;
119
120   return 0;
121 }
122
123 //////////////////////////////////////////////////////////////////////
124 // A matcher matches either with a collection of substrings, or with a
125 // regexp
126
127 struct matcher_t {
128   regex_t preg;
129   int regexp_error;
130   int nb_patterns;
131   char *splitted_patterns, **patterns;
132 };
133
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;
138     }
139     return 1;
140   } else {
141     return regexec(&matcher->preg, string, 0, 0, 0) == 0;
142   }
143 }
144
145 void free_matcher(matcher_t *matcher) {
146   if(matcher->nb_patterns >= 0) {
147     delete[] matcher->splitted_patterns;
148     delete[] matcher->patterns;
149   } else {
150     if(!matcher->regexp_error) regfree(&matcher->preg);
151   }
152 }
153
154 void initialize_matcher(int use_regexp, matcher_t *matcher, const char *pattern) {
155   if(use_regexp) {
156     matcher->nb_patterns = -1;
157     matcher->regexp_error = regcomp(&matcher->preg, pattern, REG_ICASE);
158   } else {
159     matcher->regexp_error = 0;
160     matcher->nb_patterns = 1;
161
162     for(const char *s = pattern; *s; s++) {
163       if(*s == pattern_separator) {
164         matcher->nb_patterns++;
165       }
166     }
167
168     matcher->splitted_patterns = new char[strlen(pattern) + 1];
169     matcher->patterns = new char*[matcher->nb_patterns];
170
171     strcpy(matcher->splitted_patterns, pattern);
172
173     int n = 0;
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') {
177         *s = '\0';
178         matcher->patterns[n++] = last_pattern_start;
179         last_pattern_start = s + 1;
180       }
181     }
182   }
183 }
184
185 //////////////////////////////////////////////////////////////////////
186
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--;
190   return line;
191 }
192
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++;
196
197   if(line < nb_lines)
198     return line;
199   else
200     return -1;
201 }
202
203 //////////////////////////////////////////////////////////////////////
204
205 void update_screen(int *current_line, int *temporary_line, int motion,
206                    int nb_lines, char **lines,
207                    char *pattern_list) {
208
209   char buffer[buffer_size];
210   matcher_t matcher;
211
212   initialize_matcher(use_regexp, &matcher, pattern_list);
213
214   // We now take care of printing the lines per se
215
216   int console_width = getmaxx(stdscr);
217   int console_height = getmaxy(stdscr);
218
219   // First, we find a visible line. In priority: The current, or the
220   // first visible after it, or the first visible before it.
221
222   int nb_printed_lines = 0;
223
224   clear();
225   use_default_colors();
226   addstr("\n");
227
228   if(matcher.regexp_error) {
229     addstr("[regexp error]");
230   } else {
231
232     int new_line;
233     if(match(lines[*current_line], &matcher)) {
234       new_line = *current_line;
235     } else {
236       new_line = next_visible(*current_line, nb_lines, lines, &matcher);
237       if(new_line < 0) {
238         new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
239       }
240     }
241
242     // If we found a visible line and we should move, let's move
243
244     if(new_line >= 0 && motion != 0) {
245       int l = new_line;
246       if(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);
250           if(l >= 0) {
251             new_line = l;
252           }
253         }
254       } else {
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);
258           if(l >= 0) {
259             new_line = l;
260           }
261         }
262       }
263     }
264
265     // Here new_line is either a line number matching the patterns, or -1
266
267     if(new_line >= 0) {
268
269       int first_line = new_line, last_line = new_line, nb_match = 1;
270
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
273
274       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
275
276         if(first_line > 0) {
277           first_line--;
278           while(first_line > 0 && !match(lines[first_line], &matcher)) {
279             first_line--;
280           }
281           if(match(lines[first_line], &matcher)) {
282             nb_match++;
283           }
284         }
285
286         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
287           last_line++;
288           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
289             last_line++;
290           }
291
292           if(match(lines[last_line], &matcher)) {
293             nb_match++;
294           }
295         }
296       }
297
298       // Now we display them
299
300       for(int l = first_line; l <= last_line; l++) {
301         if(match(lines[l], &matcher)) {
302           int k = 0;
303
304           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
305             buffer[k] = lines[l][k];
306             k++;
307           }
308
309           // We fill the rest of the line with blanks if either we did
310           // not clear() or if this is the highlighted line
311
312           if(l == new_line) {
313             while(k < console_width) {
314               buffer[k++] = ' ';
315             }
316           }
317
318           buffer[k++] = '\n';
319           buffer[k++] = '\0';
320
321           // Highlight the highlighted line ...
322
323           if(l == new_line) {
324             if(with_colors) {
325               attron(COLOR_PAIR(2));
326               addnstr(buffer, console_width);
327               attroff(COLOR_PAIR(2));
328             } else {
329               attron(A_STANDOUT);
330               addnstr(buffer, console_width);
331               attroff(A_STANDOUT);
332             }
333           } else {
334             addnstr(buffer, console_width);
335           }
336
337           nb_printed_lines++;
338         }
339       }
340
341       if(motion != 0) {
342         *current_line = new_line;
343       }
344     }
345
346     *temporary_line = new_line;
347
348     if(nb_printed_lines == 0) {
349       addnstr("[no selection]\n", console_width);
350     }
351   }
352
353   // Draw the modeline
354
355   sprintf(buffer, "%d/%d pattern: %s%s",
356           nb_printed_lines,
357           nb_lines,
358           pattern_list,
359           use_regexp ? " [regexp]" : "");
360
361   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
362   buffer[console_width] = '\0';
363
364   move(0, 0);
365   if(with_colors) {
366     attron(COLOR_PAIR(1));
367     addnstr(buffer, console_width);
368     attroff(COLOR_PAIR(1));
369   } else {
370     attron(A_REVERSE);
371     addnstr(buffer, console_width);
372     attroff(A_REVERSE);
373   }
374
375   // We are done
376
377   refresh();
378   free_matcher(&matcher);
379 }
380
381 //////////////////////////////////////////////////////////////////////
382
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;
387
388   color_fg_modeline  = COLOR_WHITE;
389   color_bg_modeline  = COLOR_BLACK;
390   color_fg_highlight = COLOR_BLACK;
391   color_bg_highlight = COLOR_YELLOW;
392
393   setlocale(LC_ALL, "");
394
395   char input_filename[buffer_size], output_filename[buffer_size];
396
397   strcpy(input_filename, "");
398   strcpy(output_filename, "");
399
400   int i = 1;
401   while(i < argc) {
402
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);
406       i += 2;
407     }
408
409     else if(strcmp(argv[i], "-s") == 0) {
410       check_opt(argc, argv, i, 1, "<pattern separator>");
411       pattern_separator = argv[i+1][0];
412       i += 2;
413     }
414
415     else if(strcmp(argv[i], "-v") == 0) {
416       output_to_vt_buffer = 1;
417       i++;
418     }
419
420     else if(strcmp(argv[i], "-m") == 0) {
421       with_colors = 0;
422       i++;
423     }
424
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);
428       i += 2;
429     }
430
431     else if(strcmp(argv[i], "-i") == 0) {
432       inverse_order = 1;
433       i++;
434     }
435
436     else if(strcmp(argv[i], "-z") == 0) {
437       zsh_history = 1;
438       i++;
439     }
440
441     else if(strcmp(argv[i], "-b") == 0) {
442       bash_history = 1;
443       i++;
444     }
445
446     else if(strcmp(argv[i], "-d") == 0) {
447       remove_duplicates = 1;
448       i++;
449     }
450
451     else if(strcmp(argv[i], "-e") == 0) {
452       use_regexp = 1;
453       i++;
454     }
455
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]);
459       i += 2;
460     }
461
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]);
468       i += 5;
469     }
470
471     else {
472       cerr << "Selector version " << VERSION
473            << endl
474            << "Written by Francois Fleuret <francois@fleuret.org>"
475            << endl
476            << argv[0]
477            << " [-h]"
478            << " [-v]"
479            << " [-m]"
480            << " [-d]"
481            << " [-e]"
482            << " [-z]"
483            << " [-i]"
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>"
489            << endl;
490       if(strcmp(argv[i], "-h") == 0) {
491         exit(0);
492       } else {
493         exit(1);
494       }
495     }
496   }
497
498   char **lines = new char *[nb_lines_max];
499
500   if(!input_filename[0]) {
501     cerr << "You must specify a input file with -f." << endl;
502     exit(1);
503   }
504
505   int nb_lines = 0;
506
507   ifstream file(input_filename);
508
509   if(file.fail()) {
510     cerr << "Can not open " << input_filename << endl;
511     return 1;
512   }
513
514   int hash_table_size = nb_lines_max * 10;
515   int *hash_table = 0;
516
517   if(remove_duplicates) {
518     hash_table = new_hash_table(hash_table_size);
519   }
520
521   while(nb_lines < nb_lines_max && !file.eof()) {
522     file.getline(buffer, buffer_size);
523     if(strcmp(buffer, "") != 0) {
524       char *s = buffer;
525
526       if(zsh_history && *s == ':') {
527         while(*s && *s != ';') s++;
528         if(*s == ';') s++;
529       }
530
531       if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
532         while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
533       }
534
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);
538         nb_lines++;
539       }
540     }
541   }
542
543   delete[] hash_table;
544
545   if(inverse_order) {
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];
549       lines[i] = s;
550     }
551   }
552
553   char patterns[buffer_size];
554   patterns[0] = '\0';
555   int patterns_point;
556   patterns_point = 0;
557
558   initscr();
559
560   if(with_colors) {
561     if(has_colors()) {
562       start_color();
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) {
567         echo();
568         curs_set(1);
569         endwin();
570         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
571         exit(1);
572       }
573       init_pair(1, color_fg_modeline, color_bg_modeline);
574       init_pair(2, color_fg_highlight, color_bg_highlight);
575     } else {
576       with_colors = 0;
577     }
578   }
579
580   noecho();
581   curs_set(0); // Hide the cursor
582   keypad(stdscr, TRUE); // So that the arrow keys work
583
584   int key;
585   int current_line = 0, temporary_line = 0;
586
587   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns);
588
589   do {
590
591     key = getch();
592
593     int motion = 0;
594
595     if(key >= ' ' && key <= '~') {
596       patterns[patterns_point++] = key;
597       patterns[patterns_point] = '\0';
598     }
599
600     else if(key == KEY_BACKSPACE || key == '\b' || key == '\7f' ||
601             key == KEY_DC || key == '\ 4') {
602       if(patterns_point > 0) {
603         patterns_point--;
604         patterns[patterns_point] = '\0';
605       }
606     }
607
608     else if(key == KEY_HOME) {
609       current_line = 0;
610     }
611
612     else if(key == KEY_END) {
613       current_line = nb_lines - 1;
614     }
615
616     else if(key == KEY_NPAGE) {
617       motion = 10;
618     }
619
620     else if(key == KEY_PPAGE) {
621       motion = -10;
622     }
623
624     else if(key == KEY_UP || key == '\10') {
625       motion = -1;
626     }
627
628     else if(key == '\12') {
629       use_regexp = !use_regexp;
630     }
631
632     else if(key == KEY_DOWN || key == '\ e') {
633       motion = 1;
634     }
635
636     update_screen(&current_line, &temporary_line, motion,
637                   nb_lines, lines, patterns);
638
639   } while(key != '\n' && key != KEY_ENTER && key != '\a');
640
641   echo();
642   curs_set(1);
643   endwin();
644
645   if((key == KEY_ENTER || key == '\n')) {
646
647     if(output_to_vt_buffer) {
648       if(temporary_line >= 0 && temporary_line < nb_lines) {
649         inject_into_tty_buffer(lines[temporary_line]);
650       }
651     }
652
653     if(output_filename[0]) {
654       ofstream out(output_filename);
655       if(out.fail()) {
656         cerr << "Can not open " << output_filename << " for writing." << endl;
657         exit(1);
658       } else {
659         if(temporary_line >= 0 && temporary_line < nb_lines) {
660           out << lines[temporary_line] << endl;
661         } else {
662           out << endl;
663         }
664       }
665       out.flush();
666     }
667
668   }
669
670   for(int l = 0; l < nb_lines; l++) {
671     delete[] lines[l];
672   }
673
674   delete[] lines;
675
676   exit(0);
677 }