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