668323e0ea387419a0f9946a234084fd5d1d2bbe
[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
43 using namespace std;
44
45 #define VERSION "1.0"
46
47 const int buffer_size = 1024;
48
49 // Yeah, global variables!
50
51 int nb_lines_max = 1000;
52 char pattern_separator = ';';
53 int output_to_vt_buffer = 0;
54 int with_colors = 1;
55 int zsh_history = 0, bash_history = 0;
56 int inverse_order = 0;
57 int remove_duplicates = 0;
58
59 //////////////////////////////////////////////////////////////////////
60
61 // This looks severely Linux-only ...
62
63 void inject_into_tty_buffer(char *line) {
64   struct termios oldtio, newtio;
65   tcgetattr(STDIN_FILENO,&oldtio);
66   memset(&newtio, 0, sizeof(newtio));
67   // Set input mode (non-canonical, *no echo*,...)
68   tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
69   // Put the selected line in the tty input buffer
70   for(char *k = line; *k; k++) {
71     ioctl(STDIN_FILENO, TIOCSTI, k);
72   }
73   // Restore the old settings
74   tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
75 }
76
77 //////////////////////////////////////////////////////////////////////
78
79 int match(char *string, int nb_patterns, char **patterns) {
80   for(int n = 0; n < nb_patterns; n++) {
81     if(strstr(string, patterns[n]) == 0) return 0;
82   }
83   return 1;
84 }
85
86 //////////////////////////////////////////////////////////////////////
87
88 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
89   if(n_opt + n >= argc) {
90     cerr << "Missing argument for " << argv[n_opt] << "."
91          << " "
92          << "Expecting " << help << "."
93          << endl;
94     exit(1);
95   }
96 }
97
98 //////////////////////////////////////////////////////////////////////
99 // A quick and dirty hash table
100
101 int *new_hash_table(int hash_table_size) {
102   int *result;
103   result = new int[hash_table_size];
104   for(int k = 0; k < hash_table_size; k++) {
105     result[k] = -1;
106   }
107   return result;
108 }
109
110 int test_and_add(char *new_string, int new_index,
111                  char **strings, int *hash_table, int hash_table_size) {
112   unsigned int code = 0;
113
114   for(int k = 0; new_string[k]; k++) {
115     code += int(new_string[k]) << (8 * k%4);
116   }
117
118   code = code % hash_table_size;
119
120   while(hash_table[code] >= 0) {
121     if(strcmp(new_string, strings[hash_table[code]]) == 0) return 1;
122     code = (code + 1) % hash_table_size;
123   }
124
125   hash_table[code] = new_index;
126
127   return 0;
128 }
129
130 //////////////////////////////////////////////////////////////////////
131
132 int previous_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
133   int line = current_line - 1;
134   while(line >= 0 && !match(lines[line], nb_patterns, patterns)) line--;
135   return line;
136 }
137
138 int next_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
139   int line = current_line + 1;
140   while(line < nb_lines && !match(lines[line], nb_patterns, patterns)) line++;
141
142   if(line < nb_lines)
143     return line;
144   else
145     return -1;
146 }
147
148 void update_screen(int *current_line, int *temporary_line, int motion,
149                    int nb_lines, char **lines,
150                    char *pattern_list) {
151
152   char buffer[buffer_size];
153
154   // We split the pattern list into individual patterns
155
156   int nb_patterns = 1;
157
158   for(char *s = pattern_list; *s; s++) {
159     if(*s == pattern_separator) {
160       nb_patterns++;
161     }
162   }
163
164   char splitted_patterns[strlen(pattern_list) + 1];
165   char *patterns[nb_patterns];
166
167   strcpy(splitted_patterns, pattern_list);
168
169   int n = 0;
170   char *last_pattern_start = splitted_patterns;
171   for(char *s = splitted_patterns; n < nb_patterns; s++) {
172     if(*s == pattern_separator || *s == '\0') {
173       *s = '\0';
174       patterns[n++] = last_pattern_start;
175       last_pattern_start = s + 1;
176     }
177   }
178
179   // We now take care of printing the lines per se
180
181   int console_width = getmaxx(stdscr);
182   int console_height = getmaxy(stdscr);
183
184   // First, we find a visible line. In priority: The current, or the
185   // first visible after it, or the first visible before it.
186
187   int new_line;
188   if(match(lines[*current_line], nb_patterns, patterns)) {
189     new_line = *current_line;
190   } else {
191     new_line = next_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
192     if(new_line < 0) {
193       new_line = previous_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
194     }
195   }
196
197   // If we found a visible line and we should move, let's move
198
199   if(new_line >= 0 && motion != 0) {
200     int l = new_line;
201     if(motion > 0) {
202       // We want to go down, let's find the first visible line below
203       for(int m = 0; l >= 0 && m < motion; m++) {
204         l = next_visible(l, nb_lines, lines, nb_patterns, patterns);
205         if(l >= 0) {
206           new_line = l;
207         }
208       }
209     } else {
210       // We want to go up, let's find the first visible line above
211       for(int m = 0; l >= 0 && m < -motion; m++) {
212         l = previous_visible(l, nb_lines, lines, nb_patterns, patterns);
213         if(l >= 0) {
214           new_line = l;
215         }
216       }
217     }
218   }
219
220   clear();
221
222   use_default_colors();
223
224   addstr("\n");
225
226   int nb_printed_lines = 0;
227
228   // Here new_line is either a line number matching the patterns, or -1
229
230   if(new_line >= 0) {
231
232     int first_line = new_line, last_line = new_line, nb_match = 1;
233
234     // We find the first and last line to show, so that the total of
235     // visible lines between them (them include) is console_height - 1
236
237     while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
238
239       if(first_line > 0) {
240         first_line--;
241         while(first_line > 0 && !match(lines[first_line], nb_patterns, patterns)) {
242           first_line--;
243         }
244         if(match(lines[first_line], nb_patterns, patterns)) {
245           nb_match++;
246         }
247       }
248
249       if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
250         last_line++;
251         while(last_line < nb_lines - 1 && !match(lines[last_line], nb_patterns, patterns)) {
252           last_line++;
253         }
254
255         if(match(lines[last_line], nb_patterns, patterns)) {
256           nb_match++;
257         }
258       }
259     }
260
261     // Now we display them
262
263     for(int l = first_line; l <= last_line; l++) {
264       if(match(lines[l], nb_patterns, patterns)) {
265         int k = 0;
266
267         while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
268           buffer[k] = lines[l][k];
269           k++;
270         }
271
272         // We fill the rest of the line with blanks if either we did
273         // not clear() or if this is the highlighted line
274
275         if(l == new_line) {
276           while(k < console_width) {
277             buffer[k++] = ' ';
278           }
279         }
280
281         buffer[k++] = '\n';
282         buffer[k++] = '\0';
283
284         // Highlight the highlighted line ...
285
286         if(l == new_line) {
287           if(with_colors) {
288             attron(COLOR_PAIR(2));
289             addnstr(buffer, console_width);
290             attroff(COLOR_PAIR(2));
291           } else {
292             attron(A_STANDOUT);
293             addnstr(buffer, console_width);
294             attroff(A_STANDOUT);
295           }
296         } else {
297           addnstr(buffer, console_width);
298         }
299
300         nb_printed_lines++;
301       }
302     }
303
304     if(motion != 0) {
305       *current_line = new_line;
306     }
307   }
308
309   *temporary_line = new_line;
310
311   if(nb_printed_lines == 0) {
312     addnstr("[no selection]\n", console_width);
313   }
314
315   // Draw the modeline
316
317   sprintf(buffer, "%d/%d pattern: %s",
318           nb_printed_lines,
319           nb_lines,
320           pattern_list);
321
322   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
323   buffer[console_width] = '\0';
324
325   move(0, 0);
326   if(with_colors) {
327     attron(COLOR_PAIR(1));
328     addnstr(buffer, console_width);
329     attroff(COLOR_PAIR(1));
330   } else {
331     attron(A_REVERSE);
332     addnstr(buffer, console_width);
333     attroff(A_REVERSE);
334   }
335
336   // We are done
337
338   refresh();
339 }
340
341 //////////////////////////////////////////////////////////////////////
342
343 int main(int argc, char **argv) {
344   char buffer[buffer_size];
345   int color_fg_modeline, color_bg_modeline;
346   int color_fg_highlight, color_bg_highlight;
347
348   color_fg_modeline  = COLOR_WHITE;
349   color_bg_modeline  = COLOR_BLACK;
350   color_fg_highlight = COLOR_BLACK;
351   color_bg_highlight = COLOR_YELLOW;
352
353   setlocale(LC_ALL, "");
354
355   char input_filename[buffer_size], output_filename[buffer_size];
356
357   strcpy(input_filename, "");
358   strcpy(output_filename, "");
359
360   int i = 1;
361   while(i < argc) {
362
363     if(strcmp(argv[i], "-o") == 0) {
364       check_opt(argc, argv, i, 1, "<output filename>");
365       strncpy(output_filename, argv[i+1], buffer_size);
366       i += 2;
367     }
368
369     else if(strcmp(argv[i], "-s") == 0) {
370       check_opt(argc, argv, i, 1, "<pattern separator>");
371       pattern_separator = argv[i+1][0];
372       i += 2;
373     }
374
375     else if(strcmp(argv[i], "-v") == 0) {
376       output_to_vt_buffer = 1;
377       i++;
378     }
379
380     else if(strcmp(argv[i], "-m") == 0) {
381       with_colors = 0;
382       i++;
383     }
384
385     else if(strcmp(argv[i], "-f") == 0) {
386       check_opt(argc, argv, i, 1, "<input filename>");
387       strncpy(input_filename, argv[i+1], buffer_size);
388       i += 2;
389     }
390
391     else if(strcmp(argv[i], "-i") == 0) {
392       inverse_order = 1;
393       i++;
394     }
395
396     else if(strcmp(argv[i], "-z") == 0) {
397       zsh_history = 1;
398       i++;
399     }
400
401     else if(strcmp(argv[i], "-b") == 0) {
402       bash_history = 1;
403       i++;
404     }
405
406     else if(strcmp(argv[i], "-r") == 0) {
407       remove_duplicates = 1;
408       i++;
409     }
410
411     else if(strcmp(argv[i], "-l") == 0) {
412       check_opt(argc, argv, i, 1, "<maximum number of lines>");
413       nb_lines_max = atoi(argv[i+1]);
414       i += 2;
415     }
416
417     else if(strcmp(argv[i], "-c") == 0) {
418       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
419       color_fg_modeline = atoi(argv[i+1]);
420       color_bg_modeline = atoi(argv[i+2]);
421       color_fg_highlight = atoi(argv[i+3]);
422       color_bg_highlight = atoi(argv[i+4]);
423       i += 5;
424     }
425
426     else {
427       cerr << "Selector version " << VERSION
428            << endl
429            << "Written by Francois Fleuret <francois@fleuret.org>"
430            << endl
431            << argv[0]
432            << " [-h]"
433            << " [-v]"
434            << " [-m]"
435            << " [-r]"
436            << " [-z]"
437            << " [-i]"
438            << " [-c <fg modeline> <bg modeline> <fg highlight> <bg highlight>]"
439            << " [-o <output filename>]"
440            << " [-s <pattern separator>]"
441            << " [-l <max number of lines>]"
442            << " -f <input filename>"
443            << endl;
444       if(strcmp(argv[i], "-h") == 0) {
445         exit(0);
446       } else {
447         exit(1);
448       }
449     }
450   }
451
452   char **lines = new char *[nb_lines_max];
453
454   if(!input_filename[0]) {
455     cerr << "You must specify a input file with -f." << endl;
456     exit(1);
457   }
458
459   int nb_lines = 0;
460
461   ifstream file(input_filename);
462
463   if(file.fail()) {
464     cerr << "Can not open " << input_filename << endl;
465     return 1;
466   }
467
468   int hash_table_size = nb_lines_max * 10;
469   int *hash_table = 0;
470
471   if(remove_duplicates) {
472     hash_table = new_hash_table(hash_table_size);
473   }
474
475   while(nb_lines < nb_lines_max && !file.eof()) {
476     file.getline(buffer, buffer_size);
477     if(strcmp(buffer, "") != 0) {
478       char *s = buffer;
479
480       if(zsh_history && *s == ':') {
481         while(*s && *s != ';') s++;
482         if(*s == ';') s++;
483       }
484
485       if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
486         while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
487       }
488
489       if(!hash_table || !test_and_add(s, nb_lines, lines, hash_table, hash_table_size)) {
490         lines[nb_lines] = new char[strlen(s) + 1];
491         strcpy(lines[nb_lines], s);
492         nb_lines++;
493       }
494     }
495   }
496
497   delete[] hash_table;
498
499   if(inverse_order) {
500     for(int i = 0; i < nb_lines/2; i++) {
501       char *s = lines[nb_lines - 1 - i];
502       lines[nb_lines - 1 - i] = lines[i];
503       lines[i] = s;
504     }
505   }
506
507   char patterns[buffer_size];
508   patterns[0] = '\0';
509   int patterns_point;
510   patterns_point = 0;
511
512   initscr();
513
514   if(with_colors) {
515     if(has_colors()) {
516       start_color();
517       if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
518          color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
519          color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
520          color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
521         echo();
522         curs_set(1);
523         endwin();
524         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
525         exit(1);
526       }
527       init_pair(1, color_fg_modeline, color_bg_modeline);
528       init_pair(2, color_fg_highlight, color_bg_highlight);
529     } else {
530       with_colors = 0;
531     }
532   }
533
534   noecho();
535   curs_set(0); // Hide the cursor
536   keypad(stdscr, TRUE); // So that the arrow keys work
537
538   int key;
539   int current_line = 0, temporary_line = 0;
540
541   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns);
542
543   do {
544
545     key = getch();
546
547     int motion = 0;
548
549     if(key >= ' ' && key <= '~') {
550       patterns[patterns_point++] = key;
551       patterns[patterns_point] = '\0';
552     }
553
554     else if(key == KEY_BACKSPACE || key == '\b' || key == '\7f' ||
555             key == KEY_DC || key == '\ 4') {
556       if(patterns_point > 0) {
557         patterns_point--;
558         patterns[patterns_point] = '\0';
559       }
560     }
561
562     else if(key == KEY_HOME) {
563       current_line = 0;
564     }
565
566     else if(key == KEY_END) {
567       current_line = nb_lines - 1;
568     }
569
570     else if(key == KEY_NPAGE) {
571       motion = 10;
572     }
573
574     else if(key == KEY_PPAGE) {
575       motion = -10;
576     }
577
578     else if(key == KEY_UP || key == '\10') {
579       motion = -1;
580     }
581
582     else if(key == KEY_DOWN || key == '\ e') {
583       motion = 1;
584     }
585
586     update_screen(&current_line, &temporary_line, motion,
587                   nb_lines, lines, patterns);
588
589   } while(key != '\n' && key != KEY_ENTER && key != '\a');
590
591   echo();
592   curs_set(1);
593   endwin();
594
595   if((key == KEY_ENTER || key == '\n')) {
596
597     if(output_to_vt_buffer) {
598       if(temporary_line >= 0 && temporary_line < nb_lines) {
599         inject_into_tty_buffer(lines[temporary_line]);
600       }
601     }
602
603     if(output_filename[0]) {
604       ofstream out(output_filename);
605       if(out.fail()) {
606         cerr << "Can not open " << output_filename << " for writing." << endl;
607         exit(1);
608       } else {
609         if(temporary_line >= 0 && temporary_line < nb_lines) {
610           out << lines[temporary_line] << endl;
611         } else {
612           out << endl;
613         }
614       }
615       out.flush();
616     }
617
618   }
619
620   for(int l = 0; l < nb_lines; l++) {
621     delete[] lines[l];
622   }
623   delete[] lines;
624
625   exit(0);
626 }