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