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