Fixed a comment.
[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 -d -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   // This is my recipe. I checked, it seems to work (as long as
108   // hash_table_size is not a multiple of 387433 that should be okay)
109
110   for(int k = 0; new_string[k]; k++) {
111     code = code * 387433 + (unsigned int) (new_string[k]);
112   }
113
114   code = code % hash_table_size;
115
116   while(hash_table[code] >= 0) {
117     if(strcmp(new_string, strings[hash_table[code]]) == 0) return 1;
118     code = (code + 1) % hash_table_size;
119   }
120
121   hash_table[code] = new_index;
122
123   return 0;
124 }
125
126 //////////////////////////////////////////////////////////////////////
127 // A matcher matches either with a collection of substrings, or with a
128 // regexp
129
130 struct matcher_t {
131   regex_t preg;
132   int regexp_error;
133   int nb_patterns;
134   char *splitted_patterns, **patterns;
135 };
136
137 int match(char *string, matcher_t *matcher) {
138   if(matcher->nb_patterns >= 0) {
139     for(int n = 0; n < matcher->nb_patterns; n++) {
140       if(strstr(string, matcher->patterns[n]) == 0) return 0;
141     }
142     return 1;
143   } else {
144     return regexec(&matcher->preg, string, 0, 0, 0) == 0;
145   }
146 }
147
148 void free_matcher(matcher_t *matcher) {
149   if(matcher->nb_patterns >= 0) {
150     delete[] matcher->splitted_patterns;
151     delete[] matcher->patterns;
152   } else {
153     if(!matcher->regexp_error) regfree(&matcher->preg);
154   }
155 }
156
157 void initialize_matcher(int use_regexp, matcher_t *matcher, const char *pattern) {
158   if(use_regexp) {
159     matcher->nb_patterns = -1;
160     matcher->regexp_error = regcomp(&matcher->preg, pattern, REG_ICASE);
161   } else {
162     matcher->regexp_error = 0;
163     matcher->nb_patterns = 1;
164
165     for(const char *s = pattern; *s; s++) {
166       if(*s == pattern_separator) {
167         matcher->nb_patterns++;
168       }
169     }
170
171     matcher->splitted_patterns = new char[strlen(pattern) + 1];
172     matcher->patterns = new char*[matcher->nb_patterns];
173
174     strcpy(matcher->splitted_patterns, pattern);
175
176     int n = 0;
177     char *last_pattern_start = matcher->splitted_patterns;
178     for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
179       if(*s == pattern_separator || *s == '\0') {
180         *s = '\0';
181         matcher->patterns[n++] = last_pattern_start;
182         last_pattern_start = s + 1;
183       }
184     }
185   }
186 }
187
188 //////////////////////////////////////////////////////////////////////
189
190 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
191   int line = current_line - 1;
192   while(line >= 0 && !match(lines[line], matcher)) line--;
193   return line;
194 }
195
196 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
197   int line = current_line + 1;
198   while(line < nb_lines && !match(lines[line], matcher)) line++;
199
200   if(line < nb_lines)
201     return line;
202   else
203     return -1;
204 }
205
206 //////////////////////////////////////////////////////////////////////
207
208 void update_screen(int *current_line, int *temporary_line, int motion,
209                    int nb_lines, char **lines,
210                    char *pattern_list) {
211
212   char buffer[buffer_size];
213   matcher_t matcher;
214
215   initialize_matcher(use_regexp, &matcher, pattern_list);
216
217   // We now take care of printing the lines per se
218
219   int console_width = getmaxx(stdscr);
220   int console_height = getmaxy(stdscr);
221
222   // First, we find a visible line. In priority: The current, or the
223   // first visible after it, or the first visible before it.
224
225   int nb_printed_lines = 0;
226
227   clear();
228   use_default_colors();
229   addstr("\n");
230
231   if(matcher.regexp_error) {
232     addstr("[regexp error]");
233   } else {
234
235     int new_line;
236     if(match(lines[*current_line], &matcher)) {
237       new_line = *current_line;
238     } else {
239       new_line = next_visible(*current_line, nb_lines, lines, &matcher);
240       if(new_line < 0) {
241         new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
242       }
243     }
244
245     // If we found a visible line and we should move, let's move
246
247     if(new_line >= 0 && motion != 0) {
248       int l = new_line;
249       if(motion > 0) {
250         // We want to go down, let's find the first visible line below
251         for(int m = 0; l >= 0 && m < motion; m++) {
252           l = next_visible(l, nb_lines, lines, &matcher);
253           if(l >= 0) {
254             new_line = l;
255           }
256         }
257       } else {
258         // We want to go up, let's find the first visible line above
259         for(int m = 0; l >= 0 && m < -motion; m++) {
260           l = previous_visible(l, nb_lines, lines, &matcher);
261           if(l >= 0) {
262             new_line = l;
263           }
264         }
265       }
266     }
267
268     // Here new_line is either a line number matching the patterns, or -1
269
270     if(new_line >= 0) {
271
272       int first_line = new_line, last_line = new_line, nb_match = 1;
273
274       // We find the first and last line to show, so that the total of
275       // visible lines between them (them include) is console_height - 1
276
277       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
278
279         if(first_line > 0) {
280           first_line--;
281           while(first_line > 0 && !match(lines[first_line], &matcher)) {
282             first_line--;
283           }
284           if(match(lines[first_line], &matcher)) {
285             nb_match++;
286           }
287         }
288
289         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
290           last_line++;
291           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
292             last_line++;
293           }
294
295           if(match(lines[last_line], &matcher)) {
296             nb_match++;
297           }
298         }
299       }
300
301       // Now we display them
302
303       for(int l = first_line; l <= last_line; l++) {
304         if(match(lines[l], &matcher)) {
305           int k = 0;
306
307           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
308             buffer[k] = lines[l][k];
309             k++;
310           }
311
312           // We fill the rest of the line with blanks if either we did
313           // not clear() or if this is the highlighted line
314
315           if(l == new_line) {
316             while(k < console_width) {
317               buffer[k++] = ' ';
318             }
319           }
320
321           buffer[k++] = '\n';
322           buffer[k++] = '\0';
323
324           // Highlight the highlighted line ...
325
326           if(l == new_line) {
327             if(with_colors) {
328               attron(COLOR_PAIR(2));
329               addnstr(buffer, console_width);
330               attroff(COLOR_PAIR(2));
331             } else {
332               attron(A_STANDOUT);
333               addnstr(buffer, console_width);
334               attroff(A_STANDOUT);
335             }
336           } else {
337             addnstr(buffer, console_width);
338           }
339
340           nb_printed_lines++;
341         }
342       }
343
344       if(motion != 0) {
345         *current_line = new_line;
346       }
347     }
348
349     *temporary_line = new_line;
350
351     if(nb_printed_lines == 0) {
352       addnstr("[no selection]\n", console_width);
353     }
354   }
355
356   // Draw the modeline
357
358   sprintf(buffer, "%d/%d pattern: %s%s",
359           nb_printed_lines,
360           nb_lines,
361           pattern_list,
362           use_regexp ? " [regexp]" : "");
363
364   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
365   buffer[console_width] = '\0';
366
367   move(0, 0);
368   if(with_colors) {
369     attron(COLOR_PAIR(1));
370     addnstr(buffer, console_width);
371     attroff(COLOR_PAIR(1));
372   } else {
373     attron(A_REVERSE);
374     addnstr(buffer, console_width);
375     attroff(A_REVERSE);
376   }
377
378   // We are done
379
380   refresh();
381   free_matcher(&matcher);
382 }
383
384 //////////////////////////////////////////////////////////////////////
385
386 int main(int argc, char **argv) {
387   char buffer[buffer_size];
388   int color_fg_modeline, color_bg_modeline;
389   int color_fg_highlight, color_bg_highlight;
390
391   color_fg_modeline  = COLOR_WHITE;
392   color_bg_modeline  = COLOR_BLACK;
393   color_fg_highlight = COLOR_BLACK;
394   color_bg_highlight = COLOR_YELLOW;
395
396   setlocale(LC_ALL, "");
397
398   char input_filename[buffer_size], output_filename[buffer_size];
399
400   strcpy(input_filename, "");
401   strcpy(output_filename, "");
402
403   int i = 1;
404   int error = 0, show_help = 0;
405
406   while(!error && !show_help && i < argc) {
407
408     if(strcmp(argv[i], "-o") == 0) {
409       check_opt(argc, argv, i, 1, "<output filename>");
410       strncpy(output_filename, argv[i+1], buffer_size);
411       i += 2;
412     }
413
414     else if(strcmp(argv[i], "-s") == 0) {
415       check_opt(argc, argv, i, 1, "<pattern separator>");
416       pattern_separator = argv[i+1][0];
417       i += 2;
418     }
419
420     else if(strcmp(argv[i], "-v") == 0) {
421       output_to_vt_buffer = 1;
422       i++;
423     }
424
425     else if(strcmp(argv[i], "-m") == 0) {
426       with_colors = 0;
427       i++;
428     }
429
430     else if(strcmp(argv[i], "-f") == 0) {
431       check_opt(argc, argv, i, 1, "<input filename>");
432       strncpy(input_filename, argv[i+1], buffer_size);
433       i += 2;
434     }
435
436     else if(strcmp(argv[i], "-i") == 0) {
437       inverse_order = 1;
438       i++;
439     }
440
441     else if(strcmp(argv[i], "-z") == 0) {
442       zsh_history = 1;
443       i++;
444     }
445
446     else if(strcmp(argv[i], "-b") == 0) {
447       bash_history = 1;
448       i++;
449     }
450
451     else if(strcmp(argv[i], "-d") == 0) {
452       remove_duplicates = 1;
453       i++;
454     }
455
456     else if(strcmp(argv[i], "-e") == 0) {
457       use_regexp = 1;
458       i++;
459     }
460
461     else if(strcmp(argv[i], "-l") == 0) {
462       check_opt(argc, argv, i, 1, "<maximum number of lines>");
463       nb_lines_max = atoi(argv[i+1]);
464       i += 2;
465     }
466
467     else if(strcmp(argv[i], "-c") == 0) {
468       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
469       color_fg_modeline = atoi(argv[i+1]);
470       color_bg_modeline = atoi(argv[i+2]);
471       color_fg_highlight = atoi(argv[i+3]);
472       color_bg_highlight = atoi(argv[i+4]);
473       i += 5;
474     }
475
476     else if(strcmp(argv[i], "-h") == 0) {
477       show_help = 1;
478       i++;
479     }
480
481     else {
482       cerr << "Unknown argument " << argv[i] << "." << endl;
483       error = 1;
484     }
485   }
486
487   if(show_help || error) {
488     cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
489          << endl
490          << "Written by Francois Fleuret <francois@fleuret.org>"
491          << endl
492          << argv[0]
493          << " [-h]"
494          << " [-v]"
495          << " [-m]"
496          << " [-d]"
497          << " [-e]"
498          << " [-z]"
499          << " [-i]"
500          << " [-c <fg modeline> <bg modeline> <fg highlight> <bg highlight>]"
501          << " [-o <output filename>]"
502          << " [-s <pattern separator>]"
503          << " [-l <max number of lines>]"
504          << " -f <input filename>"
505          << endl;
506
507     exit(error);
508   }
509
510   char **lines = new char *[nb_lines_max];
511
512   if(!input_filename[0]) {
513     cerr << "You must specify a input file with -f." << endl;
514     exit(1);
515   }
516
517   int nb_lines = 0;
518
519   ifstream file(input_filename);
520
521   if(file.fail()) {
522     cerr << "Can not open " << input_filename << endl;
523     return 1;
524   }
525
526   int hash_table_size = nb_lines_max * 10;
527   int *hash_table = 0;
528
529   if(remove_duplicates) {
530     hash_table = new_hash_table(hash_table_size);
531   }
532
533   while(nb_lines < nb_lines_max && !file.eof()) {
534     file.getline(buffer, buffer_size);
535     if(strcmp(buffer, "") != 0) {
536       char *s = buffer;
537
538       if(zsh_history && *s == ':') {
539         while(*s && *s != ';') s++;
540         if(*s == ';') s++;
541       }
542
543       if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
544         while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
545       }
546
547       if(!hash_table || !test_and_add(s, nb_lines, lines, hash_table, hash_table_size)) {
548         lines[nb_lines] = new char[strlen(s) + 1];
549         strcpy(lines[nb_lines], s);
550         nb_lines++;
551       }
552     }
553   }
554
555   delete[] hash_table;
556
557   if(inverse_order) {
558     for(int i = 0; i < nb_lines/2; i++) {
559       char *s = lines[nb_lines - 1 - i];
560       lines[nb_lines - 1 - i] = lines[i];
561       lines[i] = s;
562     }
563   }
564
565   char patterns[buffer_size];
566   patterns[0] = '\0';
567   int patterns_point;
568   patterns_point = 0;
569
570   initscr();
571
572   if(with_colors) {
573     if(has_colors()) {
574       start_color();
575       if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
576          color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
577          color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
578          color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
579         echo();
580         curs_set(1);
581         endwin();
582         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
583         exit(1);
584       }
585       init_pair(1, color_fg_modeline, color_bg_modeline);
586       init_pair(2, color_fg_highlight, color_bg_highlight);
587     } else {
588       with_colors = 0;
589     }
590   }
591
592   noecho();
593   curs_set(0); // Hide the cursor
594   keypad(stdscr, TRUE); // So that the arrow keys work
595
596   int key;
597   int current_line = 0, temporary_line = 0;
598
599   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns);
600
601   do {
602
603     key = getch();
604
605     int motion = 0;
606
607     if(key >= ' ' && key <= '~') {
608       patterns[patterns_point++] = key;
609       patterns[patterns_point] = '\0';
610     }
611
612     else if(key == KEY_BACKSPACE || key == '\b' || key == '\7f' ||
613             key == KEY_DC || key == '\ 4') {
614       if(patterns_point > 0) {
615         patterns_point--;
616         patterns[patterns_point] = '\0';
617       }
618     }
619
620     else if(key == KEY_HOME) {
621       current_line = 0;
622     }
623
624     else if(key == KEY_END) {
625       current_line = nb_lines - 1;
626     }
627
628     else if(key == KEY_NPAGE) {
629       motion = 10;
630     }
631
632     else if(key == KEY_PPAGE) {
633       motion = -10;
634     }
635
636     else if(key == KEY_UP || key == '\10') {
637       motion = -1;
638     }
639
640     else if(key == '\12') {
641       use_regexp = !use_regexp;
642     }
643
644     else if(key == '\15') {
645       patterns_point = 0;
646       patterns[patterns_point] = '\0';
647     }
648
649     else if(key == KEY_DOWN || key == '\ e') {
650       motion = 1;
651     }
652
653     update_screen(&current_line, &temporary_line, motion,
654                   nb_lines, lines, patterns);
655
656   } while(key != '\n' && key != KEY_ENTER && key != '\a');
657
658   echo();
659   curs_set(1);
660   endwin();
661
662   if((key == KEY_ENTER || key == '\n')) {
663
664     if(output_to_vt_buffer) {
665       if(temporary_line >= 0 && temporary_line < nb_lines) {
666         inject_into_tty_buffer(lines[temporary_line]);
667       }
668     }
669
670     if(output_filename[0]) {
671       ofstream out(output_filename);
672       if(out.fail()) {
673         cerr << "Can not open " << output_filename << " for writing." << endl;
674         exit(1);
675       } else {
676         if(temporary_line >= 0 && temporary_line < nb_lines) {
677           out << lines[temporary_line] << endl;
678         } else {
679           out << endl;
680         }
681       }
682       out.flush();
683     }
684
685   }
686
687   for(int l = 0; l < nb_lines; l++) {
688     delete[] lines[l];
689   }
690
691   delete[] lines;
692
693   exit(0);
694 }