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