887b4d04c23b4005ce77927a082d35ae75f296b2
[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) 2008 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 scurity concern.
28
29   ./selector -f ~/.bash_history
30   OLD_SETTINGS=`stty -g`
31   stty -echo raw
32   writevt `tty` "`cat /tmp/selector.out`"
33   stty ${OLD_SETTINGS}
34
35 */
36
37 #include <stdio.h>
38 #include <ncurses.h>
39 #include <iostream>
40 #include <fstream>
41 #include <string.h>
42 #include <stdlib.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <fcntl.h>
46
47 using namespace std;
48
49 int buffer_size = 1024;
50 int nb_lines_max = 1000;
51 char pattern_separator = ';';
52 int output_to_vt_buffer = 0;
53
54 int match(char *string, int nb_patterns, char **patterns) {
55   for(int n = 0; n < nb_patterns; n++) {
56     if(strstr(string, patterns[n]) == 0) return 0;
57   }
58   return 1;
59 }
60
61 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
62   if(n_opt + n >= argc) {
63     cerr << "Missing argument for "
64          << argv[n_opt]
65          << ". Expecting "
66          << help
67          << "." << endl;
68     exit(1);
69   }
70 }
71
72 int previous_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
73   int line = current_line - 1;
74   while(line >= 0 && !match(lines[line], nb_patterns, patterns)) line--;
75   return line;
76 }
77
78 int next_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
79   int line = current_line + 1;
80   while(line < nb_lines && !match(lines[line], nb_patterns, patterns)) line++;
81
82   if(line < nb_lines)
83     return line;
84   else
85     return -1;
86 }
87
88 void update_screen(int *current_line, int *temporary_line, int motion,
89                    int nb_lines, char **lines,
90                    char *pattern_list,
91                    int noblink) {
92
93   char buffer[buffer_size];
94
95   // We split the pattern list into individual patterns
96
97   int nb_patterns = 1;
98
99   for(char *s = pattern_list; *s; s++) {
100     if(*s == pattern_separator) {
101       nb_patterns++;
102     }
103   }
104
105   char splitted_patterns[strlen(pattern_list) + 1];
106   char *patterns[nb_patterns];
107
108   strcpy(splitted_patterns, pattern_list);
109
110   int n = 0;
111   char *last_pattern_start = splitted_patterns;
112   for(char *s = splitted_patterns; n < nb_patterns; s++) {
113     if(*s == pattern_separator || *s == '\0') {
114       *s = '\0';
115       patterns[n++] = last_pattern_start;
116       last_pattern_start = s + 1;
117     }
118   }
119
120   // We now take care of printing the lines per se
121
122   int console_width = getmaxx(stdscr);
123   int console_height = getmaxy(stdscr);
124
125   int nb_printed_lines = 1;
126
127   // First, we find a visible line. In priority: The current, or the
128   // first visible after it, or the first visible before it.
129
130   int new_line;
131   if(match(lines[*current_line], nb_patterns, patterns)) {
132     new_line = *current_line;
133   } else {
134     new_line = next_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
135     if(new_line < 0) {
136       new_line = previous_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
137     }
138   }
139
140   // If we found a visible line and we should move, let's move
141
142   if(new_line >= 0 && motion != 0) {
143     int l = new_line;
144     l += motion;
145
146     if(motion > 0) {
147       // We want to go down, let's find the first visible line below
148       l = next_visible(new_line, nb_lines, lines, nb_patterns, patterns);
149       if(l >= 0) {
150         new_line = l;
151       }
152     } else {
153       // We want to go up, let's find the first visible line above
154       l = previous_visible(new_line, nb_lines, lines, nb_patterns, patterns);
155       if(l >= 0) {
156         new_line = l;
157       }
158     }
159   }
160
161   if(!noblink) {
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         if(noblink || l == new_line) {
214           while(k < console_width) {
215             buffer[k++] = ' ';
216           }
217         }
218
219         buffer[k++] = '\n';
220         buffer[k++] = '\0';
221
222         if(l == new_line) {
223           attron(COLOR_PAIR(2));
224           addnstr(buffer, console_width);
225           attroff(COLOR_PAIR(2));
226         } else {
227           addnstr(buffer, console_width);
228         }
229
230         nb_printed_lines++;
231       }
232     }
233
234     *temporary_line = new_line;
235     if(motion != 0) {
236       *current_line = new_line;
237     }
238   }
239
240   if(noblink) { // Erase the rest of the window. That's slightly ugly.
241     int k = 0;
242     while(k < console_width) {
243       buffer[k++] = ' ';
244     }
245     buffer[k++] = '\n';
246     buffer[k++] = '\0';
247     for(int l = nb_printed_lines; l < console_height; l++) {
248       addnstr(buffer, console_width);
249     }
250   }
251
252   // Draw the modeline
253
254   sprintf(buffer, "%d/%d pattern: %s",
255           nb_printed_lines - 1,
256           nb_lines,
257           pattern_list);
258
259   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
260   buffer[console_width] = '\0';
261
262   move(0, 0);
263   attron(COLOR_PAIR(1));
264   addnstr(buffer, console_width);
265   attroff(COLOR_PAIR(1));
266
267   refresh();       // After doing something on the display, we refresh it
268 }
269
270 //////////////////////////////////////////////////////////////////////
271
272 int main(int argc, char **argv) {
273   char buffer[buffer_size];
274   char *lines[nb_lines_max];
275   int noblink = 0;
276
277   char input_filename[buffer_size], output_filename[buffer_size];
278   strcpy(input_filename, "/dev/stdin");
279   strcpy(output_filename, "/tmp/selector.out");
280
281   int i = 1;
282   while(i < argc) {
283     if(strcmp(argv[i], "-o") == 0) {
284       check_opt(argc, argv, i, 1, "<output filename>");
285       strncpy(output_filename, argv[i+1], buffer_size);
286       i += 2;
287     }
288
289     else if(strcmp(argv[i], "-s") == 0) {
290       check_opt(argc, argv, i, 1, "<pattern separator>");
291       pattern_separator = argv[i+1][0];
292       i += 2;
293     }
294
295     else if(strcmp(argv[i], "-v") == 0) {
296       output_to_vt_buffer = 1;
297       i++;
298     }
299
300     else if(strcmp(argv[i], "-f") == 0) {
301       check_opt(argc, argv, i, 1, "<input filename>");
302       strncpy(input_filename, argv[i+1], buffer_size);
303       i += 2;
304     }
305
306     else if(strcmp(argv[i], "-b") == 0) {
307       noblink = 1;
308       i++;
309     }
310
311     else if(strcmp(argv[i], "-l") == 0) {
312       check_opt(argc, argv, i, 1, "<maximum number of lines>");
313       nb_lines_max = atoi(argv[i+1]);
314       i += 2;
315     }
316
317     else {
318       cerr << argv[0] << " [-h] [-o <output filename>] [-b] [-l <max number of lines>] [-s <pattern separator>] [-v]" << endl;
319       if(strcmp(argv[i], "-h") == 0) {
320         exit(0);
321       } else {
322         exit(1);
323       }
324     }
325   }
326
327   ifstream file(input_filename);
328
329   if(file.fail()) {
330     cerr << "Can not open \"" << input_filename << "\"" << endl;
331     return 1;
332   }
333
334   int nb_lines = 0;
335   while(nb_lines < nb_lines_max && !file.eof()) {
336     file.getline(buffer, buffer_size);
337     lines[nb_lines] = new char[strlen(buffer) + 1];
338     strcpy(lines[nb_lines], buffer);
339     nb_lines++;
340   }
341
342   char patterns[buffer_size];
343   patterns[0] = '\0';
344   int patterns_point;
345   patterns_point = 0;
346
347   initscr();
348
349   if(!has_colors()) {
350     cerr << "No colors." << endl;
351     return 1;
352   }
353
354   noecho();
355   curs_set(0);
356   keypad(stdscr, TRUE);
357
358   start_color();
359   // init_pair(1, COLOR_WHITE, COLOR_BLACK);
360   init_pair(1, COLOR_WHITE, COLOR_GREEN);
361   init_pair(2, COLOR_BLACK, COLOR_YELLOW);
362
363   int key;
364
365   int current_line = 0, temporary_line = 0;
366
367   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns, noblink);
368
369   do {
370
371     key = getch();
372
373     int motion = 0;
374
375     if(key >= ' ' && key <= 'z') {
376       patterns[patterns_point++] = key;
377       patterns[patterns_point] = '\0';
378     }
379
380     else if(key == KEY_BACKSPACE || key == KEY_DC || key == '\b') {
381       if(patterns_point > 0) {
382         patterns_point--;
383         patterns[patterns_point] = '\0';
384       }
385     }
386
387     else if(key == KEY_UP || key == '\10') {
388       motion = -1;
389     }
390
391     else if(key == KEY_DOWN || key == '\ e') {
392       motion = 1;
393     }
394
395     update_screen(&current_line, &temporary_line, motion,
396                   nb_lines, lines, patterns, noblink);
397   } while(key != '\n' && key != KEY_ENTER && key != '\a');
398
399   echo();
400   curs_set(1);
401   endwin();
402
403   if(output_to_vt_buffer) {
404     if((key == KEY_ENTER || key == '\n') && temporary_line >= 0 && temporary_line < nb_lines) {
405       char *tty = ttyname (STDIN_FILENO);
406       int fd = open(tty, O_WRONLY);
407       write(fd, lines[temporary_line], strlen(lines[temporary_line]));
408       close(fd);
409     }
410   } else {
411
412     ofstream out(output_filename);
413     if(out.fail()) {
414       cerr << "Can not open " << output_filename << " for writing." << endl;
415       exit(1);
416     } else {
417       if((key == KEY_ENTER || key == '\n') && temporary_line >= 0 && temporary_line < nb_lines) {
418         out << lines[temporary_line] << endl;
419       } else {
420         out << endl;
421       }
422       out.flush();
423     }
424   }
425
426   for(int l = 0; l < nb_lines; l++) {
427     delete[] lines[l];
428   }
429
430   exit(0);
431 }