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, bash_history = 0;
55 int inverse_order = 0;
56 int remove_duplicates = 0;
57 int use_regexp = 0;
58 int case_sensitive = 0;
59 char *title = 0;
60 int error_flash = 0;
61
62 #define COLOR_MODELINE 1
63 #define COLOR_HIGHLIGHTED_LINE 2
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 void update_screen(int *current_line, int *temporary_line, int motion,
333                    int nb_lines, char **lines,
334                    int cursor_position,
335                    char *pattern) {
336
337   char buffer[buffer_size];
338   matcher_t matcher;
339
340   initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
341
342   // We now take care of printing the lines per se
343
344   int console_width = getmaxx(stdscr);
345   int console_height = getmaxy(stdscr);
346
347   // First, we find a visible line. In priority: The current, or the
348   // first visible after it, or the first visible before it.
349
350   int nb_printed_lines = 0;
351
352   use_default_colors();
353   addstr("\n");
354
355   if(matcher.regexp_error) {
356     addstr("[regexp error]");
357   } else if(nb_lines > 0) {
358     int new_line;
359     if(match(lines[*current_line], &matcher)) {
360       new_line = *current_line;
361     } else {
362       new_line = next_visible(*current_line, nb_lines, lines, &matcher);
363       if(new_line < 0) {
364         new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
365       }
366     }
367
368     // If we found a visible line and we should move, let's move
369
370     if(new_line >= 0 && motion != 0) {
371       int l = new_line;
372       if(motion > 0) {
373         // We want to go down, let's find the first visible line below
374         for(int m = 0; l >= 0 && m < motion; m++) {
375           l = next_visible(l, nb_lines, lines, &matcher);
376           if(l >= 0) {
377             new_line = l;
378           }
379         }
380       } else {
381         // We want to go up, let's find the first visible line above
382         for(int m = 0; l >= 0 && m < -motion; m++) {
383           l = previous_visible(l, nb_lines, lines, &matcher);
384           if(l >= 0) {
385             new_line = l;
386           }
387         }
388       }
389     }
390
391     // Here new_line is either a line number matching the patterns, or -1
392
393     if(new_line >= 0) {
394
395       int first_line = new_line, last_line = new_line, nb_match = 1;
396
397       // We find the first and last line to show, so that the total of
398       // visible lines between them (them included) is console_height-1
399
400       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
401
402         if(first_line > 0) {
403           first_line--;
404           while(first_line > 0 && !match(lines[first_line], &matcher)) {
405             first_line--;
406           }
407           if(match(lines[first_line], &matcher)) {
408             nb_match++;
409           }
410         }
411
412         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
413           last_line++;
414           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
415             last_line++;
416           }
417
418           if(match(lines[last_line], &matcher)) {
419             nb_match++;
420           }
421         }
422       }
423
424       // Now we display them
425
426       for(int l = first_line; l <= last_line; l++) {
427         if(match(lines[l], &matcher)) {
428           int k = 0;
429
430           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
431             buffer[k] = lines[l][k];
432             k++;
433           }
434
435           // We fill the rest of the line with blanks if this is the
436           // highlighted line
437
438           if(l == new_line) {
439             while(k < console_width) {
440               buffer[k++] = ' ';
441             }
442           }
443
444           buffer[k++] = '\n';
445           buffer[k++] = '\0';
446
447           clrtoeol();
448
449           // Highlight the highlighted line ...
450
451           if(l == new_line) {
452             if(with_colors) {
453               attron(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
454               addnstr(buffer, console_width);
455               attroff(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
456             } else {
457               attron(A_STANDOUT);
458               addnstr(buffer, console_width);
459               attroff(A_STANDOUT);
460             }
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       addnstr("[no selection]\n", console_width);
478     }
479   } else {
480     addnstr("[empty choice]\n", console_width);
481   }
482
483   clrtobot();
484
485   // Draw the modeline
486
487   move(0, 0);
488
489   if(with_colors) {
490     attron(COLOR_PAIR(COLOR_MODELINE));
491   } else {
492     attron(A_REVERSE);
493   }
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   if(with_colors) {
543     attroff(COLOR_PAIR(COLOR_MODELINE));
544   } else {
545     attroff(A_REVERSE);
546   }
547
548   // We are done
549
550   refresh();
551   free_matcher(&matcher);
552 }
553
554 //////////////////////////////////////////////////////////////////////
555
556 void read_file(const char *input_filename,
557                int nb_lines_max, int *nb_lines, char **lines,
558                int hash_table_size, int *hash_table) {
559
560   char raw_line[buffer_size];;
561
562   ifstream file(input_filename);
563
564   if(file.fail()) {
565     cerr << "Can not open " << input_filename << endl;
566     exit(1);
567   }
568
569   while(*nb_lines < nb_lines_max && !file.eof()) {
570
571     file.getline(raw_line, buffer_size);
572
573     if(raw_line[0]) {
574
575       if(file.fail()) {
576         cerr << "Line too long:" << endl;
577         cerr << raw_line << endl;
578         exit(1);
579       }
580
581       char *t;
582
583       t = raw_line;
584
585       // Remove the zsh history prefix
586
587       if(zsh_history && *t == ':') {
588         while(*t && *t != ';') t++;
589         if(*t == ';') t++;
590       }
591
592       // Remove the bash history prefix
593
594       if(bash_history) {
595         while(*t == ' ') t++;
596         while(*t >= '0' && *t <= '9') t++;
597         while(*t == ' ') t++;
598       }
599
600       // Check for duplicates with the hash table and insert the line
601       // in the list if necessary
602
603       int dup;
604
605       if(hash_table) {
606         dup = test_and_add(t, *nb_lines, lines, hash_table, hash_table_size);
607       } else {
608         dup = -1;
609       }
610
611       if(dup < 0) {
612         lines[*nb_lines] = new char[strlen(t) + 1];
613         strcpy(lines[*nb_lines], t);
614       } else {
615         // The string was already in there, so we do not allocate a
616         // new string but use the pointer to the first occurence of it
617         lines[*nb_lines] = lines[dup];
618         lines[dup] = 0;
619       }
620
621       (*nb_lines)++;
622     }
623   }
624 }
625
626 //////////////////////////////////////////////////////////////////////
627
628 int main(int argc, char **argv) {
629
630   if(!ttyname(STDIN_FILENO)) {
631     cerr << "The standard input is not a tty." << endl;
632     exit(1);
633   }
634
635   int color_fg_modeline, color_bg_modeline;
636   int color_fg_highlight, color_bg_highlight;
637
638   color_fg_modeline  = COLOR_WHITE;
639   color_bg_modeline  = COLOR_BLACK;
640   color_fg_highlight = COLOR_BLACK;
641   color_bg_highlight = COLOR_YELLOW;
642
643   setlocale(LC_ALL, "");
644
645   char input_filename[buffer_size], output_filename[buffer_size];
646
647   strcpy(input_filename, "");
648   strcpy(output_filename, "");
649
650   int i = 1;
651   int error = 0, show_help = 0;
652   int rest_are_files = 0;
653
654   while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
655
656     if(strcmp(argv[i], "-o") == 0) {
657       check_opt(argc, argv, i, 1, "<output filename>");
658       strncpy(output_filename, argv[i+1], buffer_size);
659       i += 2;
660     }
661
662     else if(strcmp(argv[i], "-s") == 0) {
663       check_opt(argc, argv, i, 1, "<pattern separator>");
664       pattern_separator = argv[i+1][0];
665       i += 2;
666     }
667
668     else if(strcmp(argv[i], "-x") == 0) {
669       check_opt(argc, argv, i, 1, "<label separator>");
670       label_separator = argv[i+1][0];
671       i += 2;
672     }
673
674     else if(strcmp(argv[i], "-v") == 0) {
675       output_to_vt_buffer = 1;
676       i++;
677     }
678
679     else if(strcmp(argv[i], "-w") == 0) {
680       add_control_qs = 1;
681       i++;
682     }
683
684     else if(strcmp(argv[i], "-m") == 0) {
685       with_colors = 0;
686       i++;
687     }
688
689     else if(strcmp(argv[i], "-q") == 0) {
690       error_flash = 1;
691       i++;
692     }
693
694     else if(strcmp(argv[i], "-f") == 0) {
695       check_opt(argc, argv, i, 1, "<input filename>");
696       strncpy(input_filename, argv[i+1], buffer_size);
697       i += 2;
698     }
699
700     else if(strcmp(argv[i], "-i") == 0) {
701       inverse_order = 1;
702       i++;
703     }
704
705     else if(strcmp(argv[i], "-b") == 0) {
706       bash_history = 1;
707       i++;
708     }
709
710     else if(strcmp(argv[i], "-z") == 0) {
711       zsh_history = 1;
712       i++;
713     }
714
715     else if(strcmp(argv[i], "-d") == 0) {
716       remove_duplicates = 1;
717       i++;
718     }
719
720     else if(strcmp(argv[i], "-e") == 0) {
721       use_regexp = 1;
722       i++;
723     }
724
725     else if(strcmp(argv[i], "-a") == 0) {
726       case_sensitive = 1;
727       i++;
728     }
729
730     else if(strcmp(argv[i], "-t") == 0) {
731       check_opt(argc, argv, i, 1, "<title>");
732       delete[] title;
733       title = new char[strlen(argv[i+1]) + 1];
734       strcpy(title, argv[i+1]);
735       i += 2;
736     }
737
738     else if(strcmp(argv[i], "-l") == 0) {
739       check_opt(argc, argv, i, 1, "<maximum number of lines>");
740       nb_lines_max = string_to_positive_integer(argv[i+1]);
741       i += 2;
742     }
743
744     else if(strcmp(argv[i], "-c") == 0) {
745       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
746       color_fg_modeline = string_to_positive_integer(argv[i + 1]);
747       color_bg_modeline = string_to_positive_integer(argv[i + 2]);
748       color_fg_highlight = string_to_positive_integer(argv[i + 3]);
749       color_bg_highlight = string_to_positive_integer(argv[i + 4]);
750       i += 5;
751     }
752
753     else if(strcmp(argv[i], "--") == 0) {
754       rest_are_files = 1;
755       i++;
756     }
757
758     else if(strcmp(argv[i], "-h") == 0) {
759       show_help = 1;
760       i++;
761     }
762
763     else {
764       cerr << "Unknown option " << argv[i] << "." << endl;
765       error = 1;
766     }
767   }
768
769   if(show_help || error) {
770     cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
771          << endl
772          << "Written by Francois Fleuret <francois@fleuret.org>."
773          << endl
774          << endl
775          << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
776          << endl
777          << " -h      show this help" << endl
778          << " -v      inject the selected line in the tty" << endl
779          << " -d      remove duplicated lines" << endl
780          << " -b      remove the bash history line prefix" << endl
781          << " -z      remove the zsh history line prefix" << endl
782          << " -i      invert the order of lines" << endl
783          << " -e      start in regexp mode" << endl
784          << " -a      case sensitive" << endl
785          << " -m      monochrome mode" << endl
786          << " -q      make a flash instead of a beep on an edition error" << endl
787          << " --      rest of the arguments are filenames" << endl
788          << " -t <title>" << endl
789          << "         add a title in the modeline" << endl
790          << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
791          << "         set the display colors" << endl
792          << " -o <output filename>" << endl
793          << "         set a file to write the selected line to" << endl
794          << " -s <pattern separator>" << endl
795          << "         set the symbol to separate substrings in the pattern" << endl
796          << " -x <label separator>" << endl
797          << "         set the symbol to terminate the label" << endl
798          << " -l <max number of lines>" << endl
799          << "         set the maximum number of lines to take into account" << endl
800          << endl;
801
802     exit(error);
803   }
804
805   char **lines = new char *[nb_lines_max];
806
807   int nb_lines = 0;
808   int hash_table_size = nb_lines_max * 10;
809   int *hash_table = 0;
810
811   if(remove_duplicates) {
812     hash_table = new_hash_table(hash_table_size);
813   }
814
815   if(input_filename[0]) {
816     read_file(input_filename,
817               nb_lines_max, &nb_lines, lines,
818               hash_table_size, hash_table);
819   }
820
821   while(i < argc) {
822     read_file(argv[i],
823               nb_lines_max, &nb_lines, lines,
824               hash_table_size, hash_table);
825     i++;
826   }
827
828   delete[] hash_table;
829
830   // Now remove the null strings
831
832   int n = 0;
833   for(int k = 0; k < nb_lines; k++) {
834     if(lines[k]) {
835       lines[n++] = lines[k];
836     }
837   }
838
839   nb_lines = n;
840
841   if(inverse_order) {
842     for(int i = 0; i < nb_lines / 2; i++) {
843       char *s = lines[nb_lines - 1 - i];
844       lines[nb_lines - 1 - i] = lines[i];
845       lines[i] = s;
846     }
847   }
848
849   // Build the labels from the strings, take only the part before the
850   // label_separator and transform control characters to printable
851   // ones
852
853   char **labels = new char *[nb_lines];
854   for(int l = 0; l < nb_lines; l++) {
855     char *s, *t;
856     const char *u;
857     t = lines[l];
858     int e = 0;
859     while(*t && *t != label_separator) {
860       u = unctrl(*t++);
861       e += strlen(u);
862     }
863     labels[l] = new char[e + 1];
864     t = lines[l];
865     s = labels[l];
866     while(*t && *t != label_separator) {
867       u = unctrl(*t++);
868       while(*u) { *s++ = *u++; }
869     }
870     *s = '\0';
871   }
872
873   char pattern[buffer_size];
874   pattern[0] = '\0';
875
876   int cursor_position;
877   cursor_position = 0;
878
879   //////////////////////////////////////////////////////////////////////
880   // Here we start to display with curse
881
882   initscr();
883
884   noecho();
885
886   // So that the arrow keys work
887   keypad(stdscr, TRUE);
888
889   if(with_colors) {
890
891     if(has_colors()) {
892
893       start_color();
894
895       if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
896          color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
897          color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
898          color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
899         echo();
900         endwin();
901         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
902         exit(1);
903       }
904
905       init_pair(COLOR_MODELINE, color_fg_modeline, color_bg_modeline);
906       init_pair(COLOR_HIGHLIGHTED_LINE, color_fg_highlight, color_bg_highlight);
907
908     } else {
909       with_colors = 0;
910     }
911   }
912
913   int key;
914   int current_line = 0, temporary_line = 0;
915
916   update_screen(&current_line, &temporary_line, 0,
917                 nb_lines, labels, cursor_position, pattern);
918
919   do {
920
921     key = getch();
922
923     int motion = 0;
924
925     if(key >= ' ' && key <= '~') { // Insert character
926       insert_char(pattern, &cursor_position, key);
927     }
928
929     else if(key == KEY_BACKSPACE ||
930             key == '\010' || // ^H
931             key == '\177') { // ^?
932       backspace_char(pattern, &cursor_position);
933     }
934
935     else if(key == KEY_DC ||
936             key == '\004') { // ^D
937       delete_char(pattern, &cursor_position);
938     }
939
940     else if(key == KEY_HOME) {
941       current_line = 0;
942     }
943
944     else if(key == KEY_END) {
945       current_line = nb_lines - 1;
946     }
947
948     else if(key == KEY_NPAGE) {
949       motion = 10;
950     }
951
952     else if(key == KEY_PPAGE) {
953       motion = -10;
954     }
955
956     else if(key == KEY_DOWN ||
957             key == '\016') { // ^N
958       motion = 1;
959     }
960
961     else if(key == KEY_UP ||
962             key == '\020') { // ^P
963       motion = -1;
964     }
965
966     else if(key == KEY_LEFT ||
967             key == '\002') { // ^B
968       if(cursor_position > 0) cursor_position--;
969       else error_feedback();
970     }
971
972     else if(key == KEY_RIGHT ||
973             key == '\006') { // ^F
974       if(pattern[cursor_position]) cursor_position++;
975       else error_feedback();
976     }
977
978     else if(key == '\001') { // ^A
979       cursor_position = 0;
980     }
981
982     else if(key == '\005') { // ^E
983       cursor_position = strlen(pattern);
984     }
985
986     else if(key == '\022') { // ^R
987       use_regexp = !use_regexp;
988     }
989
990     else if(key == '\011') { // ^I
991       case_sensitive = !case_sensitive;
992     }
993
994     else if(key == '\025') { // ^U
995       kill_before_cursor(pattern, &cursor_position);
996     }
997
998     else if(key == '\013') { // ^K
999       kill_after_cursor(pattern, &cursor_position);
1000     }
1001
1002     else if(key == '\014') { // ^L
1003       // I suspect that we may sometime mess up the display
1004       clear();
1005     }
1006
1007     update_screen(&current_line, &temporary_line, motion,
1008                   nb_lines, labels, cursor_position, pattern);
1009
1010   } while(key != '\007' && // ^G
1011           key != '\033' && // ^[ (escape)
1012           key != '\n' &&
1013           key != KEY_ENTER);
1014
1015   echo();
1016   endwin();
1017
1018   //////////////////////////////////////////////////////////////////////
1019   // Here we come back to standard display
1020
1021   if((key == KEY_ENTER || key == '\n')) {
1022
1023     if(output_to_vt_buffer) {
1024       if(temporary_line >= 0 && temporary_line < nb_lines) {
1025         inject_into_tty_buffer(lines[temporary_line]);
1026       }
1027     }
1028
1029     if(output_filename[0]) {
1030       ofstream out(output_filename);
1031       if(out.fail()) {
1032         cerr << "Can not open " << output_filename << " for writing." << endl;
1033         exit(1);
1034       } else {
1035         if(temporary_line >= 0 && temporary_line < nb_lines) {
1036           out << lines[temporary_line] << endl;
1037         } else {
1038           out << endl;
1039         }
1040       }
1041       out.flush();
1042     }
1043   } else {
1044     cout << "Aborted." << endl;
1045   }
1046
1047   for(int l = 0; l < nb_lines; l++) {
1048     delete[] lines[l];
1049     delete[] labels[l];
1050   }
1051
1052   delete[] labels;
1053   delete[] lines;
1054   delete[] title;
1055
1056   exit(0);
1057 }