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