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 // Here is how to use it as a super-history-search in bash
25 //
26 //  ./selector -v -f ${HISTFILE}
27
28 #include <fstream>
29 #include <iostream>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ncurses.h>
35 #include <fcntl.h>
36 #include <sys/ioctl.h>
37 #include <termios.h>
38
39 using namespace std;
40
41 // Yeah, global variables!
42
43 int buffer_size = 1024;
44 int nb_lines_max = 1000;
45 char pattern_separator = ';';
46 int output_to_vt_buffer = 0;
47
48 //////////////////////////////////////////////////////////////////////
49
50 int match(char *string, int nb_patterns, char **patterns) {
51   for(int n = 0; n < nb_patterns; n++) {
52     if(strstr(string, patterns[n]) == 0) return 0;
53   }
54   return 1;
55 }
56
57 //////////////////////////////////////////////////////////////////////
58
59 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
60   if(n_opt + n >= argc) {
61     cerr << "Missing argument for " << argv[n_opt] << "."
62          << " "
63          << "Expecting " << help << "."
64          << endl;
65     exit(1);
66   }
67 }
68
69 //////////////////////////////////////////////////////////////////////
70
71 int previous_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
72   int line = current_line - 1;
73   while(line >= 0 && !match(lines[line], nb_patterns, patterns)) line--;
74   return line;
75 }
76
77 int next_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
78   int line = current_line + 1;
79   while(line < nb_lines && !match(lines[line], nb_patterns, patterns)) line++;
80
81   if(line < nb_lines)
82     return line;
83   else
84     return -1;
85 }
86
87 void update_screen(int *current_line, int *temporary_line, int motion,
88                    int nb_lines, char **lines,
89                    char *pattern_list,
90                    int no_blink) {
91
92   char buffer[buffer_size];
93
94   // We split the pattern list into individual patterns
95
96   int nb_patterns = 1;
97
98   for(char *s = pattern_list; *s; s++) {
99     if(*s == pattern_separator) {
100       nb_patterns++;
101     }
102   }
103
104   char splitted_patterns[strlen(pattern_list) + 1];
105   char *patterns[nb_patterns];
106
107   strcpy(splitted_patterns, pattern_list);
108
109   int n = 0;
110   char *last_pattern_start = splitted_patterns;
111   for(char *s = splitted_patterns; n < nb_patterns; s++) {
112     if(*s == pattern_separator || *s == '\0') {
113       *s = '\0';
114       patterns[n++] = last_pattern_start;
115       last_pattern_start = s + 1;
116     }
117   }
118
119   // We now take care of printing the lines per se
120
121   int console_width = getmaxx(stdscr);
122   int console_height = getmaxy(stdscr);
123
124   int nb_printed_lines = 1;
125
126   // First, we find a visible line. In priority: The current, or the
127   // first visible after it, or the first visible before it.
128
129   int new_line;
130   if(match(lines[*current_line], nb_patterns, patterns)) {
131     new_line = *current_line;
132   } else {
133     new_line = next_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
134     if(new_line < 0) {
135       new_line = previous_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
136     }
137   }
138
139   // If we found a visible line and we should move, let's move
140
141   if(new_line >= 0 && motion != 0) {
142     int l = new_line;
143     if(motion > 0) {
144       // We want to go down, let's find the first visible line below
145       for(int m = 0; l >= 0 && m < motion; m++) {
146         l = next_visible(l, nb_lines, lines, nb_patterns, patterns);
147         if(l >= 0) {
148           new_line = l;
149         }
150       }
151     } else {
152       // We want to go up, let's find the first visible line above
153       for(int m = 0; l >= 0 && m < -motion; m++) {
154         l = previous_visible(l, nb_lines, lines, nb_patterns, patterns);
155         if(l >= 0) {
156           new_line = l;
157         }
158       }
159     }
160   }
161
162   if(!no_blink) {
163     clear();
164   }
165
166   use_default_colors();
167
168   addstr("\n");
169
170   // Here new_line is either a line number matching the patterns, or -1
171
172   if(new_line >= 0) {
173
174     int first_line = new_line, last_line = new_line, nb_match = 1;
175
176     // We find the first and last line to show, so that the total of
177     // visible lines between them (them include) is console_height - 1
178
179     while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
180
181       if(first_line > 0) {
182         first_line--;
183         while(first_line > 0 && !match(lines[first_line], nb_patterns, patterns)) {
184           first_line--;
185         }
186         if(match(lines[first_line], nb_patterns, patterns)) {
187           nb_match++;
188         }
189       }
190
191       if(last_line < nb_lines - 1) {
192         last_line++;
193         while(last_line < nb_lines - 1 && !match(lines[last_line], nb_patterns, patterns)) {
194           last_line++;
195         }
196
197         if(match(lines[last_line], nb_patterns, patterns)) {
198           nb_match++;
199         }
200       }
201     }
202
203     // Now we display them
204
205     for(int l = first_line; l <= last_line; l++) {
206       if(match(lines[l], nb_patterns, patterns)) {
207         int k = 0;
208
209         while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
210           buffer[k] = lines[l][k];
211           k++;
212         }
213
214         // We fill the rest of the line with blanks if either we did
215         // not clear() or if this is the highlighted line
216
217         if(no_blink || l == new_line) {
218           while(k < console_width) {
219             buffer[k++] = ' ';
220           }
221         }
222
223         buffer[k++] = '\n';
224         buffer[k++] = '\0';
225
226         // Highlight the highlighted line ...
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   // We are done
279
280   refresh();
281 }
282
283 //////////////////////////////////////////////////////////////////////
284
285 int main(int argc, char **argv) {
286   char buffer[buffer_size];
287   char *lines[nb_lines_max];
288   int no_blink = 0;
289
290   char input_filename[buffer_size], output_filename[buffer_size];
291   strcpy(input_filename, "/dev/stdin");
292   strcpy(output_filename, "/tmp/selector.out");
293
294   int i = 1;
295   while(i < argc) {
296     if(strcmp(argv[i], "-o") == 0) {
297       check_opt(argc, argv, i, 1, "<output filename>");
298       strncpy(output_filename, argv[i+1], buffer_size);
299       i += 2;
300     }
301
302     else if(strcmp(argv[i], "-s") == 0) {
303       check_opt(argc, argv, i, 1, "<pattern separator>");
304       pattern_separator = argv[i+1][0];
305       i += 2;
306     }
307
308     else if(strcmp(argv[i], "-v") == 0) {
309       output_to_vt_buffer = 1;
310       i++;
311     }
312
313     else if(strcmp(argv[i], "-f") == 0) {
314       check_opt(argc, argv, i, 1, "<input filename>");
315       strncpy(input_filename, argv[i+1], buffer_size);
316       i += 2;
317     }
318
319     else if(strcmp(argv[i], "-b") == 0) {
320       no_blink = 1;
321       i++;
322     }
323
324     else if(strcmp(argv[i], "-l") == 0) {
325       check_opt(argc, argv, i, 1, "<maximum number of lines>");
326       nb_lines_max = atoi(argv[i+1]);
327       i += 2;
328     }
329
330     else {
331       cerr << argv[0] << " [-h] [-o <output filename>] [-b] [-l <max number of lines>] [-s <pattern separator>] [-v]" << endl;
332       if(strcmp(argv[i], "-h") == 0) {
333         exit(0);
334       } else {
335         exit(1);
336       }
337     }
338   }
339
340   ifstream file(input_filename);
341
342   if(file.fail()) {
343     cerr << "Can not open \"" << input_filename << "\"" << endl;
344     return 1;
345   }
346
347   int nb_lines = 0;
348   while(nb_lines < nb_lines_max && !file.eof()) {
349     file.getline(buffer, buffer_size);
350     lines[nb_lines] = new char[strlen(buffer) + 1];
351     strcpy(lines[nb_lines], buffer);
352     nb_lines++;
353   }
354
355   char patterns[buffer_size];
356   patterns[0] = '\0';
357   int patterns_point;
358   patterns_point = 0;
359
360   initscr();
361
362   if(!has_colors()) {
363     cerr << "No colors." << endl;
364     return 1;
365   }
366
367   noecho();
368   curs_set(0);
369   keypad(stdscr, TRUE);
370
371   start_color();
372   // init_pair(1, COLOR_WHITE, COLOR_BLACK);
373   init_pair(1, COLOR_WHITE, COLOR_GREEN);
374   init_pair(2, COLOR_BLACK, COLOR_YELLOW);
375
376   int key;
377
378   int current_line = 0, temporary_line = 0;
379
380   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns, no_blink);
381
382   do {
383
384     key = getch();
385
386     int motion = 0;
387
388     if(key >= ' ' && key <= 'z') {
389       patterns[patterns_point++] = key;
390       patterns[patterns_point] = '\0';
391     }
392
393     else if(key == KEY_BACKSPACE || key == KEY_DC || key == '\b') {
394       if(patterns_point > 0) {
395         patterns_point--;
396         patterns[patterns_point] = '\0';
397       }
398     }
399
400     else if(key == KEY_HOME) {
401       current_line = 0;
402     }
403
404     else if(key == KEY_END) {
405       current_line = nb_lines - 1;
406     }
407
408     else if(key == KEY_NPAGE) {
409       motion = 10;
410     }
411
412     else if(key == KEY_PPAGE) {
413       motion = -10;
414     }
415
416     else if(key == KEY_UP || key == '\10') {
417       motion = -1;
418     }
419
420     else if(key == KEY_DOWN || key == '\ e') {
421       motion = 1;
422     }
423
424     update_screen(&current_line, &temporary_line, motion,
425                   nb_lines, lines, patterns, no_blink);
426   } while(key != '\n' && key != KEY_ENTER && key != '\a');
427
428   echo();
429   curs_set(1);
430   endwin();
431
432   if(output_to_vt_buffer) {
433     if((key == KEY_ENTER || key == '\n') && temporary_line >= 0 && temporary_line < nb_lines) {
434       char *tty = ttyname (STDIN_FILENO);
435       int fd = open(tty, O_WRONLY);
436
437       struct termios oldtio, newtio;
438
439       if (fd >= 0) {
440         // Save current port settings
441         tcgetattr(fd,&oldtio);
442         bzero(&newtio, sizeof(newtio));
443         newtio.c_cflag = 0;
444         newtio.c_iflag = 0;
445         newtio.c_oflag = 0;
446         // Set input mode (non-canonical, *no echo*,...)
447         newtio.c_lflag = 0;
448         tcflush(fd, TCIFLUSH);
449         tcsetattr(fd,TCSANOW, &newtio);
450         for(char *k = lines[temporary_line]; *k; k++) {
451           ioctl(fd, TIOCSTI, k);
452         }
453         // Restore the old settings
454         tcsetattr(fd,TCSANOW, &oldtio);
455         close(fd);
456       } else {
457         cerr << "Can not open " << tty << endl;
458         exit(1);
459       }
460     }
461   } else {
462
463     ofstream out(output_filename);
464     if(out.fail()) {
465       cerr << "Can not open " << output_filename << " for writing." << endl;
466       exit(1);
467     } else {
468       if((key == KEY_ENTER || key == '\n') && temporary_line >= 0 && temporary_line < nb_lines) {
469         out << lines[temporary_line] << endl;
470       } else {
471         out << endl;
472       }
473       out.flush();
474     }
475   }
476
477   for(int l = 0; l < nb_lines; l++) {
478     delete[] lines[l];
479   }
480
481   exit(0);
482 }