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