免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 923 | 回复: 0
打印 上一主题 下一主题

GNU readline [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-15 19:42 |只看该作者 |倒序浏览
GNU readline implement filename auto-complete by default, it will list all the files in the current directory. We can disable it by binds our TAB key to some other operation. In 
previous post
, I simply abort the operation to ignore users hitting TABs.
Auto-complete are useful if only we can customize it. Well, readline allows us do it by assign our own callback functions. First of all, you may want to read up the manual from 
HERE
. It does provides a c sample codes as well but I find it too complicated, here I provide a simplified version that can be compiled under c++.
view plain
print
?
#include   #include   #include   #include     static char** my_completion(const char*, int ,int);  char* my_generator(const char*,int);  char * dupstr (char*);  void *xmalloc (int);    char* cmd [] ={ "hello", "world", "hell" ,"word", "quit", " " };    int main()  {      char *buf;        rl_attempted_completion_function = my_completion;        while((buf = readline("\n >> "))!=NULL) {          //enable auto-complete          rl_bind_key('\t',rl_complete);            printf("cmd [%s]\n",buf);          if (strcmp(buf,"quit")==0)              break;          if (buf[0]!=0)              add_history(buf);      }        free(buf);        return 0;  }      static char** my_completion( const char * text , int start,  int end)  {      char **matches;        matches = (char **)NULL;        if (start == 0)          matches = rl_completion_matches ((char*)text, &my_generator);      else          rl_bind_key('\t',rl_abort);        return (matches);    }    char* my_generator(const char* text, int state)  {      static int list_index, len;      char *name;        if (!state) {          list_index = 0;          len = strlen (text);      }          while (name = cmd[list_index]) {          list_index++;            if (strncmp (name, text, len) == 0)              return (dupstr(name));      }        /* If no names matched, then return NULL. */      return ((char *)NULL);    }    char * dupstr (char* s) {    char *r;      r = (char*) xmalloc ((strlen (s) + 1));    strcpy (r, s);    return (r);  }    void * xmalloc (int size)  {      void *buf;        buf = malloc (size);      if (!buf) {          fprintf (stderr, "Error: Out of memory. Exiting.'n");          exit (1);      }        return buf;  }  
http://www.math.utah.edu/docs/info/rlman_2.html#SEC36
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/79955/showart_1864025.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP