Merge branch 'master' of ssh://fleuret@login.idiap.ch/homes/fleuret/public/git/selector
[selector.git] / selector.cc
index 7422fd6..9c863a4 100644 (file)
  */
 
 // To use it as a super-history-search for bash:
-//
 // alias h='selector -d -i -b -v -f <(history)'
 
-// This software is highly Linux-specific, but I would be glad to get
-// patches to make it work on other OS
-
 #include <fstream>
 #include <iostream>
 
@@ -45,7 +41,7 @@ using namespace std;
 
 #define VERSION "1.0"
 
-const int buffer_size = 1024;
+const int buffer_size = 4096;
 
 // Yeah, global variables!
 
@@ -57,19 +53,19 @@ int zsh_history = 0, bash_history = 0;
 int inverse_order = 0;
 int remove_duplicates = 0;
 int use_regexp = 0;
+int case_sensitive = 0;
+char *title = 0;
 
 //////////////////////////////////////////////////////////////////////
 
-// This looks severely Linux-only ...
-
-void inject_into_tty_buffer(char *line) {
+void inject_into_tty_buffer(char *string) {
   struct termios oldtio, newtio;
-  tcgetattr(STDIN_FILENO,&oldtio);
+  tcgetattr(STDIN_FILENO, &oldtio);
   memset(&newtio, 0, sizeof(newtio));
   // Set input mode (non-canonical, *no echo*,...)
   tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
-  // Put the selected line in the tty input buffer
-  for(char *k = line; *k; k++) {
+  // Put the selected string in the tty input buffer
+  for(char *k = string; *k; k++) {
     ioctl(STDIN_FILENO, TIOCSTI, k);
   }
   // Restore the old settings
@@ -91,6 +87,10 @@ void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
 //////////////////////////////////////////////////////////////////////
 // A quick and dirty hash table
 
+// The table itself stores index of the strings in a char
+// **table. When a string is added, if it was already in the table,
+// the new index replaces the previous one.
+
 int *new_hash_table(int hash_table_size) {
   int *result;
   result = new int[hash_table_size];
@@ -100,6 +100,10 @@ int *new_hash_table(int hash_table_size) {
   return result;
 }
 
+// Adds new_string in the table, associated to new_index. If this
+// string was not already in the table, returns -1. Otherwise, returns
+// the previous index it had.
+
 int test_and_add(char *new_string, int new_index,
                  char **strings, int *hash_table, int hash_table_size) {
   unsigned int code = 0;
@@ -114,16 +118,23 @@ int test_and_add(char *new_string, int new_index,
   code = code % hash_table_size;
 
   while(hash_table[code] >= 0) {
+    // There is a string with that code
     if(strcmp(new_string, strings[hash_table[code]]) == 0) {
+      // It is the same string, we keep a copy of the stored index
       int result = hash_table[code];
+      // Put the new one
       hash_table[code] = new_index;
+      // And return the previous one
       return result;
     }
+    // This collision was not the same string, let's move to the next
+    // in the table
     code = (code + 1) % hash_table_size;
   }
 
+  // This string was not already in there, store the index in the
+  // table and return -1
   hash_table[code] = new_index;
-
   return -1;
 }
 
@@ -135,13 +146,20 @@ struct matcher_t {
   regex_t preg;
   int regexp_error;
   int nb_patterns;
+  int case_sensitive;
   char *splitted_patterns, **patterns;
 };
 
 int match(char *string, matcher_t *matcher) {
   if(matcher->nb_patterns >= 0) {
-    for(int n = 0; n < matcher->nb_patterns; n++) {
-      if(strstr(string, matcher->patterns[n]) == 0) return 0;
+    if(matcher->case_sensitive) {
+      for(int n = 0; n < matcher->nb_patterns; n++) {
+        if(strstr(string, matcher->patterns[n]) == 0) return 0;
+      }
+    } else {
+      for(int n = 0; n < matcher->nb_patterns; n++) {
+        if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
+      }
     }
     return 1;
   } else {
@@ -158,13 +176,14 @@ void free_matcher(matcher_t *matcher) {
   }
 }
 
-void initialize_matcher(int use_regexp, matcher_t *matcher, const char *pattern) {
+void initialize_matcher(int use_regexp, int case_sensitive, matcher_t *matcher, const char *pattern) {
   if(use_regexp) {
     matcher->nb_patterns = -1;
-    matcher->regexp_error = regcomp(&matcher->preg, pattern, REG_ICASE);
+    matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
   } else {
     matcher->regexp_error = 0;
     matcher->nb_patterns = 1;
+    matcher->case_sensitive = case_sensitive;
 
     for(const char *s = pattern; *s; s++) {
       if(*s == pattern_separator) {
@@ -216,7 +235,7 @@ void update_screen(int *current_line, int *temporary_line, int motion,
   char buffer[buffer_size];
   matcher_t matcher;
 
-  initialize_matcher(use_regexp, &matcher, pattern);
+  initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
 
   // We now take care of printing the lines per se
 
@@ -234,8 +253,7 @@ void update_screen(int *current_line, int *temporary_line, int motion,
 
   if(matcher.regexp_error) {
     addstr("[regexp error]");
-  } else {
-
+  } else if(nb_lines > 0) {
     int new_line;
     if(match(lines[*current_line], &matcher)) {
       new_line = *current_line;
@@ -355,15 +373,26 @@ void update_screen(int *current_line, int *temporary_line, int motion,
     if(nb_printed_lines == 0) {
       addnstr("[no selection]\n", console_width);
     }
+  } else {
+    addnstr("[empty choice]\n", console_width);
   }
 
   // Draw the modeline
 
-  sprintf(buffer, "%d/%d pattern: %s%s",
-          nb_printed_lines,
-          nb_lines,
-          pattern,
-          use_regexp ? " [regexp]" : "");
+  if(title) {
+    sprintf(buffer, "%s %d/%d pattern: %s%s",
+            title,
+            nb_printed_lines,
+            nb_lines,
+            pattern,
+            use_regexp ? " [regexp]" : "");
+  } else {
+    sprintf(buffer, "%d/%d pattern: %s%s",
+            nb_printed_lines,
+            nb_lines,
+            pattern,
+            use_regexp ? " [regexp]" : "");
+  }
 
   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
   buffer[console_width] = '\0';
@@ -388,7 +417,13 @@ void update_screen(int *current_line, int *temporary_line, int motion,
 //////////////////////////////////////////////////////////////////////
 
 int main(int argc, char **argv) {
-  char buffer[buffer_size];
+
+  if(!ttyname(STDIN_FILENO)) {
+    cerr << "The standard input is not a tty." << endl;
+    exit(1);
+  }
+
+  char buffer[buffer_size], raw_line[buffer_size];;
   int color_fg_modeline, color_bg_modeline;
   int color_fg_highlight, color_bg_highlight;
 
@@ -462,6 +497,19 @@ int main(int argc, char **argv) {
       i++;
     }
 
+    else if(strcmp(argv[i], "-a") == 0) {
+      case_sensitive = 1;
+      i++;
+    }
+
+    else if(strcmp(argv[i], "-t") == 0) {
+      check_opt(argc, argv, i, 1, "<title>");
+      delete[] title;
+      title = new char[strlen(argv[i+1]) + 1];
+      strcpy(title, argv[i+1]);
+      i += 2;
+    }
+
     else if(strcmp(argv[i], "-l") == 0) {
       check_opt(argc, argv, i, 1, "<maximum number of lines>");
       nb_lines_max = atoi(argv[i+1]);
@@ -494,20 +542,27 @@ int main(int argc, char **argv) {
          << "Written by Francois Fleuret <francois@fleuret.org>."
          << endl
          << endl
-         << argv[0]
-         << " [-h]"
-         << " [-v]"
-         << " [-m]"
-         << " [-d]"
-         << " [-e]"
-         << " [-b]"
-         << " [-z]"
-         << " [-i]"
-         << " [-c <fg modeline> <bg modeline> <fg highlight> <bg highlight>]"
-         << " [-o <output filename>]"
-         << " [-s <pattern separator>]"
-         << " [-l <max number of lines>]"
-         << " -f <input filename>"
+         << "Usage: " << argv[0] << " [options] -f <file>" << endl
+         << endl
+         << " -h      show this help" << endl
+         << " -v      inject the selected line in the tty" << endl
+         << " -d      remove duplicated lines" << endl
+         << " -b      remove the bash history line prefix" << endl
+         << " -z      remove the zsh history line prefix" << endl
+         << " -i      invert the order of lines" << endl
+         << " -e      start in regexp mode" << endl
+         << " -a      case sensitive" << endl
+         << " -m      monochrome mode" << endl
+         << " -t <title>" << endl
+         << "         add a title in the modeline" << endl
+         << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
+         << "         set the display colors" << endl
+         << " -o <output filename>" << endl
+         << "         set a file to write the selected line to" << endl
+         << " -s <pattern separator>" << endl
+         << "         set the symbol to separate substrings in the pattern" << endl
+         << " -l <max number of lines>" << endl
+         << "         set the maximum number of lines to take into account" << endl
          << endl;
 
     exit(error);
@@ -537,9 +592,29 @@ int main(int argc, char **argv) {
   }
 
   while(nb_lines < nb_lines_max && !file.eof()) {
-    file.getline(buffer, buffer_size);
-    if(strcmp(buffer, "") != 0) {
-      char *s = buffer;
+
+    file.getline(raw_line, buffer_size);
+
+    if(raw_line[0]) {
+
+      if(file.fail()) {
+        cerr << "Line too long:" << endl;
+        cerr << raw_line << endl;
+        exit(1);
+      }
+
+      char *s, *t;
+      const char *u;
+
+      s = buffer;
+      t = raw_line;
+      while(*t) {
+        u = unctrl(*t++);
+        while(*u) { *s++ = *u++; }
+      }
+      *s = '\0';
+
+      s = buffer;
 
       if(zsh_history && *s == ':') {
         while(*s && *s != ';') s++;
@@ -562,6 +637,8 @@ int main(int argc, char **argv) {
         lines[nb_lines] = new char[strlen(s) + 1];
         strcpy(lines[nb_lines], s);
       } else {
+        // The string was already in there, so we do not allocate a
+        // new string but use the pointer to the first occurence of it
         lines[nb_lines] = lines[dup];
         lines[dup] = 0;
       }
@@ -572,6 +649,8 @@ int main(int argc, char **argv) {
 
   delete[] hash_table;
 
+  // Now remove the null strings
+
   int n = 0;
   for(int k = 0; k < nb_lines; k++) {
     if(lines[k]) {
@@ -593,8 +672,19 @@ int main(int argc, char **argv) {
   int pattern_point;
   pattern_point = 0;
 
+  //////////////////////////////////////////////////////////////////////
+  // Here we start to display with curse
+
   initscr();
 
+  noecho();
+
+  // Hide the cursor
+  curs_set(0);
+
+  // So that the arrow keys work
+  keypad(stdscr, TRUE);
+
   if(with_colors) {
     if(has_colors()) {
       start_color();
@@ -615,10 +705,6 @@ int main(int argc, char **argv) {
     }
   }
 
-  noecho();
-  curs_set(0); // Hide the cursor
-  keypad(stdscr, TRUE); // So that the arrow keys work
-
   int key;
   int current_line = 0, temporary_line = 0;
 
@@ -685,6 +771,9 @@ int main(int argc, char **argv) {
   curs_set(1);
   endwin();
 
+  //////////////////////////////////////////////////////////////////////
+  // Here we come back to standard display
+
   if((key == KEY_ENTER || key == '\n')) {
 
     if(output_to_vt_buffer) {
@@ -715,6 +804,7 @@ int main(int argc, char **argv) {
   }
 
   delete[] lines;
+  delete[] title;
 
   exit(0);
 }