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