Cosmetics.
[selector.git] / selector.cc
1
2 /*
3  *  selector is a simple command line utility for selection of strings
4  *  with a dynamic pattern-matching.
5  *
6  *  Copyright (c) 2009 Francois Fleuret
7  *  Written by Francois Fleuret <francois@fleuret.org>
8  *
9  *  This file is part of selector.
10  *
11  *  selector is free software: you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License version 3 as
13  *  published by the Free Software Foundation.
14  *
15  *  selector is distributed in the hope that it will be useful, but
16  *  WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  *  General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with selector.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 // To use it as a super-history-search for bash:
26 // selector -q -b -i -d -v -w -l 10000 <(history)
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 #include <regex.h>
39
40 using namespace std;
41
42 #define VERSION "1.0"
43
44 const int buffer_size = 4096;
45
46 // Yeah, global variables!
47
48 int nb_lines_max = 1000;
49 char pattern_separator = ';';
50 char label_separator = '\0';
51 int output_to_vt_buffer = 0;
52 int add_control_qs = 0;
53 int with_colors = 1;
54 int zsh_history = 0;
55 int bash_history = 0;
56 int inverse_order = 0;
57 int remove_duplicates = 0;
58 int use_regexp = 0;
59 int case_sensitive = 0;
60 char *title = 0;
61 int error_flash = 0;
62
63 int attr_modeline, attr_focus_line, attr_error;
64
65 //////////////////////////////////////////////////////////////////////
66
67 void inject_into_tty_buffer(char *string) {
68   struct termios oldtio, newtio;
69   tcgetattr(STDIN_FILENO, &oldtio);
70   memset(&newtio, 0, sizeof(newtio));
71   // Set input mode (non-canonical, *no echo*,...)
72   tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
73   const char control_q = '\021';
74   // Put the selected string in the tty input buffer
75   for(const char *k = string; *k; k++) {
76     if(add_control_qs && !(*k >= ' ' && *k <= '~')) {
77       // Add ^Q to quote control characters
78       ioctl(STDIN_FILENO, TIOCSTI, &control_q);
79     }
80     ioctl(STDIN_FILENO, TIOCSTI, k);
81   }
82   // Restore the old settings
83   tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
84 }
85
86 //////////////////////////////////////////////////////////////////////
87
88 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
89   if(n_opt + n >= argc) {
90     cerr << "Missing argument for " << argv[n_opt] << "."
91          << " "
92          << "Expecting " << help << "."
93          << endl;
94     exit(1);
95   }
96 }
97
98 int string_to_positive_integer(char *string) {
99   int error = 0;
100   int result = 0;
101
102   if(*string) {
103     for(char *s = string; *s; s++) {
104       if(*s >= '0' && *s <= '9') {
105         result = result * 10 + int(*s - '0');
106       } else error = 1;
107     }
108   } else error = 1;
109
110   if(error) {
111     cerr << "Value `" << string << "' is not a positive integer." << endl;
112     exit(1);
113   }
114
115   return result;
116 }
117
118 void error_feedback() {
119   if(error_flash) {
120     flash();
121   } else {
122     beep();
123   }
124 }
125
126 //////////////////////////////////////////////////////////////////////
127 // A quick and dirty hash table
128
129 // The table itself stores index of the strings in a char
130 // **table. When a string is added, if it was already in the table,
131 // the new index replaces the previous one.
132
133 int *new_hash_table(int hash_table_size) {
134   int *result;
135   result = new int[hash_table_size];
136   for(int k = 0; k < hash_table_size; k++) {
137     result[k] = -1;
138   }
139   return result;
140 }
141
142 // Adds new_string in the table, associated to new_index. If this
143 // string was not already in the table, returns -1. Otherwise, returns
144 // the previous index it had.
145
146 int test_and_add(char *new_string, int new_index,
147                  char **strings, int *hash_table, int hash_table_size) {
148
149   unsigned int code = 0;
150
151   // This is my recipe. I checked, it seems to work (as long as
152   // hash_table_size is not a multiple of 387433 that should be okay)
153
154   for(int k = 0; new_string[k]; k++) {
155     code = code * 387433 + (unsigned int) (new_string[k]);
156   }
157
158   code = code % hash_table_size;
159
160   while(hash_table[code] >= 0) {
161     // There is a string with that code
162     if(strcmp(new_string, strings[hash_table[code]]) == 0) {
163       // It is the same string, we keep a copy of the stored index
164       int result = hash_table[code];
165       // Put the new one
166       hash_table[code] = new_index;
167       // And return the previous one
168       return result;
169     }
170     // This collision was not the same string, let's move to the next
171     // in the table
172     code = (code + 1) % hash_table_size;
173   }
174
175   // This string was not already in there, store the index in the
176   // table and return -1
177   hash_table[code] = new_index;
178   return -1;
179 }
180
181 //////////////////////////////////////////////////////////////////////
182 // A matcher matches either with a collection of substrings, or with a
183 // regexp
184
185 struct matcher_t {
186   regex_t preg;
187   int regexp_error;
188   int nb_patterns;
189   int case_sensitive;
190   char *splitted_patterns, **patterns;
191 };
192
193 int match(char *string, matcher_t *matcher) {
194   if(matcher->nb_patterns >= 0) {
195     if(matcher->case_sensitive) {
196       for(int n = 0; n < matcher->nb_patterns; n++) {
197         if(strstr(string, matcher->patterns[n]) == 0) return 0;
198       }
199     } else {
200       for(int n = 0; n < matcher->nb_patterns; n++) {
201         if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
202       }
203     }
204     return 1;
205   } else {
206     return regexec(&matcher->preg, string, 0, 0, 0) == 0;
207   }
208 }
209
210 void free_matcher(matcher_t *matcher) {
211   if(matcher->nb_patterns < 0) {
212     if(!matcher->regexp_error) regfree(&matcher->preg);
213   } else {
214     delete[] matcher->splitted_patterns;
215     delete[] matcher->patterns;
216   }
217 }
218
219 void initialize_matcher(int use_regexp, int case_sensitive,
220                         matcher_t *matcher, const char *pattern) {
221
222   if(use_regexp) {
223     matcher->nb_patterns = -1;
224     matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
225   } else {
226     matcher->regexp_error = 0;
227     matcher->nb_patterns = 1;
228     matcher->case_sensitive = case_sensitive;
229
230     for(const char *s = pattern; *s; s++) {
231       if(*s == pattern_separator) {
232         matcher->nb_patterns++;
233       }
234     }
235
236     matcher->splitted_patterns = new char[strlen(pattern) + 1];
237     matcher->patterns = new char*[matcher->nb_patterns];
238
239     strcpy(matcher->splitted_patterns, pattern);
240
241     int n = 0;
242     char *last_pattern_start = matcher->splitted_patterns;
243     for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
244       if(*s == pattern_separator || *s == '\0') {
245         *s = '\0';
246         matcher->patterns[n++] = last_pattern_start;
247         last_pattern_start = s + 1;
248       }
249     }
250   }
251 }
252
253 //////////////////////////////////////////////////////////////////////
254 // Buffer edition
255
256 void delete_char(char *buffer, int *position) {
257   if(buffer[*position]) {
258     int c = *position;
259     while(c < buffer_size && buffer[c]) {
260       buffer[c] = buffer[c+1];
261       c++;
262     }
263   } else error_feedback();
264 }
265
266 void backspace_char(char *buffer, int *position) {
267   if(*position > 0) {
268     if(buffer[*position]) {
269       int c = *position - 1;
270       while(buffer[c]) {
271         buffer[c] = buffer[c+1];
272         c++;
273       }
274     } else {
275       buffer[*position - 1] = '\0';
276     }
277
278     (*position)--;
279   } else error_feedback();
280 }
281
282 void insert_char(char *buffer, int *position, char character) {
283   if(strlen(buffer) < buffer_size - 1) {
284     int c = *position;
285     char t = buffer[c], u;
286     while(t) {
287       c++;
288       u = buffer[c];
289       buffer[c] = t;
290       t = u;
291     }
292     c++;
293     buffer[c] = '\0';
294     buffer[(*position)++] = character;
295   } else error_feedback();
296 }
297
298 void kill_before_cursor(char *buffer, int *position) {
299   int s = 0;
300   while(buffer[*position + s]) {
301     buffer[s] = buffer[*position + s];
302     s++;
303   }
304   buffer[s] = '\0';
305   *position = 0;
306 }
307
308 void kill_after_cursor(char *buffer, int *position) {
309   buffer[*position] = '\0';
310 }
311
312 //////////////////////////////////////////////////////////////////////
313
314 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
315   int line = current_line - 1;
316   while(line >= 0 && !match(lines[line], matcher)) line--;
317   return line;
318 }
319
320 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
321   int line = current_line + 1;
322   while(line < nb_lines && !match(lines[line], matcher)) line++;
323
324   if(line < nb_lines)
325     return line;
326   else
327     return -1;
328 }
329
330 //////////////////////////////////////////////////////////////////////
331
332 // The value passed to this routine in current_focus_line is the index
333 // of the line to highlighted if it matches the matcher. The line
334 // highlighted is the first the one matching the matcher in that
335 // order: The current_focus_line itself, the first with a greated
336 // index, the first with a lesser index.
337
338 // The index of the line actually shown highlighted is written in
339 // displayed_focus_line (it can be -1)
340
341 // If there is a motion and a line is actually shown highlighted, its
342 // value is written in current_focus_line
343
344 void update_screen(int *current_focus_line, int *displayed_focus_line,
345                    int motion,
346                    int nb_lines, char **lines,
347                    int cursor_position,
348                    char *pattern) {
349
350   char buffer[buffer_size];
351   matcher_t matcher;
352
353   initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
354
355   int console_width = getmaxx(stdscr);
356   int console_height = getmaxy(stdscr);
357
358   // First, we find a visible line. In priority: The current, or the
359   // first visible after it, or the first visible before it.
360
361   int nb_printed_lines = 0;
362
363   use_default_colors();
364   addstr("\n");
365
366   if(matcher.regexp_error) {
367     attron(attr_error);
368     addnstr("Regexp syntax error", console_width);
369     attroff(attr_error);
370   } else if(nb_lines > 0) {
371     int new_focus_line;
372     if(match(lines[*current_focus_line], &matcher)) {
373       new_focus_line = *current_focus_line;
374     } else {
375       new_focus_line = next_visible(*current_focus_line, nb_lines, lines, &matcher);
376       if(new_focus_line < 0) {
377         new_focus_line = previous_visible(*current_focus_line, nb_lines, lines, &matcher);
378       }
379     }
380
381     // If we found a visible line and we should move, let's move
382
383     if(new_focus_line >= 0 && motion != 0) {
384       int l = new_focus_line;
385       if(motion > 0) {
386         // We want to go down, let's find the first visible line below
387         for(int m = 0; l >= 0 && m < motion; m++) {
388           l = next_visible(l, nb_lines, lines, &matcher);
389           if(l >= 0) {
390             new_focus_line = l;
391           }
392         }
393       } else {
394         // We want to go up, let's find the first visible line above
395         for(int m = 0; l >= 0 && m < -motion; m++) {
396           l = previous_visible(l, nb_lines, lines, &matcher);
397           if(l >= 0) {
398             new_focus_line = l;
399           }
400         }
401       }
402     }
403
404     // Here new_focus_line is either a line number matching the pattern, or -1
405
406     if(new_focus_line >= 0) {
407
408       int first_line = new_focus_line, last_line = new_focus_line, nb_match = 1;
409
410       // We find the first and last line to show, so that the total of
411       // visible lines between them (them included) is console_height-1
412
413       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
414
415         if(first_line > 0) {
416           first_line--;
417           while(first_line > 0 && !match(lines[first_line], &matcher)) {
418             first_line--;
419           }
420           if(match(lines[first_line], &matcher)) {
421             nb_match++;
422           }
423         }
424
425         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
426           last_line++;
427           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
428             last_line++;
429           }
430
431           if(match(lines[last_line], &matcher)) {
432             nb_match++;
433           }
434         }
435       }
436
437       // Now we display them
438
439       for(int l = first_line; l <= last_line; l++) {
440         if(match(lines[l], &matcher)) {
441           int k = 0;
442
443           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
444             buffer[k] = lines[l][k];
445             k++;
446           }
447
448           // We fill the rest of the line with blanks if this is the
449           // highlighted line
450
451           if(l == new_focus_line) {
452             while(k < console_width) {
453               buffer[k++] = ' ';
454             }
455           }
456
457           buffer[k++] = '\n';
458           buffer[k++] = '\0';
459
460           clrtoeol();
461
462           // Highlight the highlighted line ...
463
464           if(l == new_focus_line) {
465             attron(attr_focus_line);
466             addnstr(buffer, console_width);
467             attroff(attr_focus_line);
468           } else {
469             addnstr(buffer, console_width);
470           }
471
472           nb_printed_lines++;
473         }
474       }
475
476       // If we are on a focused line and we moved, this become the new
477       // focus line
478
479       if(motion != 0) {
480         *current_focus_line = new_focus_line;
481       }
482     }
483
484     *displayed_focus_line = new_focus_line;
485
486     if(nb_printed_lines == 0) {
487       attron(attr_error);
488       addnstr("No selection", console_width);
489       attroff(attr_error);
490     }
491   } else {
492     attron(attr_error);
493     addnstr("Empty choice", console_width);
494     attroff(attr_error);
495   }
496
497   clrtobot();
498
499   // Draw the modeline
500
501   move(0, 0);
502
503   attron(attr_modeline);
504
505   for(int k = 0; k < console_width; k++) buffer[k] = ' ';
506   buffer[console_width] = '\0';
507   addnstr(buffer, console_width);
508
509   move(0, 0);
510
511   // There must be a more elegant way of moving the cursor at a
512   // location met during display
513
514   int cursor_x = 0;
515
516   if(title) {
517     addstr(title);
518     addstr(" ");
519     cursor_x += strlen(title) + 1;
520   }
521
522   sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
523   addstr(buffer);
524   cursor_x += strlen(buffer);
525
526   addnstr(pattern, cursor_position);
527   cursor_x += cursor_position;
528
529   if(pattern[cursor_position]) {
530     addstr(pattern + cursor_position);
531   } else {
532     addstr(" ");
533   }
534
535   if(use_regexp || case_sensitive) {
536     addstr(" [");
537     if(use_regexp) {
538       addstr("regexp");
539     }
540
541     if(case_sensitive) {
542       if(use_regexp) {
543         addstr(",");
544       }
545       addstr("case");
546     }
547     addstr("]");
548   }
549
550   move(0, cursor_x);
551
552   attroff(attr_modeline);
553
554   // We are done
555
556   refresh();
557   free_matcher(&matcher);
558 }
559
560 //////////////////////////////////////////////////////////////////////
561
562 void read_file(const char *input_filename,
563                int nb_lines_max, int *nb_lines, char **lines,
564                int hash_table_size, int *hash_table) {
565
566   char raw_line[buffer_size];;
567
568   ifstream file(input_filename);
569
570   if(file.fail()) {
571     cerr << "Can not open " << input_filename << endl;
572     exit(1);
573   }
574
575   while(*nb_lines < nb_lines_max && !file.eof()) {
576
577     file.getline(raw_line, buffer_size);
578
579     if(raw_line[0]) {
580
581       if(file.fail()) {
582         cerr << "Line too long:" << endl;
583         cerr << raw_line << endl;
584         exit(1);
585       }
586
587       char *t;
588
589       t = raw_line;
590
591       // Remove the zsh history prefix
592
593       if(zsh_history && *t == ':') {
594         while(*t && *t != ';') t++;
595         if(*t == ';') t++;
596       }
597
598       // Remove the bash history prefix
599
600       if(bash_history) {
601         while(*t == ' ') t++;
602         while(*t >= '0' && *t <= '9') t++;
603         while(*t == ' ') t++;
604       }
605
606       // Check for duplicates with the hash table and insert the line
607       // in the list if necessary
608
609       int dup;
610
611       if(hash_table) {
612         dup = test_and_add(t, *nb_lines, lines, hash_table, hash_table_size);
613       } else {
614         dup = -1;
615       }
616
617       if(dup < 0) {
618         lines[*nb_lines] = new char[strlen(t) + 1];
619         strcpy(lines[*nb_lines], t);
620       } else {
621         // The string was already in there, so we do not allocate a
622         // new string but use the pointer to the first occurence of it
623         lines[*nb_lines] = lines[dup];
624         lines[dup] = 0;
625       }
626
627       (*nb_lines)++;
628     }
629   }
630 }
631
632 //////////////////////////////////////////////////////////////////////
633
634 int main(int argc, char **argv) {
635
636   if(!ttyname(STDIN_FILENO)) {
637     cerr << "The standard input is not a tty." << endl;
638     exit(1);
639   }
640
641   int color_fg_modeline, color_bg_modeline;
642   int color_fg_highlight, color_bg_highlight;
643
644   color_fg_modeline  = COLOR_WHITE;
645   color_bg_modeline  = COLOR_BLACK;
646   color_fg_highlight = COLOR_BLACK;
647   color_bg_highlight = COLOR_YELLOW;
648
649   setlocale(LC_ALL, "");
650
651   char input_filename[buffer_size], output_filename[buffer_size];
652
653   strcpy(input_filename, "");
654   strcpy(output_filename, "");
655
656   int i = 1;
657   int error = 0, show_help = 0;
658   int rest_are_files = 0;
659
660   while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
661
662     if(strcmp(argv[i], "-o") == 0) {
663       check_opt(argc, argv, i, 1, "<output filename>");
664       strncpy(output_filename, argv[i+1], buffer_size);
665       i += 2;
666     }
667
668     else if(strcmp(argv[i], "-s") == 0) {
669       check_opt(argc, argv, i, 1, "<pattern separator>");
670       pattern_separator = argv[i+1][0];
671       i += 2;
672     }
673
674     else if(strcmp(argv[i], "-x") == 0) {
675       check_opt(argc, argv, i, 1, "<label separator>");
676       label_separator = argv[i+1][0];
677       i += 2;
678     }
679
680     else if(strcmp(argv[i], "-v") == 0) {
681       output_to_vt_buffer = 1;
682       i++;
683     }
684
685     else if(strcmp(argv[i], "-w") == 0) {
686       add_control_qs = 1;
687       i++;
688     }
689
690     else if(strcmp(argv[i], "-m") == 0) {
691       with_colors = 0;
692       i++;
693     }
694
695     else if(strcmp(argv[i], "-q") == 0) {
696       error_flash = 1;
697       i++;
698     }
699
700     else if(strcmp(argv[i], "-f") == 0) {
701       check_opt(argc, argv, i, 1, "<input filename>");
702       strncpy(input_filename, argv[i+1], buffer_size);
703       i += 2;
704     }
705
706     else if(strcmp(argv[i], "-i") == 0) {
707       inverse_order = 1;
708       i++;
709     }
710
711     else if(strcmp(argv[i], "-b") == 0) {
712       bash_history = 1;
713       i++;
714     }
715
716     else if(strcmp(argv[i], "-z") == 0) {
717       zsh_history = 1;
718       i++;
719     }
720
721     else if(strcmp(argv[i], "-d") == 0) {
722       remove_duplicates = 1;
723       i++;
724     }
725
726     else if(strcmp(argv[i], "-e") == 0) {
727       use_regexp = 1;
728       i++;
729     }
730
731     else if(strcmp(argv[i], "-a") == 0) {
732       case_sensitive = 1;
733       i++;
734     }
735
736     else if(strcmp(argv[i], "-t") == 0) {
737       check_opt(argc, argv, i, 1, "<title>");
738       delete[] title;
739       title = new char[strlen(argv[i+1]) + 1];
740       strcpy(title, argv[i+1]);
741       i += 2;
742     }
743
744     else if(strcmp(argv[i], "-l") == 0) {
745       check_opt(argc, argv, i, 1, "<maximum number of lines>");
746       nb_lines_max = string_to_positive_integer(argv[i+1]);
747       i += 2;
748     }
749
750     else if(strcmp(argv[i], "-c") == 0) {
751       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
752       color_fg_modeline = string_to_positive_integer(argv[i + 1]);
753       color_bg_modeline = string_to_positive_integer(argv[i + 2]);
754       color_fg_highlight = string_to_positive_integer(argv[i + 3]);
755       color_bg_highlight = string_to_positive_integer(argv[i + 4]);
756       i += 5;
757     }
758
759     else if(strcmp(argv[i], "--") == 0) {
760       rest_are_files = 1;
761       i++;
762     }
763
764     else if(strcmp(argv[i], "-h") == 0) {
765       show_help = 1;
766       i++;
767     }
768
769     else {
770       cerr << "Unknown option " << argv[i] << "." << endl;
771       error = 1;
772     }
773   }
774
775   if(show_help || error) {
776     cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
777          << endl
778          << "Written by Francois Fleuret <francois@fleuret.org>."
779          << endl
780          << endl
781          << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
782          << endl
783          << " -h      show this help" << endl
784          << " -v      inject the selected line in the tty" << endl
785          << " -w      quote control characters with ^Qs when using -v" << endl
786          << " -d      remove duplicated lines" << endl
787          << " -b      remove the bash history line prefix" << endl
788          << " -z      remove the zsh history line prefix" << endl
789          << " -i      invert the order of lines" << endl
790          << " -e      start in regexp mode" << endl
791          << " -a      case sensitive" << endl
792          << " -m      monochrome mode" << endl
793          << " -q      make a flash instead of a beep on an edition error" << endl
794          << " --      all following arguments are filenames" << endl
795          << " -t <title>" << endl
796          << "         add a title in the modeline" << endl
797          << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
798          << "         set the display colors" << endl
799          << " -o <output filename>" << endl
800          << "         set a file to write the selected line to" << endl
801          << " -s <pattern separator>" << endl
802          << "         set the symbol to separate substrings in the pattern" << endl
803          << " -x <label separator>" << endl
804          << "         set the symbol to terminate the label" << endl
805          << " -l <max number of lines>" << endl
806          << "         set the maximum number of lines to take into account" << endl
807          << endl;
808
809     exit(error);
810   }
811
812   char **lines = new char *[nb_lines_max];
813
814   int nb_lines = 0;
815   int hash_table_size = nb_lines_max * 10;
816   int *hash_table = 0;
817
818   if(remove_duplicates) {
819     hash_table = new_hash_table(hash_table_size);
820   }
821
822   if(input_filename[0]) {
823     read_file(input_filename,
824               nb_lines_max, &nb_lines, lines,
825               hash_table_size, hash_table);
826   }
827
828   while(i < argc) {
829     read_file(argv[i],
830               nb_lines_max, &nb_lines, lines,
831               hash_table_size, hash_table);
832     i++;
833   }
834
835   delete[] hash_table;
836
837   // Now remove the null strings
838
839   int n = 0;
840   for(int k = 0; k < nb_lines; k++) {
841     if(lines[k]) {
842       lines[n++] = lines[k];
843     }
844   }
845
846   nb_lines = n;
847
848   if(inverse_order) {
849     for(int i = 0; i < nb_lines / 2; i++) {
850       char *s = lines[nb_lines - 1 - i];
851       lines[nb_lines - 1 - i] = lines[i];
852       lines[i] = s;
853     }
854   }
855
856   // Build the labels from the strings, take only the part before the
857   // label_separator and transform control characters to printable
858   // ones
859
860   char **labels = new char *[nb_lines];
861   for(int l = 0; l < nb_lines; l++) {
862     char *s, *t;
863     const char *u;
864     t = lines[l];
865     int e = 0;
866     while(*t && *t != label_separator) {
867       u = unctrl(*t++);
868       e += strlen(u);
869     }
870     labels[l] = new char[e + 1];
871     t = lines[l];
872     s = labels[l];
873     while(*t && *t != label_separator) {
874       u = unctrl(*t++);
875       while(*u) { *s++ = *u++; }
876     }
877     *s = '\0';
878   }
879
880   char pattern[buffer_size];
881   pattern[0] = '\0';
882
883   int cursor_position;
884   cursor_position = 0;
885
886   //////////////////////////////////////////////////////////////////////
887   // Here we start to display with curse
888
889   initscr();
890
891   noecho();
892
893   // So that the arrow keys work
894   keypad(stdscr, TRUE);
895
896   attr_error = A_STANDOUT;
897   attr_modeline = A_REVERSE;
898   attr_focus_line = A_STANDOUT;
899
900   if(with_colors && has_colors()) {
901
902     start_color();
903
904     if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
905        color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
906        color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
907        color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
908       echo();
909       endwin();
910       cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
911       exit(1);
912     }
913
914     init_pair(1, color_fg_modeline, color_bg_modeline);
915     attr_modeline = COLOR_PAIR(1);
916
917     init_pair(2, color_fg_highlight, color_bg_highlight);
918     attr_focus_line = COLOR_PAIR(2);
919
920     init_pair(3, COLOR_WHITE, COLOR_RED);
921     attr_error = COLOR_PAIR(3);
922
923   }
924
925   int key;
926   int current_focus_line = 0, displayed_focus_line = 0;
927
928   update_screen(&current_focus_line, &displayed_focus_line,
929                 0,
930                 nb_lines, labels, cursor_position, pattern);
931
932   do {
933
934     key = getch();
935
936     int motion = 0;
937
938     if(key >= ' ' && key <= '~') { // Insert character
939       insert_char(pattern, &cursor_position, key);
940     }
941
942     else if(key == KEY_BACKSPACE ||
943             key == '\010' || // ^H
944             key == '\177') { // ^?
945       backspace_char(pattern, &cursor_position);
946     }
947
948     else if(key == KEY_DC ||
949             key == '\004') { // ^D
950       delete_char(pattern, &cursor_position);
951     }
952
953     else if(key == KEY_HOME) {
954       current_focus_line = 0;
955     }
956
957     else if(key == KEY_END) {
958       current_focus_line = nb_lines - 1;
959     }
960
961     else if(key == KEY_NPAGE) {
962       motion = 10;
963     }
964
965     else if(key == KEY_PPAGE) {
966       motion = -10;
967     }
968
969     else if(key == KEY_DOWN ||
970             key == '\016') { // ^N
971       motion = 1;
972     }
973
974     else if(key == KEY_UP ||
975             key == '\020') { // ^P
976       motion = -1;
977     }
978
979     else if(key == KEY_LEFT ||
980             key == '\002') { // ^B
981       if(cursor_position > 0) cursor_position--;
982       else error_feedback();
983     }
984
985     else if(key == KEY_RIGHT ||
986             key == '\006') { // ^F
987       if(pattern[cursor_position]) cursor_position++;
988       else error_feedback();
989     }
990
991     else if(key == '\001') { // ^A
992       cursor_position = 0;
993     }
994
995     else if(key == '\005') { // ^E
996       cursor_position = strlen(pattern);
997     }
998
999     else if(key == '\022') { // ^R
1000       use_regexp = !use_regexp;
1001     }
1002
1003     else if(key == '\011') { // ^I
1004       case_sensitive = !case_sensitive;
1005     }
1006
1007     else if(key == '\025') { // ^U
1008       kill_before_cursor(pattern, &cursor_position);
1009     }
1010
1011     else if(key == '\013') { // ^K
1012       kill_after_cursor(pattern, &cursor_position);
1013     }
1014
1015     else if(key == '\014') { // ^L
1016       // I suspect that we may sometime mess up the display
1017       clear();
1018     }
1019
1020     update_screen(&current_focus_line, &displayed_focus_line,
1021                   motion,
1022                   nb_lines, labels, cursor_position, pattern);
1023
1024   } while(key != '\007' && // ^G
1025           key != '\033' && // ^[ (escape)
1026           key != '\n' &&
1027           key != KEY_ENTER);
1028
1029   echo();
1030   endwin();
1031
1032   //////////////////////////////////////////////////////////////////////
1033   // Here we come back to standard display
1034
1035   if((key == KEY_ENTER || key == '\n')) {
1036
1037     if(output_to_vt_buffer) {
1038       if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1039         inject_into_tty_buffer(lines[displayed_focus_line]);
1040       }
1041     }
1042
1043     if(output_filename[0]) {
1044       ofstream out(output_filename);
1045       if(out.fail()) {
1046         cerr << "Can not open " << output_filename << " for writing." << endl;
1047         exit(1);
1048       } else {
1049         if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1050           out << lines[displayed_focus_line] << endl;
1051         } else {
1052           out << endl;
1053         }
1054       }
1055       out.flush();
1056     }
1057   } else {
1058     cout << "Aborted." << endl;
1059   }
1060
1061   for(int l = 0; l < nb_lines; l++) {
1062     delete[] lines[l];
1063     delete[] labels[l];
1064   }
1065
1066   delete[] labels;
1067   delete[] lines;
1068   delete[] title;
1069
1070   exit(0);
1071 }