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