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