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