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) 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
44 using namespace std;
45
46 int buffer_size = 1024;
47 int nb_lines_max = 100000;
48 char pattern_separator = ';';
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 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
58   if(n_opt + n >= argc) {
59     cerr << "Missing argument for " << argv[n_opt] << ". Expecting " << help << "." << endl;
60     exit(1);
61   }
62 }
63
64 int previous_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
65   int line = current_line - 1;
66   while(line >= 0 && !match(lines[line], nb_patterns, patterns)) line--;
67   return line;
68 }
69
70 int next_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
71   int line = current_line + 1;
72   while(line < nb_lines && !match(lines[line], nb_patterns, patterns)) line++;
73
74   if(line < nb_lines)
75     return line;
76   else
77     return -1;
78 }
79
80 void update_screen(int *current_line, int *temporary_line, int motion,
81                    int nb_lines, char **lines,
82                    char *pattern_list,
83                    int noblink) {
84
85   char buffer[buffer_size];
86
87   // We split the pattern list into individual patterns
88
89   int nb_patterns = 1;
90
91   for(char *s = pattern_list; *s; s++) {
92     if(*s == pattern_separator) {
93       nb_patterns++;
94     }
95   }
96
97   char splitted_patterns[strlen(pattern_list) + 1];
98   char *patterns[nb_patterns];
99
100   strcpy(splitted_patterns, pattern_list);
101
102   int n = 0;
103   char *last_pattern_start = splitted_patterns;
104   for(char *s = splitted_patterns; n < nb_patterns; s++) {
105     if(*s == pattern_separator || *s == '\0') {
106       *s = '\0';
107       patterns[n++] = last_pattern_start;
108       last_pattern_start = s + 1;
109     }
110   }
111
112   // We now take care of printing the lines per se
113
114   int console_width = getmaxx(stdscr);
115   int console_height = getmaxy(stdscr);
116
117   int nb_printed_lines = 1;
118
119   // First, we find a visible line. In priority: The current, or the
120   // first visible after it, or the first visible before it.
121
122   int new_line;
123   if(match(lines[*current_line], nb_patterns, patterns)) {
124     new_line = *current_line;
125   } else {
126     new_line = next_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
127     if(new_line < 0) {
128       new_line = previous_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
129     }
130   }
131
132   // If we found a visible line and we should move, let's move
133
134   if(new_line >= 0 && motion != 0) {
135     int l = new_line;
136     l += motion;
137
138     if(motion > 0) {
139       // We want to go down, let's find the first visible line below
140       l = next_visible(new_line, nb_lines, lines, nb_patterns, patterns);
141       if(l >= 0) {
142         new_line = l;
143       }
144     } else {
145       // We want to go up, let's find the first visible line above
146       l = previous_visible(new_line, nb_lines, lines, nb_patterns, patterns);
147       if(l >= 0) {
148         new_line = l;
149       }
150     }
151   }
152
153   if(!noblink) {
154     clear();
155   }
156
157   use_default_colors();
158
159   addstr("\n");
160
161   // Here new_line is either a line number matching the patterns, or -1
162
163   if(new_line >= 0) {
164
165     int first_line = new_line, last_line = new_line, nb_match = 1;
166
167     // We find the first and last line to show, so that the total of
168     // visible lines between them (them include) is console_height - 1
169
170     while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
171
172       if(first_line > 0) {
173         first_line--;
174         while(first_line > 0 && !match(lines[first_line], nb_patterns, patterns)) {
175           first_line--;
176         }
177         if(match(lines[first_line], nb_patterns, patterns)) {
178           nb_match++;
179         }
180       }
181
182       if(last_line < nb_lines - 1) {
183         last_line++;
184         while(last_line < nb_lines - 1 && !match(lines[last_line], nb_patterns, patterns)) {
185           last_line++;
186         }
187
188         if(match(lines[last_line], nb_patterns, patterns)) {
189           nb_match++;
190         }
191       }
192     }
193
194     // Now we display them
195
196     for(int l = first_line; l <= last_line; l++) {
197       if(match(lines[l], nb_patterns, patterns)) {
198         int k = 0;
199
200         while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
201           buffer[k] = lines[l][k];
202           k++;
203         }
204
205         if(noblink || l == new_line) {
206           while(k < console_width) {
207             buffer[k++] = ' ';
208           }
209         }
210
211         buffer[k++] = '\n';
212         buffer[k++] = '\0';
213
214         if(l == new_line) {
215           attron(COLOR_PAIR(2));
216           addnstr(buffer, console_width);
217           attroff(COLOR_PAIR(2));
218         } else {
219           addnstr(buffer, console_width);
220         }
221
222         nb_printed_lines++;
223       }
224     }
225
226     *temporary_line = new_line;
227     if(motion != 0) {
228       *current_line = new_line;
229     }
230   }
231
232   if(noblink) { // Erase the rest of the window. That's slightly ugly.
233     int k = 0;
234     while(k < console_width) {
235       buffer[k++] = ' ';
236     }
237     buffer[k++] = '\n';
238     buffer[k++] = '\0';
239     for(int l = nb_printed_lines; l < console_height; l++) {
240       addnstr(buffer, console_width);
241     }
242   }
243
244   // Draw the modeline
245
246   sprintf(buffer, "%d/%d pattern: %s",
247           nb_printed_lines - 1,
248           nb_lines,
249           pattern_list);
250
251   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
252   buffer[console_width] = '\0';
253
254   move(0, 0);
255   attron(COLOR_PAIR(1));
256   addnstr(buffer, console_width);
257   attroff(COLOR_PAIR(1));
258
259   refresh();       // After doing something on the display, we refresh it
260 }
261
262 //////////////////////////////////////////////////////////////////////
263
264 int main(int argc, char **argv) {
265   char buffer[buffer_size];
266   char *lines[nb_lines_max];
267   int noblink = 0;
268
269   char input_filename[buffer_size], output_filename[buffer_size];
270   strcpy(input_filename, "/dev/stdin");
271   strcpy(output_filename, "/tmp/selector.out");
272
273   int i = 1;
274   while(i < argc) {
275     if(strcmp(argv[i], "-o") == 0) {
276       check_opt(argc, argv, i, 1, "<output filename>");
277       strncpy(output_filename, argv[i+1], buffer_size);
278       i += 2;
279     }
280
281     else if(strcmp(argv[i], "-s") == 0) {
282       check_opt(argc, argv, i, 1, "<pattern separator>");
283       pattern_separator = argv[i+1][0];
284       i += 2;
285     }
286
287     else if(strcmp(argv[i], "-f") == 0) {
288       check_opt(argc, argv, i, 1, "<input filename>");
289       strncpy(input_filename, argv[i+1], buffer_size);
290       i += 2;
291     }
292
293     else if(strcmp(argv[i], "-b") == 0) {
294       noblink = 1;
295       i++;
296     }
297
298     else if(strcmp(argv[i], "-l") == 0) {
299       check_opt(argc, argv, i, 1, "<maximum number of lines>");
300       nb_lines_max = atoi(argv[i+1]);
301       i += 2;
302     }
303
304     else {
305       cerr << argv[0] << " [-h] [-o <output filename>] [-b] [-l <max number of lines>] [-s <pattern separator>]" << endl;
306       if(strcmp(argv[i], "-h") == 0) {
307         exit(0);
308       } else {
309         exit(1);
310       }
311     }
312   }
313
314   ifstream file(input_filename);
315
316   if(file.fail()) {
317     cerr << "Can not open \"" << input_filename << "\"" << endl;
318     return 1;
319   }
320
321   int nb_lines = 0;
322   while(nb_lines < nb_lines_max && !file.eof()) {
323     file.getline(buffer, buffer_size);
324     lines[nb_lines] = new char[strlen(buffer) + 1];
325     strcpy(lines[nb_lines], buffer);
326     nb_lines++;
327   }
328
329   char patterns[buffer_size];
330   patterns[0] = '\0';
331   int patterns_point;
332   patterns_point = 0;
333
334   initscr();
335
336   if(!has_colors()) {
337     cerr << "No colors." << endl;
338     return 1;
339   }
340
341   noecho();
342   curs_set(0);
343   keypad(stdscr, TRUE);
344
345   start_color();
346   // init_pair(1, COLOR_WHITE, COLOR_BLACK);
347   init_pair(1, COLOR_WHITE, COLOR_GREEN);
348   init_pair(2, COLOR_BLACK, COLOR_YELLOW);
349
350   int key;
351
352   int current_line = 0, temporary_line = 0;
353
354   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns, noblink);
355
356   do {
357
358     key = getch();
359
360     int motion = 0;
361
362     if(key >= ' ' && key <= 'z') {
363       patterns[patterns_point++] = key;
364       patterns[patterns_point] = '\0';
365     }
366
367     else if(key == KEY_BACKSPACE || key == KEY_DC || key == '\b') {
368       if(patterns_point > 0) {
369         patterns_point--;
370         patterns[patterns_point] = '\0';
371       }
372     }
373
374     else if(key == KEY_UP || key == '\10') {
375       motion = -1;
376     }
377
378     else if(key == KEY_DOWN || key == '\ e') {
379       motion = 1;
380     }
381
382     update_screen(&current_line, &temporary_line, motion,
383                   nb_lines, lines, patterns, noblink);
384   } while(key != '\n' && key != KEY_ENTER && key != '\a');
385
386   echo();
387   curs_set(1);
388   endwin();
389
390   ofstream out(output_filename);
391   if(out.fail()) {
392     cerr << "Can not open " << output_filename << " for writing." << endl;
393     exit(1);
394   } else {
395     if((key == KEY_ENTER || key == '\n') && temporary_line >= 0 && temporary_line < nb_lines) {
396       out << lines[temporary_line] << endl;
397     } else {
398       out << endl;
399     }
400     out.flush();
401   }
402
403   for(int l = 0; l < nb_lines; l++) {
404     delete[] lines[l];
405   }
406
407   exit(0);
408 }