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