反向搜索的示例:
(reverse-i-search)`grep': git log | grep master
Run Code Online (Sandbox Code Playgroud)
查找建议的算法是什么?它的搜索空间从何而来?
对其源代码的指针将不胜感激。
反向搜索是GNU Readline库的一部分。Readline库方便了阅读线和编辑功能。完整的源代码可以在这里找到。
以下源代码段显示了如何确定历史记录的源文件:
/* Return the string that should be used in the place of this
filename. This only matters when you dont specify the
filename to read_history (), or write_history (). */
static char *
history_filename (filename)
const char *filename;
{
char *return_val;
const char *home;
int home_len;
return_val = filename ? savestring (filename) : (char *)NULL;
if (return_val)
return (return_val);
home = sh_get_env_value ("HOME");
#if defined (_WIN32)
if (home == 0)
home = sh_get_env_value ("APPDATA");
#endif
if (home == 0)
return (NULL);
else
home_len = strlen (home);
return_val = (char *)xmalloc (2 + home_len + 8); /* strlen(".history") == 8 */
strcpy (return_val, home);
return_val[home_len] = '/';
#if defined (__MSDOS__)
strcpy (return_val + home_len + 1, "_history");
#else
strcpy (return_val + home_len + 1, ".history");
#endif
return (return_val);
}
Run Code Online (Sandbox Code Playgroud)
savestring()在savestring.c中定义,filename如果定义了该字符串,它将简单地复制该字符串 。sh_get_env_value()使用用于获取环境值的getenv()函数(由提供<stdlib.h>)实现函数(请参见手册页getenv(3))。.bash_history或.history(NULL将在函数返回的情况下使用此文件)将用作在Linux系统上实现搜索的源。资料来源:histfile.c
HIST_ENTRY(历史记录列表)数组中。来自的数据.bash_history将添加到此数组。资料来源:history.c_rl_saved_line_for_history。_rl_search_cxt实例成员数组(cxt->lines[]),使用该成员数组进行搜索。使用_rl_isearch_dispatch()和_rl_search_getchar()功能执行实际搜索。
简短摘要:该算法逐个字符地读取输入,以决定应执行的操作。在没有中断的情况下,它将字符添加到搜索字符串中以在数组中搜索它。如果未找到该字符串,它将移至下一个元素,跳过再次找到的相同字符串,并且字符串的长度比搜索字符串的当前长度短。(请阅读default :以switch获取确切的详细信息_rl_isearch_dispatch())
如果找不到该字符串,则铃声会响起。否则,它将显示字符串,但实际上不会在历史记录列表中移动到用户接受位置的位置。