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