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