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