Added a label separator. Only the part of the line before it is shown.
[selector.git] / selector.cc
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 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 // To use it as a super-history-search for bash:
26 // alias h='selector -d -i -b -v -f <(history)'
27
28 #include <fstream>
29 #include <iostream>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ncurses.h>
35 #include <fcntl.h>
36 #include <sys/ioctl.h>
37 #include <termios.h>
38 #include <regex.h>
39
40 using namespace std;
41
42 #define VERSION "1.0"
43
44 const int buffer_size = 4096;
45
46 // Yeah, global variables!
47
48 int nb_lines_max = 1000;
49 char pattern_separator = ';';
50 char label_separator = '\0';
51 int output_to_vt_buffer = 0;
52 int add_control_qs = 0;
53 int with_colors = 1;
54 int zsh_history = 0, bash_history = 0;
55 int inverse_order = 0;
56 int remove_duplicates = 0;
57 int use_regexp = 0;
58 int case_sensitive = 0;
59 char *title = 0;
60 int error_flash = 0;
61
62 #define COLOR_MODELINE 1
63 #define COLOR_HIGHLIGHTED_LINE 2
64
65 //////////////////////////////////////////////////////////////////////
66
67 void inject_into_tty_buffer(char *string) {
68   struct termios oldtio, newtio;
69   tcgetattr(STDIN_FILENO, &oldtio);
70   memset(&newtio, 0, sizeof(newtio));
71   // Set input mode (non-canonical, *no echo*,...)
72   tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
73   // Put the selected string in the tty input buffer
74   char control_q = '\021';
75   for(char *k = string; *k; k++) {
76     if(add_control_qs) {
77       ioctl(STDIN_FILENO, TIOCSTI, &control_q);
78     }
79     ioctl(STDIN_FILENO, TIOCSTI, k);
80   }
81   // Restore the old settings
82   tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
83 }
84
85 //////////////////////////////////////////////////////////////////////
86
87 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
88   if(n_opt + n >= argc) {
89     cerr << "Missing argument for " << argv[n_opt] << "."
90          << " "
91          << "Expecting " << help << "."
92          << endl;
93     exit(1);
94   }
95 }
96
97 int string_to_positive_integer(char *string) {
98   int error = 0;
99   int result = 0;
100
101   if(*string) {
102     for(char *s = string; *s; s++) {
103       if(*s >= '0' && *s <= '9') {
104         result = result * 10 + int(*s - '0');
105       } else error = 1;
106     }
107   } else error = 1;
108
109   if(error) {
110     cerr << "Value `" << string << "' is not a positive integer." << endl;
111     exit(1);
112   }
113
114   return result;
115 }
116
117 void error_feedback() {
118   if(error_flash) {
119     flash();
120   } else {
121     beep();
122   }
123 }
124
125 //////////////////////////////////////////////////////////////////////
126 // A quick and dirty hash table
127
128 // The table itself stores index of the strings in a char
129 // **table. When a string is added, if it was already in the table,
130 // the new index replaces the previous one.
131
132 int *new_hash_table(int hash_table_size) {
133   int *result;
134   result = new int[hash_table_size];
135   for(int k = 0; k < hash_table_size; k++) {
136     result[k] = -1;
137   }
138   return result;
139 }
140
141 // Adds new_string in the table, associated to new_index. If this
142 // string was not already in the table, returns -1. Otherwise, returns
143 // the previous index it had.
144
145 int test_and_add(char *new_string, int new_index,
146                  char **strings, int *hash_table, int hash_table_size) {
147
148   unsigned int code = 0;
149
150   // This is my recipe. I checked, it seems to work (as long as
151   // hash_table_size is not a multiple of 387433 that should be okay)
152
153   for(int k = 0; new_string[k]; k++) {
154     code = code * 387433 + (unsigned int) (new_string[k]);
155   }
156
157   code = code % hash_table_size;
158
159   while(hash_table[code] >= 0) {
160     // There is a string with that code
161     if(strcmp(new_string, strings[hash_table[code]]) == 0) {
162       // It is the same string, we keep a copy of the stored index
163       int result = hash_table[code];
164       // Put the new one
165       hash_table[code] = new_index;
166       // And return the previous one
167       return result;
168     }
169     // This collision was not the same string, let's move to the next
170     // in the table
171     code = (code + 1) % hash_table_size;
172   }
173
174   // This string was not already in there, store the index in the
175   // table and return -1
176   hash_table[code] = new_index;
177   return -1;
178 }
179
180 //////////////////////////////////////////////////////////////////////
181 // A matcher matches either with a collection of substrings, or with a
182 // regexp
183
184 struct matcher_t {
185   regex_t preg;
186   int regexp_error;
187   int nb_patterns;
188   int case_sensitive;
189   char *splitted_patterns, **patterns;
190 };
191
192 int match(char *string, matcher_t *matcher) {
193   if(matcher->nb_patterns >= 0) {
194     if(matcher->case_sensitive) {
195       for(int n = 0; n < matcher->nb_patterns; n++) {
196         if(strstr(string, matcher->patterns[n]) == 0) return 0;
197       }
198     } else {
199       for(int n = 0; n < matcher->nb_patterns; n++) {
200         if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
201       }
202     }
203     return 1;
204   } else {
205     return regexec(&matcher->preg, string, 0, 0, 0) == 0;
206   }
207 }
208
209 void free_matcher(matcher_t *matcher) {
210   if(matcher->nb_patterns < 0) {
211     if(!matcher->regexp_error) regfree(&matcher->preg);
212   } else {
213     delete[] matcher->splitted_patterns;
214     delete[] matcher->patterns;
215   }
216 }
217
218 void initialize_matcher(int use_regexp, int case_sensitive,
219                         matcher_t *matcher, const char *pattern) {
220
221   if(use_regexp) {
222     matcher->nb_patterns = -1;
223     matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
224   } else {
225     matcher->regexp_error = 0;
226     matcher->nb_patterns = 1;
227     matcher->case_sensitive = case_sensitive;
228
229     for(const char *s = pattern; *s; s++) {
230       if(*s == pattern_separator) {
231         matcher->nb_patterns++;
232       }
233     }
234
235     matcher->splitted_patterns = new char[strlen(pattern) + 1];
236     matcher->patterns = new char*[matcher->nb_patterns];
237
238     strcpy(matcher->splitted_patterns, pattern);
239
240     int n = 0;
241     char *last_pattern_start = matcher->splitted_patterns;
242     for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
243       if(*s == pattern_separator || *s == '\0') {
244         *s = '\0';
245         matcher->patterns[n++] = last_pattern_start;
246         last_pattern_start = s + 1;
247       }
248     }
249   }
250 }
251
252 //////////////////////////////////////////////////////////////////////
253 // Buffer edition
254
255 void delete_char(char *buffer, int *position) {
256   if(buffer[*position]) {
257     int c = *position;
258     while(c < buffer_size && buffer[c]) {
259       buffer[c] = buffer[c+1];
260       c++;
261     }
262   } else error_feedback();
263 }
264
265 void backspace_char(char *buffer, int *position) {
266   if(*position > 0) {
267     if(buffer[*position]) {
268       int c = *position - 1;
269       while(buffer[c]) {
270         buffer[c] = buffer[c+1];
271         c++;
272       }
273     } else {
274       buffer[*position - 1] = '\0';
275     }
276
277     (*position)--;
278   } else error_feedback();
279 }
280
281 void insert_char(char *buffer, int *position, char character) {
282   if(strlen(buffer) < buffer_size - 1) {
283     int c = *position;
284     char t = buffer[c], u;
285     while(t) {
286       c++;
287       u = buffer[c];
288       buffer[c] = t;
289       t = u;
290     }
291     c++;
292     buffer[c] = '\0';
293     buffer[(*position)++] = character;
294   } else error_feedback();
295 }
296
297 void kill_before_cursor(char *buffer, int *position) {
298   int s = 0;
299   while(buffer[*position + s]) {
300     buffer[s] = buffer[*position + s];
301     s++;
302   }
303   buffer[s] = '\0';
304   *position = 0;
305 }
306
307 void kill_after_cursor(char *buffer, int *position) {
308   buffer[*position] = '\0';
309 }
310
311 //////////////////////////////////////////////////////////////////////
312
313 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
314   int line = current_line - 1;
315   while(line >= 0 && !match(lines[line], matcher)) line--;
316   return line;
317 }
318
319 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
320   int line = current_line + 1;
321   while(line < nb_lines && !match(lines[line], matcher)) line++;
322
323   if(line < nb_lines)
324     return line;
325   else
326     return -1;
327 }
328
329 //////////////////////////////////////////////////////////////////////
330
331 void update_screen(int *current_line, int *temporary_line, int motion,
332                    int nb_lines, char **lines,
333                    int cursor_position,
334                    char *pattern) {
335
336   char buffer[buffer_size];
337   matcher_t matcher;
338
339   initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
340
341   // We now take care of printing the lines per se
342
343   int console_width = getmaxx(stdscr);
344   int console_height = getmaxy(stdscr);
345
346   // First, we find a visible line. In priority: The current, or the
347   // first visible after it, or the first visible before it.
348
349   int nb_printed_lines = 0;
350
351   clear();
352   use_default_colors();
353   addstr("\n");
354
355   if(matcher.regexp_error) {
356     addstr("[regexp error]");
357   } else if(nb_lines > 0) {
358     int new_line;
359     if(match(lines[*current_line], &matcher)) {
360       new_line = *current_line;
361     } else {
362       new_line = next_visible(*current_line, nb_lines, lines, &matcher);
363       if(new_line < 0) {
364         new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
365       }
366     }
367
368     // If we found a visible line and we should move, let's move
369
370     if(new_line >= 0 && motion != 0) {
371       int l = new_line;
372       if(motion > 0) {
373         // We want to go down, let's find the first visible line below
374         for(int m = 0; l >= 0 && m < motion; m++) {
375           l = next_visible(l, nb_lines, lines, &matcher);
376           if(l >= 0) {
377             new_line = l;
378           }
379         }
380       } else {
381         // We want to go up, let's find the first visible line above
382         for(int m = 0; l >= 0 && m < -motion; m++) {
383           l = previous_visible(l, nb_lines, lines, &matcher);
384           if(l >= 0) {
385             new_line = l;
386           }
387         }
388       }
389     }
390
391     // Here new_line is either a line number matching the patterns, or -1
392
393     if(new_line >= 0) {
394
395       int first_line = new_line, last_line = new_line, nb_match = 1;
396
397       // We find the first and last line to show, so that the total of
398       // visible lines between them (them included) is console_height-1
399
400       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
401
402         if(first_line > 0) {
403           first_line--;
404           while(first_line > 0 && !match(lines[first_line], &matcher)) {
405             first_line--;
406           }
407           if(match(lines[first_line], &matcher)) {
408             nb_match++;
409           }
410         }
411
412         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
413           last_line++;
414           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
415             last_line++;
416           }
417
418           if(match(lines[last_line], &matcher)) {
419             nb_match++;
420           }
421         }
422       }
423
424       // Now we display them
425
426       for(int l = first_line; l <= last_line; l++) {
427         if(match(lines[l], &matcher)) {
428           int k = 0;
429
430           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
431             buffer[k] = lines[l][k];
432             k++;
433           }
434
435           // We fill the rest of the line with blanks if this is the
436           // highlighted line
437
438           if(l == new_line) {
439             while(k < console_width) {
440               buffer[k++] = ' ';
441             }
442           }
443
444           buffer[k++] = '\n';
445           buffer[k++] = '\0';
446
447           // Highlight the highlighted line ...
448
449           if(l == new_line) {
450             if(with_colors) {
451               attron(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
452               addnstr(buffer, console_width);
453               attroff(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
454             } else {
455               attron(A_STANDOUT);
456               addnstr(buffer, console_width);
457               attroff(A_STANDOUT);
458             }
459           } else {
460             addnstr(buffer, console_width);
461           }
462
463           nb_printed_lines++;
464         }
465       }
466
467       if(motion != 0) {
468         *current_line = new_line;
469       }
470     }
471
472     *temporary_line = new_line;
473
474     if(nb_printed_lines == 0) {
475       addnstr("[no selection]\n", console_width);
476     }
477   } else {
478     addnstr("[empty choice]\n", console_width);
479   }
480
481   // Draw the modeline
482
483   move(0, 0);
484
485   if(with_colors) {
486     attron(COLOR_PAIR(COLOR_MODELINE));
487   } else {
488     attron(A_REVERSE);
489   }
490
491   for(int k = 0; k < console_width; k++) buffer[k] = ' ';
492   buffer[console_width] = '\0';
493   addnstr(buffer, console_width);
494
495   move(0, 0);
496
497   // There must be a more elegant way of moving the cursor at a
498   // location met during display
499
500   int cursor_x = 0;
501
502   if(title) {
503     addstr(title);
504     addstr(" ");
505     cursor_x += strlen(title) + 1;
506   }
507
508   sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
509   addstr(buffer);
510   cursor_x += strlen(buffer);
511
512   addnstr(pattern, cursor_position);
513   cursor_x += cursor_position;
514
515   if(pattern[cursor_position]) {
516     addstr(pattern + cursor_position);
517   } else {
518     addstr(" ");
519   }
520
521   if(use_regexp || case_sensitive) {
522     addstr(" [");
523     if(use_regexp) {
524       addstr("regexp");
525     }
526
527     if(case_sensitive) {
528       if(use_regexp) {
529         addstr(",");
530       }
531       addstr("case");
532     }
533     addstr("]");
534   }
535
536   move(0, cursor_x);
537
538   if(with_colors) {
539     attroff(COLOR_PAIR(COLOR_MODELINE));
540   } else {
541     attroff(A_REVERSE);
542   }
543
544   // We are done
545
546   refresh();
547   free_matcher(&matcher);
548 }
549
550 //////////////////////////////////////////////////////////////////////
551
552 void read_file(const char *input_filename,
553                int nb_lines_max, int *nb_lines, char **lines,
554                int hash_table_size, int *hash_table) {
555
556   char raw_line[buffer_size];;
557
558   ifstream file(input_filename);
559
560   if(file.fail()) {
561     cerr << "Can not open " << input_filename << endl;
562     exit(1);
563   }
564
565   while(*nb_lines < nb_lines_max && !file.eof()) {
566
567     file.getline(raw_line, buffer_size);
568
569     if(raw_line[0]) {
570
571       if(file.fail()) {
572         cerr << "Line too long:" << endl;
573         cerr << raw_line << endl;
574         exit(1);
575       }
576
577       char *t;
578
579       t = raw_line;
580
581       // Remove the zsh history prefix
582
583       if(zsh_history && *t == ':') {
584         while(*t && *t != ';') t++;
585         if(*t == ';') t++;
586       }
587
588       // Remove the bash history prefix
589
590       if(bash_history) {
591         while(*t == ' ') t++;
592         while(*t >= '0' && *t <= '9') t++;
593         while(*t == ' ') t++;
594       }
595
596       // Check for duplicates with the hash table and insert the line
597       // in the list if necessary
598
599       int dup;
600
601       if(hash_table) {
602         dup = test_and_add(t, *nb_lines, lines, hash_table, hash_table_size);
603       } else {
604         dup = -1;
605       }
606
607       if(dup < 0) {
608         lines[*nb_lines] = new char[strlen(t) + 1];
609         strcpy(lines[*nb_lines], t);
610       } else {
611         // The string was already in there, so we do not allocate a
612         // new string but use the pointer to the first occurence of it
613         lines[*nb_lines] = lines[dup];
614         lines[dup] = 0;
615       }
616
617       (*nb_lines)++;
618     }
619   }
620 }
621
622 //////////////////////////////////////////////////////////////////////
623
624 int main(int argc, char **argv) {
625
626   if(!ttyname(STDIN_FILENO)) {
627     cerr << "The standard input is not a tty." << endl;
628     exit(1);
629   }
630
631   int color_fg_modeline, color_bg_modeline;
632   int color_fg_highlight, color_bg_highlight;
633
634   color_fg_modeline  = COLOR_WHITE;
635   color_bg_modeline  = COLOR_BLACK;
636   color_fg_highlight = COLOR_BLACK;
637   color_bg_highlight = COLOR_YELLOW;
638
639   setlocale(LC_ALL, "");
640
641   char input_filename[buffer_size], output_filename[buffer_size];
642
643   strcpy(input_filename, "");
644   strcpy(output_filename, "");
645
646   int i = 1;
647   int error = 0, show_help = 0;
648   int rest_are_files = 0;
649
650   while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
651
652     if(strcmp(argv[i], "-o") == 0) {
653       check_opt(argc, argv, i, 1, "<output filename>");
654       strncpy(output_filename, argv[i+1], buffer_size);
655       i += 2;
656     }
657
658     else if(strcmp(argv[i], "-s") == 0) {
659       check_opt(argc, argv, i, 1, "<pattern separator>");
660       pattern_separator = argv[i+1][0];
661       i += 2;
662     }
663
664     else if(strcmp(argv[i], "-x") == 0) {
665       check_opt(argc, argv, i, 1, "<label separator>");
666       label_separator = argv[i+1][0];
667       i += 2;
668     }
669
670     else if(strcmp(argv[i], "-v") == 0) {
671       output_to_vt_buffer = 1;
672       i++;
673     }
674
675     else if(strcmp(argv[i], "-w") == 0) {
676       add_control_qs = 1;
677       i++;
678     }
679
680     else if(strcmp(argv[i], "-m") == 0) {
681       with_colors = 0;
682       i++;
683     }
684
685     else if(strcmp(argv[i], "-q") == 0) {
686       error_flash = 1;
687       i++;
688     }
689
690     else if(strcmp(argv[i], "-f") == 0) {
691       check_opt(argc, argv, i, 1, "<input filename>");
692       strncpy(input_filename, argv[i+1], buffer_size);
693       i += 2;
694     }
695
696     else if(strcmp(argv[i], "-i") == 0) {
697       inverse_order = 1;
698       i++;
699     }
700
701     else if(strcmp(argv[i], "-b") == 0) {
702       bash_history = 1;
703       i++;
704     }
705
706     else if(strcmp(argv[i], "-z") == 0) {
707       zsh_history = 1;
708       i++;
709     }
710
711     else if(strcmp(argv[i], "-d") == 0) {
712       remove_duplicates = 1;
713       i++;
714     }
715
716     else if(strcmp(argv[i], "-e") == 0) {
717       use_regexp = 1;
718       i++;
719     }
720
721     else if(strcmp(argv[i], "-a") == 0) {
722       case_sensitive = 1;
723       i++;
724     }
725
726     else if(strcmp(argv[i], "-t") == 0) {
727       check_opt(argc, argv, i, 1, "<title>");
728       delete[] title;
729       title = new char[strlen(argv[i+1]) + 1];
730       strcpy(title, argv[i+1]);
731       i += 2;
732     }
733
734     else if(strcmp(argv[i], "-l") == 0) {
735       check_opt(argc, argv, i, 1, "<maximum number of lines>");
736       nb_lines_max = string_to_positive_integer(argv[i+1]);
737       i += 2;
738     }
739
740     else if(strcmp(argv[i], "-c") == 0) {
741       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
742       color_fg_modeline = string_to_positive_integer(argv[i + 1]);
743       color_bg_modeline = string_to_positive_integer(argv[i + 2]);
744       color_fg_highlight = string_to_positive_integer(argv[i + 3]);
745       color_bg_highlight = string_to_positive_integer(argv[i + 4]);
746       i += 5;
747     }
748
749     else if(strcmp(argv[i], "--") == 0) {
750       rest_are_files = 1;
751       i++;
752     }
753
754     else if(strcmp(argv[i], "-h") == 0) {
755       show_help = 1;
756       i++;
757     }
758
759     else {
760       cerr << "Unknown option " << argv[i] << "." << endl;
761       error = 1;
762     }
763   }
764
765   if(show_help || error) {
766     cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
767          << endl
768          << "Written by Francois Fleuret <francois@fleuret.org>."
769          << endl
770          << endl
771          << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
772          << endl
773          << " -h      show this help" << endl
774          << " -v      inject the selected line in the tty" << endl
775          << " -d      remove duplicated lines" << endl
776          << " -b      remove the bash history line prefix" << endl
777          << " -z      remove the zsh history line prefix" << endl
778          << " -i      invert the order of lines" << endl
779          << " -e      start in regexp mode" << endl
780          << " -a      case sensitive" << endl
781          << " -m      monochrome mode" << endl
782          << " -q      make a flash instead of a beep on an edition error" << endl
783          << " --      rest of the arguments are filenames" << endl
784          << " -t <title>" << endl
785          << "         add a title in the modeline" << endl
786          << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
787          << "         set the display colors" << endl
788          << " -o <output filename>" << endl
789          << "         set a file to write the selected line to" << endl
790          << " -s <pattern separator>" << endl
791          << "         set the symbol to separate substrings in the pattern" << endl
792          << " -x <label separator>" << endl
793          << "         set the symbol to terminate the label" << endl
794          << " -l <max number of lines>" << endl
795          << "         set the maximum number of lines to take into account" << endl
796          << endl;
797
798     exit(error);
799   }
800
801   char **lines = new char *[nb_lines_max];
802
803   int nb_lines = 0;
804   int hash_table_size = nb_lines_max * 10;
805   int *hash_table = 0;
806
807   if(remove_duplicates) {
808     hash_table = new_hash_table(hash_table_size);
809   }
810
811   if(input_filename[0]) {
812     read_file(input_filename,
813               nb_lines_max, &nb_lines, lines,
814               hash_table_size, hash_table);
815   }
816
817   while(i < argc) {
818     read_file(argv[i],
819               nb_lines_max, &nb_lines, lines,
820               hash_table_size, hash_table);
821     i++;
822   }
823
824   delete[] hash_table;
825
826   // Now remove the null strings
827
828   int n = 0;
829   for(int k = 0; k < nb_lines; k++) {
830     if(lines[k]) {
831       lines[n++] = lines[k];
832     }
833   }
834
835   nb_lines = n;
836
837   if(inverse_order) {
838     for(int i = 0; i < nb_lines / 2; i++) {
839       char *s = lines[nb_lines - 1 - i];
840       lines[nb_lines - 1 - i] = lines[i];
841       lines[i] = s;
842     }
843   }
844
845   // Build the labels from the strings, take only the part before the
846   // label_separator and transform control characters to printable
847   // ones
848
849   char **labels = new char *[nb_lines];
850   for(int l = 0; l < nb_lines; l++) {
851     char *s, *t;
852     const char *u;
853     t = lines[l];
854     int e = 0;
855     while(*t && *t != label_separator) {
856       u = unctrl(*t++);
857       e += strlen(u);
858     }
859     labels[l] = new char[e + 1];
860     t = lines[l];
861     s = labels[l];
862     while(*t && *t != label_separator) {
863       u = unctrl(*t++);
864       while(*u) { *s++ = *u++; }
865     }
866     *s = '\0';
867   }
868
869   char pattern[buffer_size];
870   pattern[0] = '\0';
871   int cursor_position;
872   cursor_position = 0;
873
874   //////////////////////////////////////////////////////////////////////
875   // Here we start to display with curse
876
877   initscr();
878
879   noecho();
880
881   // So that the arrow keys work
882   keypad(stdscr, TRUE);
883
884   if(with_colors) {
885
886     if(has_colors()) {
887
888       start_color();
889
890       if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
891          color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
892          color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
893          color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
894         echo();
895         endwin();
896         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
897         exit(1);
898       }
899
900       init_pair(COLOR_MODELINE, color_fg_modeline, color_bg_modeline);
901       init_pair(COLOR_HIGHLIGHTED_LINE, color_fg_highlight, color_bg_highlight);
902
903     } else {
904       with_colors = 0;
905     }
906   }
907
908   int key;
909   int current_line = 0, temporary_line = 0;
910
911   update_screen(&current_line, &temporary_line, 0, nb_lines, labels, cursor_position, pattern);
912
913   do {
914
915     key = getch();
916
917     int motion = 0;
918
919     if(key >= ' ' && key <= '~') { // Insert character
920       insert_char(pattern, &cursor_position, key);
921     }
922
923     else if(key == KEY_BACKSPACE ||
924             key == '\010' || // ^H
925             key == '\177') { // ^?
926       backspace_char(pattern, &cursor_position);
927     }
928
929     else if(key == KEY_DC ||
930             key == '\004') { // ^D
931       delete_char(pattern, &cursor_position);
932     }
933
934     else if(key == KEY_HOME) {
935       current_line = 0;
936     }
937
938     else if(key == KEY_END) {
939       current_line = nb_lines - 1;
940     }
941
942     else if(key == KEY_NPAGE) {
943       motion = 10;
944     }
945
946     else if(key == KEY_PPAGE) {
947       motion = -10;
948     }
949
950     else if(key == KEY_DOWN ||
951             key == '\016') { // ^N
952       motion = 1;
953     }
954
955     else if(key == KEY_UP ||
956             key == '\020') { // ^P
957       motion = -1;
958     }
959
960     else if(key == KEY_LEFT ||
961             key == '\002') { // ^B
962       if(cursor_position > 0) cursor_position--;
963       else error_feedback();
964     }
965
966     else if(key == KEY_RIGHT ||
967             key == '\006') { // ^F
968       if(pattern[cursor_position]) cursor_position++;
969       else error_feedback();
970     }
971
972     else if(key == '\001') { // ^A
973       cursor_position = 0;
974     }
975
976     else if(key == '\005') { // ^E
977       cursor_position = strlen(pattern);
978     }
979
980     else if(key == '\022') { // ^R
981       use_regexp = !use_regexp;
982     }
983
984     else if(key == '\011') { // ^I
985       case_sensitive = !case_sensitive;
986     }
987
988     else if(key == '\025') { // ^U
989       kill_before_cursor(pattern, &cursor_position);
990     }
991
992     else if(key == '\013') { // ^K
993       kill_after_cursor(pattern, &cursor_position);
994     }
995
996     update_screen(&current_line, &temporary_line, motion,
997                   nb_lines, labels, cursor_position, pattern);
998
999   } while(key != '\007' && // ^G
1000           key != '\033' && // ^[ (escape)
1001           key != '\n' &&
1002           key != KEY_ENTER);
1003
1004   echo();
1005   endwin();
1006
1007   //////////////////////////////////////////////////////////////////////
1008   // Here we come back to standard display
1009
1010   if((key == KEY_ENTER || key == '\n')) {
1011
1012     if(output_to_vt_buffer) {
1013       if(temporary_line >= 0 && temporary_line < nb_lines) {
1014         inject_into_tty_buffer(lines[temporary_line]);
1015       }
1016     }
1017
1018     if(output_filename[0]) {
1019       ofstream out(output_filename);
1020       if(out.fail()) {
1021         cerr << "Can not open " << output_filename << " for writing." << endl;
1022         exit(1);
1023       } else {
1024         if(temporary_line >= 0 && temporary_line < nb_lines) {
1025           out << lines[temporary_line] << endl;
1026         } else {
1027           out << endl;
1028         }
1029       }
1030       out.flush();
1031     }
1032   } else {
1033     cout << "Aborted." << endl;
1034   }
1035
1036   for(int l = 0; l < nb_lines; l++) {
1037     delete[] lines[l];
1038     delete[] labels[l];
1039   }
1040
1041   delete[] labels;
1042   delete[] lines;
1043   delete[] title;
1044
1045   exit(0);
1046 }