f740e899ceb216568d5c88930aa1be8864fe822f
[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_FOCUS_LINE 2
65 #define COLOR_ERROR 3
66
67 int attr_modeline, attr_focus_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 // The value passed to this routine in current_focus_line is the index
337 // of the line to highlighted if it matches the matcher. The line
338 // highlighted is the first the one matching the matcher in that
339 // order: The current_focus_line itself, the first with a greated
340 // index, the first with a lesser index.
341
342 // The index of the line actually shown highlighted is written in
343 // displayed_focus_line (it can be -1)
344
345 // If there is a motion and a line is actually shown highlighted, its
346 // value is written in current_focus_line
347
348 void update_screen(int *current_focus_line, int *displayed_focus_line,
349                    int motion,
350                    int nb_lines, char **lines,
351                    int cursor_position,
352                    char *pattern) {
353
354   char buffer[buffer_size];
355   matcher_t matcher;
356
357   initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
358
359   int console_width = getmaxx(stdscr);
360   int console_height = getmaxy(stdscr);
361
362   // First, we find a visible line. In priority: The current, or the
363   // first visible after it, or the first visible before it.
364
365   int nb_printed_lines = 0;
366
367   use_default_colors();
368   addstr("\n");
369
370   if(matcher.regexp_error) {
371     attron(attr_error);
372     addnstr("Regexp syntax error", console_width);
373     attroff(attr_error);
374   } else if(nb_lines > 0) {
375     int new_focus_line;
376     if(match(lines[*current_focus_line], &matcher)) {
377       new_focus_line = *current_focus_line;
378     } else {
379       new_focus_line = next_visible(*current_focus_line, nb_lines, lines, &matcher);
380       if(new_focus_line < 0) {
381         new_focus_line = previous_visible(*current_focus_line, nb_lines, lines, &matcher);
382       }
383     }
384
385     // If we found a visible line and we should move, let's move
386
387     if(new_focus_line >= 0 && motion != 0) {
388       int l = new_focus_line;
389       if(motion > 0) {
390         // We want to go down, let's find the first visible line below
391         for(int m = 0; l >= 0 && m < motion; m++) {
392           l = next_visible(l, nb_lines, lines, &matcher);
393           if(l >= 0) {
394             new_focus_line = l;
395           }
396         }
397       } else {
398         // We want to go up, let's find the first visible line above
399         for(int m = 0; l >= 0 && m < -motion; m++) {
400           l = previous_visible(l, nb_lines, lines, &matcher);
401           if(l >= 0) {
402             new_focus_line = l;
403           }
404         }
405       }
406     }
407
408     // Here new_focus_line is either a line number matching the pattern, or -1
409
410     if(new_focus_line >= 0) {
411
412       int first_line = new_focus_line, last_line = new_focus_line, nb_match = 1;
413
414       // We find the first and last line to show, so that the total of
415       // visible lines between them (them included) is console_height-1
416
417       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
418
419         if(first_line > 0) {
420           first_line--;
421           while(first_line > 0 && !match(lines[first_line], &matcher)) {
422             first_line--;
423           }
424           if(match(lines[first_line], &matcher)) {
425             nb_match++;
426           }
427         }
428
429         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
430           last_line++;
431           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
432             last_line++;
433           }
434
435           if(match(lines[last_line], &matcher)) {
436             nb_match++;
437           }
438         }
439       }
440
441       // Now we display them
442
443       for(int l = first_line; l <= last_line; l++) {
444         if(match(lines[l], &matcher)) {
445           int k = 0;
446
447           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
448             buffer[k] = lines[l][k];
449             k++;
450           }
451
452           // We fill the rest of the line with blanks if this is the
453           // highlighted line
454
455           if(l == new_focus_line) {
456             while(k < console_width) {
457               buffer[k++] = ' ';
458             }
459           }
460
461           buffer[k++] = '\n';
462           buffer[k++] = '\0';
463
464           clrtoeol();
465
466           // Highlight the highlighted line ...
467
468           if(l == new_focus_line) {
469             attron(attr_focus_line);
470             addnstr(buffer, console_width);
471             attroff(attr_focus_line);
472           } else {
473             addnstr(buffer, console_width);
474           }
475
476           nb_printed_lines++;
477         }
478       }
479
480       // If we are on a focused line and we moved, this become the new
481       // focus line
482
483       if(motion != 0) {
484         *current_focus_line = new_focus_line;
485       }
486     }
487
488     *displayed_focus_line = new_focus_line;
489
490     if(nb_printed_lines == 0) {
491       attron(attr_error);
492       addnstr("No selection", console_width);
493       attroff(attr_error);
494     }
495   } else {
496     attron(attr_error);
497     addnstr("Empty choice", console_width);
498     attroff(attr_error);
499   }
500
501   clrtobot();
502
503   // Draw the modeline
504
505   move(0, 0);
506
507   attron(attr_modeline);
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   attroff(attr_modeline);
557
558   // We are done
559
560   refresh();
561   free_matcher(&matcher);
562 }
563
564 //////////////////////////////////////////////////////////////////////
565
566 void read_file(const char *input_filename,
567                int nb_lines_max, int *nb_lines, char **lines,
568                int hash_table_size, int *hash_table) {
569
570   char raw_line[buffer_size];;
571
572   ifstream file(input_filename);
573
574   if(file.fail()) {
575     cerr << "Can not open " << input_filename << endl;
576     exit(1);
577   }
578
579   while(*nb_lines < nb_lines_max && !file.eof()) {
580
581     file.getline(raw_line, buffer_size);
582
583     if(raw_line[0]) {
584
585       if(file.fail()) {
586         cerr << "Line too long:" << endl;
587         cerr << raw_line << endl;
588         exit(1);
589       }
590
591       char *t;
592
593       t = raw_line;
594
595       // Remove the zsh history prefix
596
597       if(zsh_history && *t == ':') {
598         while(*t && *t != ';') t++;
599         if(*t == ';') t++;
600       }
601
602       // Remove the bash history prefix
603
604       if(bash_history) {
605         while(*t == ' ') t++;
606         while(*t >= '0' && *t <= '9') t++;
607         while(*t == ' ') t++;
608       }
609
610       // Check for duplicates with the hash table and insert the line
611       // in the list if necessary
612
613       int dup;
614
615       if(hash_table) {
616         dup = test_and_add(t, *nb_lines, lines, hash_table, hash_table_size);
617       } else {
618         dup = -1;
619       }
620
621       if(dup < 0) {
622         lines[*nb_lines] = new char[strlen(t) + 1];
623         strcpy(lines[*nb_lines], t);
624       } else {
625         // The string was already in there, so we do not allocate a
626         // new string but use the pointer to the first occurence of it
627         lines[*nb_lines] = lines[dup];
628         lines[dup] = 0;
629       }
630
631       (*nb_lines)++;
632     }
633   }
634 }
635
636 //////////////////////////////////////////////////////////////////////
637
638 int main(int argc, char **argv) {
639
640   if(!ttyname(STDIN_FILENO)) {
641     cerr << "The standard input is not a tty." << endl;
642     exit(1);
643   }
644
645   int color_fg_modeline, color_bg_modeline;
646   int color_fg_highlight, color_bg_highlight;
647
648   color_fg_modeline  = COLOR_WHITE;
649   color_bg_modeline  = COLOR_BLACK;
650   color_fg_highlight = COLOR_BLACK;
651   color_bg_highlight = COLOR_YELLOW;
652
653   setlocale(LC_ALL, "");
654
655   char input_filename[buffer_size], output_filename[buffer_size];
656
657   strcpy(input_filename, "");
658   strcpy(output_filename, "");
659
660   int i = 1;
661   int error = 0, show_help = 0;
662   int rest_are_files = 0;
663
664   while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
665
666     if(strcmp(argv[i], "-o") == 0) {
667       check_opt(argc, argv, i, 1, "<output filename>");
668       strncpy(output_filename, argv[i+1], buffer_size);
669       i += 2;
670     }
671
672     else if(strcmp(argv[i], "-s") == 0) {
673       check_opt(argc, argv, i, 1, "<pattern separator>");
674       pattern_separator = argv[i+1][0];
675       i += 2;
676     }
677
678     else if(strcmp(argv[i], "-x") == 0) {
679       check_opt(argc, argv, i, 1, "<label separator>");
680       label_separator = argv[i+1][0];
681       i += 2;
682     }
683
684     else if(strcmp(argv[i], "-v") == 0) {
685       output_to_vt_buffer = 1;
686       i++;
687     }
688
689     else if(strcmp(argv[i], "-w") == 0) {
690       add_control_qs = 1;
691       i++;
692     }
693
694     else if(strcmp(argv[i], "-m") == 0) {
695       with_colors = 0;
696       i++;
697     }
698
699     else if(strcmp(argv[i], "-q") == 0) {
700       error_flash = 1;
701       i++;
702     }
703
704     else if(strcmp(argv[i], "-f") == 0) {
705       check_opt(argc, argv, i, 1, "<input filename>");
706       strncpy(input_filename, argv[i+1], buffer_size);
707       i += 2;
708     }
709
710     else if(strcmp(argv[i], "-i") == 0) {
711       inverse_order = 1;
712       i++;
713     }
714
715     else if(strcmp(argv[i], "-b") == 0) {
716       bash_history = 1;
717       i++;
718     }
719
720     else if(strcmp(argv[i], "-z") == 0) {
721       zsh_history = 1;
722       i++;
723     }
724
725     else if(strcmp(argv[i], "-d") == 0) {
726       remove_duplicates = 1;
727       i++;
728     }
729
730     else if(strcmp(argv[i], "-e") == 0) {
731       use_regexp = 1;
732       i++;
733     }
734
735     else if(strcmp(argv[i], "-a") == 0) {
736       case_sensitive = 1;
737       i++;
738     }
739
740     else if(strcmp(argv[i], "-t") == 0) {
741       check_opt(argc, argv, i, 1, "<title>");
742       delete[] title;
743       title = new char[strlen(argv[i+1]) + 1];
744       strcpy(title, argv[i+1]);
745       i += 2;
746     }
747
748     else if(strcmp(argv[i], "-l") == 0) {
749       check_opt(argc, argv, i, 1, "<maximum number of lines>");
750       nb_lines_max = string_to_positive_integer(argv[i+1]);
751       i += 2;
752     }
753
754     else if(strcmp(argv[i], "-c") == 0) {
755       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
756       color_fg_modeline = string_to_positive_integer(argv[i + 1]);
757       color_bg_modeline = string_to_positive_integer(argv[i + 2]);
758       color_fg_highlight = string_to_positive_integer(argv[i + 3]);
759       color_bg_highlight = string_to_positive_integer(argv[i + 4]);
760       i += 5;
761     }
762
763     else if(strcmp(argv[i], "--") == 0) {
764       rest_are_files = 1;
765       i++;
766     }
767
768     else if(strcmp(argv[i], "-h") == 0) {
769       show_help = 1;
770       i++;
771     }
772
773     else {
774       cerr << "Unknown option " << argv[i] << "." << endl;
775       error = 1;
776     }
777   }
778
779   if(show_help || error) {
780     cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
781          << endl
782          << "Written by Francois Fleuret <francois@fleuret.org>."
783          << endl
784          << endl
785          << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
786          << endl
787          << " -h      show this help" << endl
788          << " -v      inject the selected line in the tty" << endl
789          << " -w      quote control characters with ^Qs when using -v" << endl
790          << " -d      remove duplicated lines" << endl
791          << " -b      remove the bash history line prefix" << endl
792          << " -z      remove the zsh history line prefix" << endl
793          << " -i      invert the order of lines" << endl
794          << " -e      start in regexp mode" << endl
795          << " -a      case sensitive" << endl
796          << " -m      monochrome mode" << endl
797          << " -q      make a flash instead of a beep on an edition error" << endl
798          << " --      all following arguments are filenames" << endl
799          << " -t <title>" << endl
800          << "         add a title in the modeline" << endl
801          << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
802          << "         set the display colors" << endl
803          << " -o <output filename>" << endl
804          << "         set a file to write the selected line to" << endl
805          << " -s <pattern separator>" << endl
806          << "         set the symbol to separate substrings in the pattern" << endl
807          << " -x <label separator>" << endl
808          << "         set the symbol to terminate the label" << endl
809          << " -l <max number of lines>" << endl
810          << "         set the maximum number of lines to take into account" << endl
811          << endl;
812
813     exit(error);
814   }
815
816   char **lines = new char *[nb_lines_max];
817
818   int nb_lines = 0;
819   int hash_table_size = nb_lines_max * 10;
820   int *hash_table = 0;
821
822   if(remove_duplicates) {
823     hash_table = new_hash_table(hash_table_size);
824   }
825
826   if(input_filename[0]) {
827     read_file(input_filename,
828               nb_lines_max, &nb_lines, lines,
829               hash_table_size, hash_table);
830   }
831
832   while(i < argc) {
833     read_file(argv[i],
834               nb_lines_max, &nb_lines, lines,
835               hash_table_size, hash_table);
836     i++;
837   }
838
839   delete[] hash_table;
840
841   // Now remove the null strings
842
843   int n = 0;
844   for(int k = 0; k < nb_lines; k++) {
845     if(lines[k]) {
846       lines[n++] = lines[k];
847     }
848   }
849
850   nb_lines = n;
851
852   if(inverse_order) {
853     for(int i = 0; i < nb_lines / 2; i++) {
854       char *s = lines[nb_lines - 1 - i];
855       lines[nb_lines - 1 - i] = lines[i];
856       lines[i] = s;
857     }
858   }
859
860   // Build the labels from the strings, take only the part before the
861   // label_separator and transform control characters to printable
862   // ones
863
864   char **labels = new char *[nb_lines];
865   for(int l = 0; l < nb_lines; l++) {
866     char *s, *t;
867     const char *u;
868     t = lines[l];
869     int e = 0;
870     while(*t && *t != label_separator) {
871       u = unctrl(*t++);
872       e += strlen(u);
873     }
874     labels[l] = new char[e + 1];
875     t = lines[l];
876     s = labels[l];
877     while(*t && *t != label_separator) {
878       u = unctrl(*t++);
879       while(*u) { *s++ = *u++; }
880     }
881     *s = '\0';
882   }
883
884   char pattern[buffer_size];
885   pattern[0] = '\0';
886
887   int cursor_position;
888   cursor_position = 0;
889
890   //////////////////////////////////////////////////////////////////////
891   // Here we start to display with curse
892
893   initscr();
894
895   noecho();
896
897   // So that the arrow keys work
898   keypad(stdscr, TRUE);
899
900   attr_error = A_STANDOUT;
901   attr_modeline = A_REVERSE;
902   attr_focus_line = A_STANDOUT;
903
904   if(with_colors && has_colors()) {
905
906     start_color();
907
908     if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
909        color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
910        color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
911        color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
912       echo();
913       endwin();
914       cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
915       exit(1);
916     }
917
918     init_pair(COLOR_MODELINE, color_fg_modeline, color_bg_modeline);
919     init_pair(COLOR_FOCUS_LINE, color_fg_highlight, color_bg_highlight);
920     init_pair(COLOR_ERROR, COLOR_WHITE, COLOR_RED);
921
922     attr_modeline = COLOR_PAIR(COLOR_MODELINE);
923     attr_focus_line = COLOR_PAIR(COLOR_FOCUS_LINE);
924     attr_error = COLOR_PAIR(COLOR_ERROR);
925
926   }
927
928   int key;
929   int current_focus_line = 0, displayed_focus_line = 0;
930
931   update_screen(&current_focus_line, &displayed_focus_line,
932                 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_focus_line = 0;
958     }
959
960     else if(key == KEY_END) {
961       current_focus_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_focus_line, &displayed_focus_line,
1024                   motion,
1025                   nb_lines, labels, cursor_position, pattern);
1026
1027   } while(key != '\007' && // ^G
1028           key != '\033' && // ^[ (escape)
1029           key != '\n' &&
1030           key != KEY_ENTER);
1031
1032   echo();
1033   endwin();
1034
1035   //////////////////////////////////////////////////////////////////////
1036   // Here we come back to standard display
1037
1038   if((key == KEY_ENTER || key == '\n')) {
1039
1040     if(output_to_vt_buffer) {
1041       if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1042         inject_into_tty_buffer(lines[displayed_focus_line]);
1043       }
1044     }
1045
1046     if(output_filename[0]) {
1047       ofstream out(output_filename);
1048       if(out.fail()) {
1049         cerr << "Can not open " << output_filename << " for writing." << endl;
1050         exit(1);
1051       } else {
1052         if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1053           out << lines[displayed_focus_line] << endl;
1054         } else {
1055           out << endl;
1056         }
1057       }
1058       out.flush();
1059     }
1060   } else {
1061     cout << "Aborted." << endl;
1062   }
1063
1064   for(int l = 0; l < nb_lines; l++) {
1065     delete[] lines[l];
1066     delete[] labels[l];
1067   }
1068
1069   delete[] labels;
1070   delete[] lines;
1071   delete[] title;
1072
1073   exit(0);
1074 }