Automatic commit
[selector.git] / selector.cc
1 /*
2  *  selector is a simple shell command for selection of strings with a
3  *  dynamic pattern-matching.
4  *
5  *  Copyright (c) 2009 Francois Fleuret
6  *  Written by Francois Fleuret <francois.fleuret@idiap.ch>
7  *
8  *  This file is part of selector.
9  *
10  *  selector is free software: you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License version 3 as
12  *  published by the Free Software Foundation.
13  *
14  *  selector is distributed in the hope that it will be useful, but
15  *  WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  *  General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with selector.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  */
23
24 /*
25
26   Here is the magical shell script for a smart bash-history. Note that
27   the line remains in /tmp/selector.out, which may be a security
28   concern.
29
30   ./selector -f ~/.bash_history
31   OLD_SETTINGS=`stty -g`
32   stty -echo raw
33   writevt `tty` "`cat /tmp/selector.out`"
34   stty ${OLD_SETTINGS}
35
36 */
37
38 #include <stdio.h>
39 #include <ncurses.h>
40 #include <iostream>
41 #include <fstream>
42 #include <string.h>
43 #include <stdlib.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <fcntl.h>
47 #include <sys/ioctl.h>
48 #include <fcntl.h>
49 #include <termios.h>
50 #include <strings.h>
51
52 using namespace std;
53
54 int buffer_size = 1024;
55 int nb_lines_max = 1000;
56 char pattern_separator = ';';
57 int output_to_vt_buffer = 0;
58
59 int match(char *string, int nb_patterns, char **patterns) {
60   for(int n = 0; n < nb_patterns; n++) {
61     if(strstr(string, patterns[n]) == 0) return 0;
62   }
63   return 1;
64 }
65
66 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
67   if(n_opt + n >= argc) {
68     cerr << "Missing argument for " << argv[n_opt] << "."
69          << " "
70          << "Expecting " << help << "."
71          << endl;
72     exit(1);
73   }
74 }
75
76 int previous_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
77   int line = current_line - 1;
78   while(line >= 0 && !match(lines[line], nb_patterns, patterns)) line--;
79   return line;
80 }
81
82 int next_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
83   int line = current_line + 1;
84   while(line < nb_lines && !match(lines[line], nb_patterns, patterns)) line++;
85
86   if(line < nb_lines)
87     return line;
88   else
89     return -1;
90 }
91
92 void update_screen(int *current_line, int *temporary_line, int motion,
93                    int nb_lines, char **lines,
94                    char *pattern_list,
95                    int no_blink) {
96
97   char buffer[buffer_size];
98
99   // We split the pattern list into individual patterns
100
101   int nb_patterns = 1;
102
103   for(char *s = pattern_list; *s; s++) {
104     if(*s == pattern_separator) {
105       nb_patterns++;
106     }
107   }
108
109   char splitted_patterns[strlen(pattern_list) + 1];
110   char *patterns[nb_patterns];
111
112   strcpy(splitted_patterns, pattern_list);
113
114   int n = 0;
115   char *last_pattern_start = splitted_patterns;
116   for(char *s = splitted_patterns; n < nb_patterns; s++) {
117     if(*s == pattern_separator || *s == '\0') {
118       *s = '\0';
119       patterns[n++] = last_pattern_start;
120       last_pattern_start = s + 1;
121     }
122   }
123
124   // We now take care of printing the lines per se
125
126   int console_width = getmaxx(stdscr);
127   int console_height = getmaxy(stdscr);
128
129   int nb_printed_lines = 1;
130
131   // First, we find a visible line. In priority: The current, or the
132   // first visible after it, or the first visible before it.
133
134   int new_line;
135   if(match(lines[*current_line], nb_patterns, patterns)) {
136     new_line = *current_line;
137   } else {
138     new_line = next_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
139     if(new_line < 0) {
140       new_line = previous_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
141     }
142   }
143
144   // If we found a visible line and we should move, let's move
145
146   if(new_line >= 0 && motion != 0) {
147     int l = new_line;
148     if(motion > 0) {
149       // We want to go down, let's find the first visible line below
150       for(int m = 0; l >= 0 && m < motion; m++) {
151         l = next_visible(l, nb_lines, lines, nb_patterns, patterns);
152         if(l >= 0) {
153           new_line = l;
154         }
155       }
156     } else {
157       // We want to go up, let's find the first visible line above
158       for(int m = 0; l >= 0 && m < -motion; m++) {
159         l = previous_visible(l, nb_lines, lines, nb_patterns, patterns);
160         if(l >= 0) {
161           new_line = l;
162         }
163       }
164     }
165   }
166
167   if(!no_blink) {
168     clear();
169   }
170
171   use_default_colors();
172
173   addstr("\n");
174
175   // Here new_line is either a line number matching the patterns, or -1
176
177   if(new_line >= 0) {
178
179     int first_line = new_line, last_line = new_line, nb_match = 1;
180
181     // We find the first and last line to show, so that the total of
182     // visible lines between them (them include) is console_height - 1
183
184     while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
185
186       if(first_line > 0) {
187         first_line--;
188         while(first_line > 0 && !match(lines[first_line], nb_patterns, patterns)) {
189           first_line--;
190         }
191         if(match(lines[first_line], nb_patterns, patterns)) {
192           nb_match++;
193         }
194       }
195
196       if(last_line < nb_lines - 1) {
197         last_line++;
198         while(last_line < nb_lines - 1 && !match(lines[last_line], nb_patterns, patterns)) {
199           last_line++;
200         }
201
202         if(match(lines[last_line], nb_patterns, patterns)) {
203           nb_match++;
204         }
205       }
206     }
207
208     // Now we display them
209
210     for(int l = first_line; l <= last_line; l++) {
211       if(match(lines[l], nb_patterns, patterns)) {
212         int k = 0;
213
214         while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
215           buffer[k] = lines[l][k];
216           k++;
217         }
218
219         if(no_blink || l == new_line) {
220           while(k < console_width) {
221             buffer[k++] = ' ';
222           }
223         }
224
225         buffer[k++] = '\n';
226         buffer[k++] = '\0';
227
228         if(l == new_line) {
229           attron(COLOR_PAIR(2));
230           addnstr(buffer, console_width);
231           attroff(COLOR_PAIR(2));
232         } else {
233           addnstr(buffer, console_width);
234         }
235
236         nb_printed_lines++;
237       }
238     }
239
240     *temporary_line = new_line;
241     if(motion != 0) {
242       *current_line = new_line;
243     }
244   }
245
246   // if(nb_printed_lines == 1) {
247   // addnstr("[no selection]\n", console_width);
248   // nb_printed_lines++;
249   // }
250
251   if(no_blink) { // Erase the rest of the window. That's slightly ugly.
252     int k = 0;
253     while(k < console_width) {
254       buffer[k++] = ' ';
255     }
256     buffer[k++] = '\n';
257     buffer[k++] = '\0';
258     for(int l = nb_printed_lines; l < console_height; l++) {
259       addnstr(buffer, console_width);
260     }
261   }
262
263   // Draw the modeline
264
265   sprintf(buffer, "%d/%d pattern: %s",
266           nb_printed_lines - 1,
267           nb_lines,
268           pattern_list);
269
270   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
271   buffer[console_width] = '\0';
272
273   move(0, 0);
274   attron(COLOR_PAIR(1));
275   addnstr(buffer, console_width);
276   attroff(COLOR_PAIR(1));
277
278   refresh();       // After doing something on the display, we refresh it
279 }
280
281 //////////////////////////////////////////////////////////////////////
282
283 int main(int argc, char **argv) {
284   char buffer[buffer_size];
285   char *lines[nb_lines_max];
286   int no_blink = 0;
287
288   char input_filename[buffer_size], output_filename[buffer_size];
289   strcpy(input_filename, "/dev/stdin");
290   strcpy(output_filename, "/tmp/selector.out");
291
292   int i = 1;
293   while(i < argc) {
294     if(strcmp(argv[i], "-o") == 0) {
295       check_opt(argc, argv, i, 1, "<output filename>");
296       strncpy(output_filename, argv[i+1], buffer_size);
297       i += 2;
298     }
299
300     else if(strcmp(argv[i], "-s") == 0) {
301       check_opt(argc, argv, i, 1, "<pattern separator>");
302       pattern_separator = argv[i+1][0];
303       i += 2;
304     }
305
306     else if(strcmp(argv[i], "-v") == 0) {
307       output_to_vt_buffer = 1;
308       i++;
309     }
310
311     else if(strcmp(argv[i], "-f") == 0) {
312       check_opt(argc, argv, i, 1, "<input filename>");
313       strncpy(input_filename, argv[i+1], buffer_size);
314       i += 2;
315     }
316
317     else if(strcmp(argv[i], "-b") == 0) {
318       no_blink = 1;
319       i++;
320     }
321
322     else if(strcmp(argv[i], "-l") == 0) {
323       check_opt(argc, argv, i, 1, "<maximum number of lines>");
324       nb_lines_max = atoi(argv[i+1]);
325       i += 2;
326     }
327
328     else {
329       cerr << argv[0] << " [-h] [-o <output filename>] [-b] [-l <max number of lines>] [-s <pattern separator>] [-v]" << endl;
330       if(strcmp(argv[i], "-h") == 0) {
331         exit(0);
332       } else {
333         exit(1);
334       }
335     }
336   }
337
338   ifstream file(input_filename);
339
340   if(file.fail()) {
341     cerr << "Can not open \"" << input_filename << "\"" << endl;
342     return 1;
343   }
344
345   int nb_lines = 0;
346   while(nb_lines < nb_lines_max && !file.eof()) {
347     file.getline(buffer, buffer_size);
348     lines[nb_lines] = new char[strlen(buffer) + 1];
349     strcpy(lines[nb_lines], buffer);
350     nb_lines++;
351   }
352
353   char patterns[buffer_size];
354   patterns[0] = '\0';
355   int patterns_point;
356   patterns_point = 0;
357
358   initscr();
359
360   if(!has_colors()) {
361     cerr << "No colors." << endl;
362     return 1;
363   }
364
365   noecho();
366   curs_set(0);
367   keypad(stdscr, TRUE);
368
369   start_color();
370   // init_pair(1, COLOR_WHITE, COLOR_BLACK);
371   init_pair(1, COLOR_WHITE, COLOR_GREEN);
372   init_pair(2, COLOR_BLACK, COLOR_YELLOW);
373
374   int key;
375
376   int current_line = 0, temporary_line = 0;
377
378   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns, no_blink);
379
380   do {
381
382     key = getch();
383
384     int motion = 0;
385
386     if(key >= ' ' && key <= 'z') {
387       patterns[patterns_point++] = key;
388       patterns[patterns_point] = '\0';
389     }
390
391     else if(key == KEY_BACKSPACE || key == KEY_DC || key == '\b') {
392       if(patterns_point > 0) {
393         patterns_point--;
394         patterns[patterns_point] = '\0';
395       }
396     }
397
398     else if(key == KEY_HOME) {
399       current_line = 0;
400     }
401
402     else if(key == KEY_END) {
403       current_line = nb_lines - 1;
404     }
405
406     else if(key == KEY_NPAGE) {
407       motion = 10;
408     }
409
410     else if(key == KEY_PPAGE) {
411       motion = -10;
412     }
413
414     else if(key == KEY_UP || key == '\10') {
415       motion = -1;
416     }
417
418     else if(key == KEY_DOWN || key == '\ e') {
419       motion = 1;
420     }
421
422     update_screen(&current_line, &temporary_line, motion,
423                   nb_lines, lines, patterns, no_blink);
424   } while(key != '\n' && key != KEY_ENTER && key != '\a');
425
426   echo();
427   curs_set(1);
428   endwin();
429
430   if(output_to_vt_buffer) {
431     if((key == KEY_ENTER || key == '\n') && temporary_line >= 0 && temporary_line < nb_lines) {
432       char *tty = ttyname (STDIN_FILENO);
433       int fd = open(tty, O_WRONLY);
434
435       struct termios oldtio, newtio;
436
437       if (fd >= 0) {
438         // Save current port settings
439         tcgetattr(fd,&oldtio);
440         bzero(&newtio, sizeof(newtio));
441         newtio.c_cflag = 0;
442         newtio.c_iflag = 0;
443         newtio.c_oflag = 0;
444         // Set input mode (non-canonical, *no echo*,...)
445         newtio.c_lflag = 0;
446         tcflush(fd, TCIFLUSH);
447         tcsetattr(fd,TCSANOW, &newtio);
448         for(char *k = lines[temporary_line]; *k; k++) {
449           ioctl(fd, TIOCSTI, k);
450         }
451         // Restore the old settings
452         tcsetattr(fd,TCSANOW, &oldtio);
453         close(fd);
454       } else {
455         cerr << "Can not open " << tty << endl;
456         exit(1);
457       }
458     }
459   } else {
460
461     ofstream out(output_filename);
462     if(out.fail()) {
463       cerr << "Can not open " << output_filename << " for writing." << endl;
464       exit(1);
465     } else {
466       if((key == KEY_ENTER || key == '\n') && temporary_line >= 0 && temporary_line < nb_lines) {
467         out << lines[temporary_line] << endl;
468       } else {
469         out << endl;
470       }
471       out.flush();
472     }
473   }
474
475   for(int l = 0; l < nb_lines; l++) {
476     delete[] lines[l];
477   }
478
479   exit(0);
480 }