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