Cosmetics.
[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-2013 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 /*
26
27   To use it as a super-history-search for bash:
28   selector --bash <(history)
29
30 */
31
32 #define _GNU_SOURCE
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <ncurses.h>
40 #include <fcntl.h>
41 #include <sys/ioctl.h>
42 #include <termios.h>
43 #include <regex.h>
44 #include <locale.h>
45 #include <getopt.h>
46 #include <limits.h>
47
48 #define VERSION "1.1.7"
49
50 #define BUFFER_SIZE 16384
51
52 /* Yeah, global variables! */
53
54 int nb_lines_max = 1000;
55 char pattern_separator = ';';
56 char label_separator = '\0';
57 int output_to_vt_buffer = 0;
58 int add_control_qs = 0;
59 int with_colors = 1;
60 int zsh_history = 0;
61 int bash_history = 0;
62 int inverse_order = 0;
63 int remove_duplicates = 0;
64 int use_regexp = 0;
65 int case_sensitive = 0;
66 char *title = 0;
67 int error_flash = 0;
68 int upper_caps_makes_case_sensitive = 0;
69 int show_long_lines = 0;
70 int show_hits = 0;
71
72 int attr_modeline, attr_focus_line, attr_error, attr_hits;
73
74 /********************************************************************/
75
76 /* malloc with error checking.  */
77
78 void *safe_malloc(size_t n) {
79   void *p = malloc(n);
80   if(!p && n != 0) {
81     fprintf(stderr,
82             "selector: cannot allocate memory: %s\n", strerror(errno));
83     exit(EXIT_FAILURE);
84   }
85   return p;
86 }
87
88 /*********************************************************************/
89
90 void inject_into_tty_buffer(char *string, int add_control_qs) {
91   struct termios oldtio, newtio;
92   const char *k;
93   const char control_q = '\021';
94   tcgetattr(STDIN_FILENO, &oldtio);
95   memset(&newtio, 0, sizeof(newtio));
96   /* Set input mode (non-canonical, *no echo*,...) */
97   tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
98   /* Put the selected string in the tty input buffer */
99   for(k = string; *k; k++) {
100     if(add_control_qs && !(*k >= ' ' && *k <= '~')) {
101       /* Add ^Q to quote control characters */
102       ioctl(STDIN_FILENO, TIOCSTI, &control_q);
103     }
104     ioctl(STDIN_FILENO, TIOCSTI, k);
105   }
106   /* Restore the old settings */
107   tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
108 }
109
110 /*********************************************************************/
111
112 void str_to_positive_integers(char *string, int *values, int nb) {
113   int current_value, gotone;
114   char *s;
115   int n;
116
117   n = 0;
118   current_value = 0;
119   gotone = 0;
120   s = string;
121
122   while(1) {
123     if(*s >= '0' && *s <= '9') {
124       current_value = current_value * 10 + (int) (*s - '0');
125       gotone = 1;
126     } else if(*s == ',' || *s == '\0') {
127       if(gotone) {
128         if(n < nb) {
129           values[n++] = current_value;
130           if(*s == '\0') {
131             if(n == nb) {
132               return;
133             } else {
134               fprintf(stderr,
135                       "selector: Missing value in `%s'.\n", string);
136               exit(EXIT_FAILURE);
137             }
138           }
139           current_value = 0;
140           gotone = 0;
141         } else {
142           fprintf(stderr,
143                   "selector: Too many values in `%s'.\n", string);
144           exit(EXIT_FAILURE);
145         }
146       } else {
147         fprintf(stderr,
148                 "selector: Empty value in `%s'.\n", string);
149         exit(EXIT_FAILURE);
150       }
151     } else {
152       fprintf(stderr,
153               "selector: Syntax error in `%s'.\n", string);
154       exit(EXIT_FAILURE);
155     }
156     s++;
157   }
158 }
159
160 void error_feedback() {
161   if(error_flash) {
162     flash();
163   } else {
164     beep();
165   }
166 }
167
168 void usage(FILE *out) {
169
170   fprintf(out, "Selector version %s (%s)\n", VERSION, UNAME);
171   fprintf(out, "Written by Francois Fleuret <francois@fleuret.org>.\n");
172   fprintf(out, "\n");
173   fprintf(out, "Usage: selector [options] [<filename1> [<filename2> ...]]\n");
174   fprintf(out, "\n");
175   fprintf(out, " -h, --help\n");
176   fprintf(out, "         show this help\n");
177   fprintf(out, " -v, --inject-in-tty\n");
178   fprintf(out, "         inject the selected line in the tty\n");
179   fprintf(out, " -w, --add-control-qs\n");
180   fprintf(out, "         quote control characters with ^Qs when using -v\n");
181   fprintf(out, " -d, --remove-duplicates\n");
182   fprintf(out, "         remove duplicated lines\n");
183   fprintf(out, " -b, --remove-bash-prefix\n");
184   fprintf(out, "         remove the bash history line prefix\n");
185   fprintf(out, " -z, --remove-zsh-prefix\n");
186   fprintf(out, "         remove the zsh history line prefix\n");
187   fprintf(out, " -i, --revert-order\n");
188   fprintf(out, "         invert the order of lines\n");
189   fprintf(out, " -e, --regexp\n");
190   fprintf(out, "         start in regexp mode\n");
191   fprintf(out, " -a, --case-sensitive\n");
192   fprintf(out, "         start in case sensitive mode\n");
193   fprintf(out, " -j, --show-long-lines\n");
194   fprintf(out, "         print a long-line indicator at the end of truncated lines\n");
195   fprintf(out, " -y, --show-hits\n");
196   fprintf(out, "         highlight the matching substrings\n");
197   fprintf(out, " -u, --upper-case-makes-case-sensitive\n");
198   fprintf(out, "         using an upper case character in the matching string makes\n");
199   fprintf(out, "         the matching case-sensitive\n");
200   fprintf(out, " -m, --monochrome\n");
201   fprintf(out, "         monochrome mode\n");
202   fprintf(out, " -q, --no-beep\n");
203   fprintf(out, "         make a flash instead of a beep on an edition error\n");
204   fprintf(out, " --bash\n");
205   fprintf(out, "         setting for bash history search, same as -b -i -d -v -w -l ${HISTSIZE}\n");
206   fprintf(out, " --\n");
207   fprintf(out, "         all following arguments are filenames\n");
208   fprintf(out, " -t <title>, --title <title>\n");
209   fprintf(out, "         add a title in the modeline\n");
210   fprintf(out, " -r <pattern>, --pattern <pattern>\n");
211   fprintf(out, "         set an initial pattern\n");
212   fprintf(out, " -c <colors>, --colors <colors>\n");
213   fprintf(out, "         set the display colors with an argument of the form\n");
214   fprintf(out, "         <fg_modeline>,<bg_modeline>,<fg_highlight>,<bg_highlight>\n");
215   fprintf(out, " -o <output filename>, --output-file <output filename>\n");
216   fprintf(out, "         set a file to write the selected line to\n");
217   fprintf(out, " -s <pattern separator>, --pattern-separator <pattern separator>\n");
218   fprintf(out, "         set the symbol to separate substrings in the pattern\n");
219   fprintf(out, " -x <label separator>, --label-separator <label separator>\n");
220   fprintf(out, "         set the character to separate the label to show from the\n");
221   fprintf(out, "         string to return\n");
222   fprintf(out, " -l <max number of lines>, --number-of-lines <max number of lines>\n");
223   fprintf(out, "         set the maximum number of lines to take into account\n");
224   fprintf(out, "\n");
225 }
226
227 /*********************************************************************/
228
229 /* A quick and dirty hash table */
230
231 #define MAGIC_HASH_MULTIPLIER 387433
232
233 /* The table itself stores indexes of the strings taken in a char**
234    table. When a string is added, if it was already in the table, the
235    new index replaces the previous one.  */
236
237 struct hash_table_t {
238   int size;
239   int *entries;
240 };
241
242 struct hash_table_t *new_hash_table(int size) {
243   int k;
244   struct hash_table_t *hash_table;
245
246   hash_table = safe_malloc(sizeof(struct hash_table_t));
247
248   hash_table->size = size;
249   hash_table->entries = safe_malloc(hash_table->size * sizeof(int));
250
251   for(k = 0; k < hash_table->size; k++) {
252     hash_table->entries[k] = -1;
253   }
254
255   return hash_table;
256 }
257
258 void free_hash_table(struct hash_table_t *hash_table) {
259   free(hash_table->entries);
260   free(hash_table);
261 }
262
263 /* Adds new_string in the table, associated to new_index. If this
264    string was not already in the table, returns -1. Otherwise, returns
265    the previous index it had. */
266
267 int add_and_get_previous_index(struct hash_table_t *hash_table,
268                                const char *new_string, int new_index,
269                                char **strings) {
270
271   unsigned int code = 0, start;
272   int k;
273
274   /* This is my recipe. I checked, it seems to work (as long as
275      hash_table->size is not a multiple of MAGIC_HASH_MULTIPLIER that
276      should be okay) */
277
278   for(k = 0; new_string[k]; k++) {
279     code = code * MAGIC_HASH_MULTIPLIER + (unsigned int) (new_string[k]);
280   }
281
282   code = code % hash_table->size;
283   start = code;
284
285   while(hash_table->entries[code] >= 0) {
286     /* There is a string with that code */
287     if(strcmp(new_string, strings[hash_table->entries[code]]) == 0) {
288       /* It is the same string, we keep a copy of the stored index */
289       int result = hash_table->entries[code];
290       /* Put the new one */
291       hash_table->entries[code] = new_index;
292       /* And return the previous one */
293       return result;
294     }
295     /* This collision was not the same string, let's move to the next
296        in the table */
297     code = (code + 1) % hash_table->size;
298     /* We came back to our original code, which means that the table
299        is full */
300     if(code == start) {
301       fprintf(stderr,
302               "Full hash table (that should not happen)\n");
303       exit(EXIT_FAILURE);
304    }
305   }
306
307   /* This string was not already in there, store the index in the
308      table and return -1 */
309
310   hash_table->entries[code] = new_index;
311   return -1;
312 }
313
314 /*********************************************************************
315  A matcher matches either with a collection of substrings, or with a
316  regexp */
317
318 struct matcher {
319   regex_t preg;
320   int regexp_error;
321   int nb_patterns;
322   int case_sensitive;
323   char *splitted_patterns, **patterns;
324 };
325
326 /* Routine to add an interval to a sorted list of intervals
327    extremities. Returns the resulting number of extremities.
328
329    This routine is an effing nightmare */
330
331 int add_interval(int n, int *switches, int start, int end) {
332   int f, g, k;
333
334   if(start == end) { return n; }
335
336   f = 0;
337   while(f < n && switches[f] <= start) { f++; }
338   g = f;
339   while(g < n && switches[g] <= end) { g++; }
340
341   if(f == n) {
342     /* switches[n-1]   start  end  */
343     /* XXXXXXXXXXXX|               */
344     switches[f] = start;
345     switches[f+1] = end;
346     return n + 2;
347   }
348
349   if(f % 2) {
350
351     if(g % 2) {
352       /* switches[f-1]   start   switches[f]         switches[g-1]   end    switches[g] */
353       /* |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|   ...   |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| */
354       for(k = f; k < n; k++) { switches[k] = switches[k + (g - f)]; }
355       return n - (g - f);
356     } else {
357       /* switches[f-1]   start   switches[f]         switches[g-1]   end    switches[g] */
358       /* |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|   ...   XXXXXXXXXXXX|          |XXXXXXXXXX */
359       switches[g - 1] = end;
360       for(k = f; k < n; k++) { switches[k] = switches[k + ((g - 1) - f)]; }
361       return n - ((g - 1) - f);
362     }
363
364   } else {
365
366     if(f == g) {
367       /* switches[f-1]   start  end   switches[f]  */
368       /* XXXXXXXXXXXX|                |XXXXXXXXXX  */
369       for(k = n - 1; k >= f; k--) {
370         switches[k + 2] = switches[k];
371       }
372       switches[f] = start;
373       switches[f + 1] = end;
374       return n + 2;
375     }
376
377     if(g % 2) {
378       /* switches[f-1]   start   switches[f]         switches[g-1]   end    switches[g] */
379       /* XXXXXXXXXXXX|           |XXXXXXXXXX   ...   |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| */
380       switches[f] = start;
381       for(k = f + 1; k < n; k++) { switches[k] = switches[k + (g - (f + 1))]; }
382       return n - (g - (f + 1));
383     } else {
384       /* switches[f-1]   start   switches[f]         switches[g-1]   end    switches[g] */
385       /* XXXXXXXXXXXX|           |XXXXXXXXXX   ...   XXXXXXXXXXXX|          |XXXXXXXXXX */
386       switches[f] = start;
387       switches[g - 1] = end;
388       for(k = f + 1; k < n; k++) { switches[k] = switches[k + ((g - 1) - (f + 1))]; }
389       return n - ((g - 1) - (f + 1));
390     }
391   }
392 }
393
394 int match(struct matcher *matcher, char *string, int *nb_switches, int *switches) {
395   int n;
396   char *where;
397   regmatch_t matches;
398
399   if(nb_switches) { *nb_switches = 0; }
400
401   if(matcher->nb_patterns >= 0) {
402     if(matcher->case_sensitive) {
403       for(n = 0; n < matcher->nb_patterns; n++) {
404         if((where = strstr(string, matcher->patterns[n])) == 0) return 0;
405         if(switches) {
406           *nb_switches = add_interval(*nb_switches, switches,
407                                       (int) (where - string),
408                                       (int) (where - string) + strlen(matcher->patterns[n]));
409         }
410       }
411     } else {
412       for(n = 0; n < matcher->nb_patterns; n++) {
413         if((where = strcasestr(string, matcher->patterns[n])) == 0) return 0;
414         if(switches) {
415           *nb_switches = add_interval(*nb_switches, switches,
416                                       (int) (where - string),
417                                       (int) (where - string) + strlen(matcher->patterns[n]));
418         }
419       }
420     }
421     return 1;
422   } else {
423     if(switches) {
424       if(regexec(&matcher->preg, string, 1, &matches, 0) == 0) {
425         *nb_switches = 2;
426         switches[0] = matches.rm_so;
427         switches[1] = matches.rm_eo;
428         return 1;
429       } else {
430         return 0;
431       }
432     } else {
433       return regexec(&matcher->preg, string, 0, 0, 0) == 0;
434     }
435   }
436 }
437
438 void free_matcher(struct matcher *matcher) {
439   if(matcher->nb_patterns < 0) {
440     if(!matcher->regexp_error) regfree(&matcher->preg);
441   } else {
442     free(matcher->splitted_patterns);
443     free(matcher->patterns);
444   }
445 }
446
447 void initialize_matcher(struct matcher *matcher,
448                         int use_regexp, int case_sensitive,
449                         const char *pattern) {
450   const char *s;
451   char *t, *last_pattern_start;
452   int n;
453
454   if(use_regexp) {
455     matcher->case_sensitive = case_sensitive;
456     matcher->nb_patterns = -1;
457     matcher->regexp_error = regcomp(&matcher->preg, pattern,
458                                     case_sensitive ? 0 : REG_ICASE);
459   } else {
460     matcher->regexp_error = 0;
461     matcher->nb_patterns = 1;
462
463     if(upper_caps_makes_case_sensitive) {
464       for(s = pattern; *s && !case_sensitive; s++) {
465         case_sensitive = (*s >= 'A' && *s <= 'Z');
466       }
467     }
468
469     matcher->case_sensitive = case_sensitive;
470
471     for(s = pattern; *s; s++) {
472       if(*s == pattern_separator) {
473         matcher->nb_patterns++;
474       }
475     }
476
477     matcher->splitted_patterns =
478       safe_malloc((strlen(pattern) + 1) * sizeof(char));
479
480     matcher->patterns =
481       safe_malloc(matcher->nb_patterns * sizeof(char *));
482
483     strcpy(matcher->splitted_patterns, pattern);
484
485     n = 0;
486     last_pattern_start = matcher->splitted_patterns;
487     for(t = matcher->splitted_patterns; n < matcher->nb_patterns; t++) {
488       if(*t == pattern_separator || *t == '\0') {
489         *t = '\0';
490         matcher->patterns[n++] = last_pattern_start;
491         last_pattern_start = t + 1;
492       }
493     }
494   }
495 }
496
497 /*********************************************************************
498  Buffer edition */
499
500 void delete_char(char *buffer, int *position) {
501   if(buffer[*position]) {
502     int c = *position;
503     while(c < BUFFER_SIZE && buffer[c]) {
504       buffer[c] = buffer[c+1];
505       c++;
506     }
507   } else error_feedback();
508 }
509
510 void backspace_char(char *buffer, int *position) {
511   if(*position > 0) {
512     if(buffer[*position]) {
513       int c = *position - 1;
514       while(buffer[c]) {
515         buffer[c] = buffer[c+1];
516         c++;
517       }
518     } else {
519       buffer[*position - 1] = '\0';
520     }
521
522     (*position)--;
523   } else error_feedback();
524 }
525
526 void insert_char(char *buffer, int *position, char character) {
527   if(strlen(buffer) < BUFFER_SIZE - 1) {
528     int c = *position;
529     char t = buffer[c], u;
530     while(t) {
531       c++;
532       u = buffer[c];
533       buffer[c] = t;
534       t = u;
535     }
536     c++;
537     buffer[c] = '\0';
538     buffer[(*position)++] = character;
539   } else error_feedback();
540 }
541
542 void kill_before_cursor(char *buffer, int *position) {
543   int s = 0;
544   while(buffer[*position + s]) {
545     buffer[s] = buffer[*position + s];
546     s++;
547   }
548   buffer[s] = '\0';
549   *position = 0;
550 }
551
552 void kill_after_cursor(char *buffer, int *position) {
553   buffer[*position] = '\0';
554 }
555
556 /*********************************************************************/
557
558 int previous_visible(int current_line, char **lines, struct matcher *matcher) {
559   int line = current_line - 1;
560   while(line >= 0 && !match(matcher, lines[line], 0, 0)) line--;
561   return line;
562 }
563
564 int next_visible(int current_line, int nb_lines, char **lines,
565                  struct matcher *matcher) {
566   int line = current_line + 1;
567   while(line < nb_lines && !match(matcher, lines[line], 0, 0)) line++;
568
569   if(line < nb_lines)
570     return line;
571   else
572     return -1;
573 }
574
575 /*********************************************************************/
576
577 void print_string_with_switches(char *buffer, int line_width,
578                                 int nb_patterns, int *switches) {
579   int w, current = 0, next;
580   if(switches) {
581     for(w = 0; w < nb_patterns && switches[2 * w] < line_width; w++) {
582       if(switches[2 * w] < switches[2 * w + 1]) {
583         next = switches[2 * w];
584         if(next > line_width) { next = line_width; }
585         if(next > current) { addnstr(buffer + current,  next - current); }
586         attron(attr_hits);
587         current = next;
588         next = switches[2 * w + 1];
589         if(next > line_width) { next = line_width; }
590         if(next > current) { addnstr(buffer + current,  next - current); }
591         attroff(attr_hits);
592         current = next;
593       }
594     }
595     if(current < line_width) {
596       addnstr(buffer + current, line_width - current);
597     }
598   } else {
599     addnstr(buffer, line_width);
600   }
601 }
602
603 /* The line highlighted is the first one matching the matcher in that
604    order: (1) current_focus_line after motion, if it does not match,
605    then (2) the first with a greater index, if none matches, then (3)
606    the first with a lesser index.
607
608    The index of the line actually shown highlighted is written in
609    displayed_focus_line (it can be -1 if no line at all matches the
610    matcher)
611
612    If there is a motion and a line is actually shown highlighted, its
613    value is written in current_focus_line. */
614
615 void update_screen(int *current_focus_line, int *displayed_focus_line,
616                    int motion,
617                    int nb_lines, char **lines,
618                    int cursor_position,
619                    char *pattern) {
620   int *switches;
621   char buffer[BUFFER_SIZE];
622   struct matcher matcher;
623   int k, l, m;
624   int console_width, console_height;
625   int nb_printed_lines = 0;
626   int cursor_x;
627   int nb_switches;
628
629   initialize_matcher(&matcher, use_regexp, case_sensitive, pattern);
630
631   if(show_hits) {
632     if(matcher.nb_patterns >= 0) {
633       switches = safe_malloc(sizeof(int) * matcher.nb_patterns * 2);
634     } else {
635       switches = safe_malloc(sizeof(int) * 2);
636     }
637   } else {
638     switches = 0;
639   }
640
641   console_width = getmaxx(stdscr);
642   console_height = getmaxy(stdscr);
643
644   use_default_colors();
645
646   /* Add an empty line where we will print the modeline at the end */
647
648   addstr("\n");
649
650   /* If the regexp is erroneous, print a message saying so */
651
652   if(matcher.regexp_error) {
653     attron(attr_error);
654     addnstr("Regexp syntax error", console_width);
655     attroff(attr_error);
656   }
657
658   /* Else, and we do have lines to select from, find a visible line. */
659
660   else if(nb_lines > 0) {
661     int new_focus_line;
662     if(match(&matcher, lines[*current_focus_line], 0, 0)) {
663       new_focus_line = *current_focus_line;
664     } else {
665       new_focus_line = next_visible(*current_focus_line, nb_lines, lines,
666                                     &matcher);
667       if(new_focus_line < 0) {
668         new_focus_line = previous_visible(*current_focus_line, lines, &matcher);
669       }
670     }
671
672     /* If we found a visible line and we should move, let's move */
673
674     if(new_focus_line >= 0 && motion != 0) {
675       int l = new_focus_line;
676       if(motion > 0) {
677         /* We want to go down, let's find the first visible line below */
678         for(m = 0; l >= 0 && m < motion; m++) {
679           l = next_visible(l, nb_lines, lines, &matcher);
680           if(l >= 0) {
681             new_focus_line = l;
682           }
683         }
684       } else {
685         /* We want to go up, let's find the first visible line above */
686         for(m = 0; l >= 0 && m < -motion; m++) {
687           l = previous_visible(l, lines, &matcher);
688           if(l >= 0) {
689             new_focus_line = l;
690           }
691         }
692       }
693     }
694
695     /* Here new_focus_line is either a line number matching the
696        pattern, or -1 */
697
698     if(new_focus_line >= 0) {
699
700       int first_line = new_focus_line, last_line = new_focus_line;
701       int nb_match = 1;
702
703       /* We find the first and last lines to show, so that the total
704          of visible lines between them (them included) is
705          console_height-1 */
706
707       while(nb_match < console_height-1 &&
708             (first_line > 0 || last_line < nb_lines - 1)) {
709
710         if(first_line > 0) {
711           first_line--;
712           while(first_line > 0 && !match(&matcher, lines[first_line], 0, 0)) {
713             first_line--;
714           }
715           if(match(&matcher, lines[first_line], 0, 0)) {
716             nb_match++;
717           }
718         }
719
720         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
721           last_line++;
722           while(last_line < nb_lines - 1 && !match(&matcher, lines[last_line], 0, 0)) {
723             last_line++;
724           }
725
726           if(match(&matcher, lines[last_line], 0, 0)) {
727             nb_match++;
728           }
729         }
730       }
731
732       /* Now we display them */
733
734       for(l = first_line; l <= last_line; l++) {
735         if(match(&matcher, lines[l], &nb_switches, switches)) {
736           int k = 0;
737
738           while(lines[l][k] && k < BUFFER_SIZE - 2 && k < console_width) {
739             buffer[k] = lines[l][k];
740             k++;
741           }
742
743           /* Highlight the highlighted line ... */
744
745           if(l == new_focus_line) {
746             if(show_long_lines && k >= console_width) {
747               attron(attr_focus_line);
748               print_string_with_switches(buffer, console_width-1,
749                                          nb_switches / 2, switches);
750               /* attron(attr_error); */
751               addnstr("\\", 1);
752               /* attroff(attr_error); */
753               attroff(attr_focus_line);
754             } else {
755               while(k < console_width) {
756                 buffer[k++] = ' ';
757               }
758               attron(attr_focus_line);
759               print_string_with_switches(buffer, k,
760                                          nb_switches / 2, switches);
761               attroff(attr_focus_line);
762             }
763           } else {
764             if(show_long_lines && k >= console_width) {
765               print_string_with_switches(buffer, console_width-1,
766                                          nb_switches / 2, switches);
767               attron(attr_focus_line);
768               addnstr("\\", 1);
769               attroff(attr_focus_line);
770             } else {
771               if(k < console_width) {
772                 buffer[k++] = '\n';
773                 buffer[k++] = '\0';
774               }
775               print_string_with_switches(buffer, k,
776                                          nb_switches / 2, switches);
777             }
778           }
779
780           nb_printed_lines++;
781         }
782       }
783
784       /* If we are on a focused line and we moved, this become the new
785          focus line */
786
787       if(motion != 0) {
788         *current_focus_line = new_focus_line;
789       }
790     }
791
792     *displayed_focus_line = new_focus_line;
793
794     if(nb_printed_lines == 0) {
795       attron(attr_error);
796       addnstr("No selection", console_width);
797       attroff(attr_error);
798     }
799   }
800
801   /* Else, print a message saying that there are no lines to select from */
802
803   else {
804     attron(attr_error);
805     addnstr("Empty choice", console_width);
806     attroff(attr_error);
807   }
808
809   clrtobot();
810
811   /* Draw the modeline */
812
813   move(0, 0);
814
815   attron(attr_modeline);
816
817   for(k = 0; k < console_width; k++) buffer[k] = ' ';
818   buffer[console_width] = '\0';
819   addnstr(buffer, console_width);
820
821   move(0, 0);
822
823   /* There must be a more elegant way of moving the cursor at a
824      location met during display */
825
826   cursor_x = 0;
827
828   if(title) {
829     addstr(title);
830     addstr(" ");
831     cursor_x += strlen(title) + 1;
832   }
833
834   sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
835   addstr(buffer);
836   cursor_x += strlen(buffer);
837
838   addnstr(pattern, cursor_position);
839   cursor_x += cursor_position;
840
841   if(pattern[cursor_position]) {
842     addstr(pattern + cursor_position);
843   } else {
844     addstr(" ");
845   }
846
847   /* Add a few info about the mode we are in (regexp and/or case
848      sensitive) */
849
850   if(use_regexp || matcher.case_sensitive) {
851     addstr(" [");
852     if(use_regexp) {
853       addstr("regexp");
854     }
855
856     if(matcher.case_sensitive) {
857       if(use_regexp) {
858         addstr(",");
859       }
860       addstr("case");
861     }
862     addstr("]");
863   }
864
865   move(0, cursor_x);
866
867   attroff(attr_modeline);
868
869   /* We are done */
870
871   refresh();
872   if(switches) { free(switches); }
873   free_matcher(&matcher);
874 }
875
876 /*********************************************************************/
877
878 void store_line(struct hash_table_t *hash_table,
879                 const char *new_line,
880                 int *nb_lines, char **lines) {
881   int dup;
882
883   /* Remove the zsh history prefix */
884
885   if(zsh_history && *new_line == ':') {
886     while(*new_line && *new_line != ';') new_line++;
887     if(*new_line == ';') new_line++;
888   }
889
890   /* Remove the bash history prefix */
891
892   if(bash_history) {
893     while(*new_line == ' ') new_line++;
894     while(*new_line >= '0' && *new_line <= '9') new_line++;
895     while(*new_line == ' ') new_line++;
896   }
897
898   /* Check for duplicates with the hash table and insert the line in
899      the list if necessary */
900
901   if(hash_table) {
902     dup = add_and_get_previous_index(hash_table,
903                                      new_line, *nb_lines, lines);
904   } else {
905     dup = -1;
906   }
907
908   if(dup < 0) {
909     lines[*nb_lines] = safe_malloc((strlen(new_line) + 1) * sizeof(char));
910     strcpy(lines[*nb_lines], new_line);
911   } else {
912     /* The string was already in there, so we do not allocate a new
913        string but use the pointer to the first occurence of it */
914     lines[*nb_lines] = lines[dup];
915     lines[dup] = 0;
916   }
917
918   (*nb_lines)++;
919 }
920
921 void read_file(struct hash_table_t *hash_table,
922                const char *input_filename,
923                int nb_lines_max, int *nb_lines, char **lines) {
924
925   char raw_line[BUFFER_SIZE];
926   char *s;
927   FILE *file;
928   int l;
929
930   file = fopen(input_filename, "r");
931
932   if(!file) {
933     fprintf(stderr, "selector: Cannot open `%s'.\n", input_filename);
934     exit(EXIT_FAILURE);
935   }
936
937   if(label_separator == '\n') {
938     while(*nb_lines < nb_lines_max && fgets(raw_line, BUFFER_SIZE, file)) {
939       l = strlen(raw_line);
940       fgets(raw_line + l, BUFFER_SIZE - l, file);
941       for(s = raw_line + strlen(raw_line) - 1; s > raw_line && *s == '\n'; s--) {
942         *s = '\0';
943       }
944       store_line(hash_table, raw_line, nb_lines, lines);
945     }
946   } else {
947     while(*nb_lines < nb_lines_max && fgets(raw_line, BUFFER_SIZE, file)) {
948       for(s = raw_line + strlen(raw_line) - 1; s > raw_line && *s == '\n'; s--) {
949         *s = '\0';
950       }
951       store_line(hash_table, raw_line, nb_lines, lines);
952     }
953   }
954
955   fclose(file);
956 }
957
958 /*********************************************************************/
959
960 /* For long options that have no equivalent short option, use a
961    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
962 enum
963 {
964   OPT_BASH_MODE = CHAR_MAX + 1
965 };
966
967 static struct option long_options[] = {
968   { "output-file", 1, 0, 'o' },
969   { "pattern-separator", 1, 0, 's' },
970   { "label-separator", 1, 0, 'x' },
971   { "inject-in-tty", no_argument, 0, 'v' },
972   { "add-control-qs", no_argument, 0, 'w' },
973   { "monochrome", no_argument, 0, 'm' },
974   { "no-beep", no_argument, 0, 'q' },
975   { "revert-order", no_argument, 0, 'i' },
976   { "remove-bash-prefix", no_argument, 0, 'b' },
977   { "remove-zsh-prefix", no_argument, 0, 'z' },
978   { "remove-duplicates", no_argument, 0, 'd' },
979   { "regexp", no_argument, 0, 'e' },
980   { "case-sensitive", no_argument, 0, 'a' },
981   { "show-long-lines", no_argument, 0, 'j'},
982   { "show-hits", no_argument, 0, 'j'},
983   { "upper-case-makes-case-sensitive", no_argument, 0, 'u' },
984   { "title", 1, 0, 't' },
985   { "pattern", 1, 0, 'r' },
986   { "number-of-lines", 1, 0, 'l' },
987   { "colors", 1, 0, 'c' },
988   { "bash", no_argument, 0, OPT_BASH_MODE },
989   { "help", no_argument, 0, 'h' },
990   { 0, 0, 0, 0 }
991 };
992
993 int main(int argc, char **argv) {
994
995   char output_filename[BUFFER_SIZE];
996   char pattern[BUFFER_SIZE];
997   int c, k, l, n;
998   int cursor_position;
999   int error = 0, show_help = 0, done = 0;
1000   int key;
1001   int current_focus_line, displayed_focus_line;
1002
1003   int colors[4];
1004   int color_fg_modeline, color_bg_modeline;
1005   int color_fg_highlight, color_bg_highlight;
1006
1007   char **lines, **labels;
1008   int nb_lines;
1009   struct hash_table_t *hash_table;
1010   char *bash_histsize;
1011
1012   if(!isatty(STDIN_FILENO)) {
1013     fprintf(stderr, "selector: The standard input is not a tty.\n");
1014     exit(EXIT_FAILURE);
1015   }
1016
1017   pattern[0] = '\0';
1018
1019   color_fg_modeline  = COLOR_WHITE;
1020   color_bg_modeline  = COLOR_BLACK;
1021   color_fg_highlight = COLOR_BLACK;
1022   color_bg_highlight = COLOR_YELLOW;
1023
1024   setlocale(LC_ALL, "");
1025
1026   strcpy(output_filename, "");
1027
1028   while ((c = getopt_long(argc, argv, "o:s:x:vwmqf:ibzdeajyunt:r:l:c:-h",
1029                           long_options, NULL)) != -1) {
1030
1031     switch(c) {
1032
1033     case 'o':
1034       strncpy(output_filename, optarg, BUFFER_SIZE);
1035       break;
1036
1037     case 's':
1038       pattern_separator = optarg[0];
1039       break;
1040
1041     case 'x':
1042       if(strcmp(optarg, "\\n") == 0) {
1043         label_separator = '\n';
1044       } else {
1045         label_separator = optarg[0];
1046       }
1047       break;
1048
1049     case 'v':
1050       output_to_vt_buffer = 1;
1051       break;
1052
1053     case 'w':
1054       add_control_qs = 1;
1055       break;
1056
1057     case 'm':
1058       with_colors = 0;
1059       break;
1060
1061     case 'q':
1062       error_flash = 1;
1063       break;
1064
1065     case 'i':
1066       inverse_order = 1;
1067       break;
1068
1069     case 'b':
1070       bash_history = 1;
1071       break;
1072
1073     case 'z':
1074       zsh_history = 1;
1075       break;
1076
1077     case 'd':
1078       remove_duplicates = 1;
1079       break;
1080
1081     case 'e':
1082       use_regexp = 1;
1083       break;
1084
1085     case 'a':
1086       case_sensitive = 1;
1087       break;
1088
1089     case 'j':
1090       show_long_lines = 1;
1091       break;
1092
1093     case 'y':
1094       show_hits = 1;
1095       break;
1096
1097     case 'u':
1098       upper_caps_makes_case_sensitive = 1;
1099       break;
1100
1101     case 't':
1102       free(title);
1103       title = safe_malloc((strlen(optarg) + 1) * sizeof(char));
1104       strcpy(title, optarg);
1105       break;
1106
1107     case 'r':
1108       strcpy(pattern, optarg);
1109       break;
1110
1111     case 'l':
1112       str_to_positive_integers(optarg, &nb_lines_max, 1);
1113       break;
1114
1115     case 'c':
1116       str_to_positive_integers(optarg, colors, 4);
1117       color_fg_modeline = colors[0];
1118       color_bg_modeline = colors[1];
1119       color_fg_highlight = colors[2];
1120       color_bg_highlight = colors[3];
1121       break;
1122
1123     case 'h':
1124       show_help = 1;
1125       break;
1126
1127     case OPT_BASH_MODE:
1128       /* Same as -c 7,4,0,3 -q */
1129       /* color_fg_modeline = 7; */
1130       /* color_bg_modeline = 4; */
1131       /* color_fg_highlight = 0; */
1132       /* color_bg_highlight = 3; */
1133       /* error_flash = 1; */
1134       /* Same as -b -i -d -v -w */
1135       bash_history = 1;
1136       inverse_order = 1;
1137       remove_duplicates = 1;
1138       output_to_vt_buffer = 1;
1139       add_control_qs = 1;
1140       bash_histsize = getenv("HISTSIZE");
1141       if(bash_histsize) {
1142         str_to_positive_integers(bash_histsize, &nb_lines_max, 1);
1143       }
1144       break;
1145
1146     default:
1147       error = 1;
1148       break;
1149     }
1150   }
1151
1152   if(error) {
1153     usage(stderr);
1154     exit(EXIT_FAILURE);
1155   }
1156
1157   if(show_help) {
1158     usage(stdout);
1159     exit(EXIT_SUCCESS);
1160   }
1161
1162   lines = safe_malloc(nb_lines_max * sizeof(char *));
1163
1164   nb_lines = 0;
1165
1166   if(remove_duplicates) {
1167     hash_table = new_hash_table(nb_lines_max * 10);
1168   } else {
1169     hash_table = 0;
1170   }
1171
1172   while(optind < argc) {
1173     read_file(hash_table,
1174               argv[optind],
1175               nb_lines_max, &nb_lines, lines);
1176     optind++;
1177   }
1178
1179   if(hash_table) {
1180     free_hash_table(hash_table);
1181   }
1182
1183   /* Now remove the null strings */
1184
1185   n = 0;
1186   for(k = 0; k < nb_lines; k++) {
1187     if(lines[k]) {
1188       lines[n++] = lines[k];
1189     }
1190   }
1191
1192   nb_lines = n;
1193
1194   if(inverse_order) {
1195     for(l = 0; l < nb_lines / 2; l++) {
1196       char *s = lines[nb_lines - 1 - l];
1197       lines[nb_lines - 1 - l] = lines[l];
1198       lines[l] = s;
1199     }
1200   }
1201
1202   /* Build the labels from the strings, take only the part before the
1203      label_separator and transform control characters to printable
1204      ones */
1205
1206   labels = safe_malloc(nb_lines * sizeof(char *));
1207
1208   for(l = 0; l < nb_lines; l++) {
1209     char *s, *t;
1210     int e = 0;
1211     const char *u;
1212     t = lines[l];
1213
1214     while(*t && *t != label_separator) {
1215       u = unctrl(*t++);
1216       e += strlen(u);
1217     }
1218
1219     labels[l] = safe_malloc((e + 1) * sizeof(char));
1220     t = lines[l];
1221     s = labels[l];
1222     while(*t && *t != label_separator) {
1223       u = unctrl(*t++);
1224       while(*u) { *s++ = *u++; }
1225     }
1226     *s = '\0';
1227   }
1228
1229   cursor_position = 0;
1230
1231   /* Here we start to display with curse */
1232
1233   initscr();
1234   cbreak();
1235   noecho();
1236   intrflush(stdscr, FALSE);
1237
1238   /* So that the arrow keys work */
1239   keypad(stdscr, TRUE);
1240
1241   attr_error = A_STANDOUT;
1242   attr_modeline = A_REVERSE;
1243   attr_focus_line = A_STANDOUT;
1244   attr_hits = A_BOLD;
1245
1246   if(with_colors && has_colors()) {
1247
1248     start_color();
1249
1250     if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
1251        color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
1252        color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
1253        color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
1254       echo();
1255       endwin();
1256       fprintf(stderr, "selector: Color numbers have to be between 0 and %d.\n",
1257               COLORS - 1);
1258       exit(EXIT_FAILURE);
1259     }
1260
1261     init_pair(1, color_fg_modeline, color_bg_modeline);
1262     attr_modeline = COLOR_PAIR(1);
1263
1264     init_pair(2, color_fg_highlight, color_bg_highlight);
1265     attr_focus_line = COLOR_PAIR(2);
1266
1267     init_pair(3, COLOR_WHITE, COLOR_RED);
1268     attr_error = COLOR_PAIR(3);
1269
1270   }
1271
1272   current_focus_line = 0;
1273   displayed_focus_line = 0;
1274   cursor_position = strlen(pattern);
1275
1276   update_screen(&current_focus_line, &displayed_focus_line,
1277                 0,
1278                 nb_lines, labels, cursor_position, pattern);
1279
1280   do {
1281     int motion = 0;
1282
1283     key = getch();
1284
1285     if(key >= ' ' && key <= '~') { /* Insert character */
1286       insert_char(pattern, &cursor_position, key);
1287     }
1288
1289     else if(key == KEY_BACKSPACE ||
1290             key == '\010' || /* ^H */
1291             key == '\177') { /* ^? */
1292       backspace_char(pattern, &cursor_position);
1293     }
1294
1295     else if(key == KEY_DC ||
1296             key == '\004') { /* ^D */
1297       delete_char(pattern, &cursor_position);
1298     }
1299
1300     else if(key == KEY_HOME) {
1301       current_focus_line = 0;
1302     }
1303
1304     else if(key == KEY_END) {
1305       current_focus_line = nb_lines - 1;
1306     }
1307
1308     else if(key == KEY_NPAGE) {
1309       motion = 10;
1310     }
1311
1312     else if(key == KEY_PPAGE) {
1313       motion = -10;
1314     }
1315
1316     else if(key == KEY_DOWN ||
1317             key == '\016') { /* ^N */
1318       motion = 1;
1319     }
1320
1321     else if(key == KEY_UP ||
1322             key == '\020') { /* ^P */
1323       motion = -1;
1324     }
1325
1326     else if(key == KEY_LEFT ||
1327             key == '\002') { /* ^B */
1328       if(cursor_position > 0) cursor_position--;
1329       else error_feedback();
1330     }
1331
1332     else if(key == KEY_RIGHT ||
1333             key == '\006') { /* ^F */
1334       if(pattern[cursor_position]) cursor_position++;
1335       else error_feedback();
1336     }
1337
1338     else if(key == '\001') { /* ^A */
1339       cursor_position = 0;
1340     }
1341
1342     else if(key == '\005') { /* ^E */
1343       cursor_position = strlen(pattern);
1344     }
1345
1346     else if(key == '\022') { /* ^R */
1347       use_regexp = !use_regexp;
1348     }
1349
1350     else if(key == '\011') { /* ^I */
1351       case_sensitive = !case_sensitive;
1352     }
1353
1354     else if(key == '\025') { /* ^U */
1355       kill_before_cursor(pattern, &cursor_position);
1356     }
1357
1358     else if(key == '\013') { /* ^K */
1359       kill_after_cursor(pattern, &cursor_position);
1360     }
1361
1362     else if(key == '\014') { /* ^L */
1363       /* I suspect that we may sometime mess up the display, so ^L is
1364          here to force a full refresh */
1365       clear();
1366     }
1367
1368     else if(key == '\007' || /* ^G */
1369             key == '\033' || /* ^[ (escape) */
1370             key == '\n' ||
1371             key == KEY_ENTER) {
1372       done = 1;
1373     }
1374
1375     else if(key == KEY_RESIZE || key == -1) {
1376       /* Do nothing when the tty is resized */
1377     }
1378
1379     else {
1380       /* Unknown key */
1381       error_feedback();
1382     }
1383
1384     update_screen(&current_focus_line, &displayed_focus_line,
1385                   motion,
1386                   nb_lines, labels, cursor_position, pattern);
1387
1388   } while(!done);
1389
1390   echo();
1391   endwin();
1392
1393   /* Here we come back to standard display */
1394
1395   if(key == KEY_ENTER || key == '\n') {
1396
1397     char *t;
1398
1399     if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1400       t = lines[displayed_focus_line];
1401       if(label_separator) {
1402         while(*t && *t != label_separator) t++;
1403         if(*t) t++;
1404       }
1405     } else {
1406       t = 0;
1407     }
1408
1409     if(output_to_vt_buffer && t) {
1410       inject_into_tty_buffer(t, add_control_qs);
1411     }
1412
1413     if(output_filename[0]) {
1414       FILE *out = fopen(output_filename, "w");
1415       if(out) {
1416         if(t) {
1417           fprintf(out, "%s", t);
1418         }
1419         fprintf(out, "\n");
1420       } else {
1421         fprintf(stderr,
1422                 "selector: Cannot open %s for writing.\n",
1423                 output_filename);
1424         exit(EXIT_FAILURE);
1425       }
1426       fclose(out);
1427     }
1428
1429   } else {
1430     printf("Aborted.\n");
1431   }
1432
1433   for(l = 0; l < nb_lines; l++) {
1434     free(lines[l]);
1435     free(labels[l]);
1436   }
1437
1438   free(labels);
1439   free(lines);
1440   free(title);
1441
1442   exit(EXIT_SUCCESS);
1443 }