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