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